@celljs/ta-host 4.15.1 → 4.16.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 (53) hide show
  1. package/esm/node/exec-endpoint.d.ts +14 -0
  2. package/esm/node/exec-endpoint.js +48 -0
  3. package/esm/node/gateway-models.d.ts +38 -0
  4. package/esm/node/gateway-models.js +124 -0
  5. package/esm/node/index.d.ts +3 -0
  6. package/esm/node/index.js +3 -0
  7. package/esm/node/remote/cloud-hosts.d.ts +40 -0
  8. package/esm/node/remote/cloud-hosts.js +99 -0
  9. package/esm/node/remote/index.d.ts +1 -0
  10. package/esm/node/remote/index.js +1 -0
  11. package/esm/node/remote/pi-directories.d.ts +2 -1
  12. package/esm/node/remote/pi-directories.js +7 -2
  13. package/esm/node/remote/remote-hosts.d.ts +5 -0
  14. package/esm/node/remote/remote-hosts.js +71 -2
  15. package/esm/node/remote/remote-protocol.d.ts +2 -0
  16. package/esm/node/remote/remote-server-impl.d.ts +1 -0
  17. package/esm/node/remote/remote-server-impl.js +3 -0
  18. package/esm/node/team/team-calls.js +6 -0
  19. package/esm/node/usage/agent-activity.d.ts +13 -0
  20. package/esm/node/usage/agent-activity.js +84 -0
  21. package/esm/node/usage/index.d.ts +3 -0
  22. package/esm/node/usage/index.js +4 -0
  23. package/esm/node/usage/usage-reader.d.ts +28 -0
  24. package/esm/node/usage/usage-reader.js +159 -0
  25. package/esm/node/usage/usage-server-impl.d.ts +12 -0
  26. package/esm/node/usage/usage-server-impl.js +46 -0
  27. package/lib/node/exec-endpoint.d.ts +15 -0
  28. package/lib/node/exec-endpoint.js +51 -0
  29. package/lib/node/gateway-models.d.ts +39 -0
  30. package/lib/node/gateway-models.js +127 -0
  31. package/lib/node/index.d.ts +3 -0
  32. package/lib/node/index.js +3 -0
  33. package/lib/node/remote/cloud-hosts.d.ts +41 -0
  34. package/lib/node/remote/cloud-hosts.js +103 -0
  35. package/lib/node/remote/index.d.ts +1 -0
  36. package/lib/node/remote/index.js +1 -0
  37. package/lib/node/remote/pi-directories.d.ts +2 -1
  38. package/lib/node/remote/pi-directories.js +7 -2
  39. package/lib/node/remote/remote-hosts.d.ts +5 -0
  40. package/lib/node/remote/remote-hosts.js +71 -2
  41. package/lib/node/remote/remote-protocol.d.ts +2 -0
  42. package/lib/node/remote/remote-server-impl.d.ts +1 -0
  43. package/lib/node/remote/remote-server-impl.js +3 -0
  44. package/lib/node/team/team-calls.js +6 -0
  45. package/lib/node/usage/agent-activity.d.ts +14 -0
  46. package/lib/node/usage/agent-activity.js +87 -0
  47. package/lib/node/usage/index.d.ts +4 -0
  48. package/lib/node/usage/index.js +20 -0
  49. package/lib/node/usage/usage-reader.d.ts +29 -0
  50. package/lib/node/usage/usage-reader.js +163 -0
  51. package/lib/node/usage/usage-server-impl.d.ts +13 -0
  52. package/lib/node/usage/usage-server-impl.js +49 -0
  53. package/package.json +14 -10
@@ -0,0 +1,41 @@
1
+ import { ExecClient } from '@celljs/ta-exec';
2
+ /** The path of the exec server of ta serve (and, forwarded, of ta gateway): ExecEndpoint. */
3
+ export declare const TA_EXEC_PATH = "/api/exec";
4
+ export interface CloudHost {
5
+ name: string;
6
+ /** The http(s) address of the gateway or Ta service. */
7
+ url: string;
8
+ /** That of the account there: a sign-in of the gateway, or the access token of a Ta service. */
9
+ token: string;
10
+ addedAt: number;
11
+ }
12
+ export declare namespace CloudHostsUtil {
13
+ /** An address as one writes it: http(s), without a path, a query or credentials. */
14
+ function url(value: string): string;
15
+ /** The WebSocket of its exec server. */
16
+ function execUrl(url: string): string;
17
+ }
18
+ /**
19
+ * The cloud workspaces the user added (`<agent directory>/cloud-hosts.json`, readable by this user only, as their
20
+ * tokens are there), and a connection to each, made on its first call. Each connection fences the ones of
21
+ * before (its epoch is when it was made), as with `ta.exec.url`.
22
+ */
23
+ export declare class CloudHosts {
24
+ protected readonly dir: () => string;
25
+ protected readonly clients: Map<string, ExecClient>;
26
+ constructor(dir: () => string);
27
+ list(): CloudHost[];
28
+ get(name: string): CloudHost | undefined;
29
+ save(host: CloudHost): void;
30
+ remove(name: string): void;
31
+ /** A connection to its exec server, made once; undefined for a name not added. */
32
+ client(name: string): ExecClient | undefined;
33
+ /** What a connection to it would be, for a host not kept yet (checked before it is). */
34
+ static connect(host: Pick<CloudHost, 'url' | 'token'>): ExecClient;
35
+ connected(name: string): boolean;
36
+ /** Its connection ends; the next call connects again. */
37
+ drop(name: string): ExecClient | undefined;
38
+ protected file(): string;
39
+ protected write(hosts: CloudHost[]): void;
40
+ }
41
+ //# sourceMappingURL=cloud-hosts.d.ts.map
@@ -0,0 +1,103 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.CloudHosts = exports.CloudHostsUtil = exports.TA_EXEC_PATH = void 0;
4
+ const node_fs_1 = require("node:fs");
5
+ const node_path_1 = require("node:path");
6
+ const ta_exec_1 = require("@celljs/ta-exec");
7
+ const ta_protocol_1 = require("@celljs/ta-protocol");
8
+ /** The path of the exec server of ta serve (and, forwarded, of ta gateway): ExecEndpoint. */
9
+ exports.TA_EXEC_PATH = '/api/exec';
10
+ var CloudHostsUtil;
11
+ (function (CloudHostsUtil) {
12
+ /** An address as one writes it: http(s), without a path, a query or credentials. */
13
+ function url(value) {
14
+ let parsed;
15
+ try {
16
+ parsed = new URL(value.trim());
17
+ }
18
+ catch (_a) {
19
+ throw new Error(`${value} is not an address: write https://ta.example.com.`);
20
+ }
21
+ if ((parsed.protocol !== 'https:' && parsed.protocol !== 'http:') || parsed.username || parsed.password) {
22
+ throw new Error(`${value} is not an address of a Ta gateway: write https://ta.example.com.`);
23
+ }
24
+ return `${parsed.origin}${parsed.pathname.replace(/\/+$/, '')}`;
25
+ }
26
+ CloudHostsUtil.url = url;
27
+ /** The WebSocket of its exec server. */
28
+ function execUrl(url) {
29
+ return `${url.replace(/^http/, 'ws')}${exports.TA_EXEC_PATH}`;
30
+ }
31
+ CloudHostsUtil.execUrl = execUrl;
32
+ })(CloudHostsUtil || (exports.CloudHostsUtil = CloudHostsUtil = {}));
33
+ /**
34
+ * The cloud workspaces the user added (`<agent directory>/cloud-hosts.json`, readable by this user only, as their
35
+ * tokens are there), and a connection to each, made on its first call. Each connection fences the ones of
36
+ * before (its epoch is when it was made), as with `ta.exec.url`.
37
+ */
38
+ class CloudHosts {
39
+ constructor(dir) {
40
+ this.dir = dir;
41
+ this.clients = new Map();
42
+ }
43
+ list() {
44
+ try {
45
+ const value = JSON.parse((0, node_fs_1.readFileSync)(this.file(), 'utf8'));
46
+ return Array.isArray(value.hosts)
47
+ ? value.hosts.filter(host => ta_protocol_1.TaLocation.isCloudName(host === null || host === void 0 ? void 0 : host.name) && typeof host.url === 'string' && typeof host.token === 'string')
48
+ : [];
49
+ }
50
+ catch (_a) {
51
+ return [];
52
+ }
53
+ }
54
+ get(name) {
55
+ return this.list().find(host => host.name === name);
56
+ }
57
+ save(host) {
58
+ this.write([host, ...this.list().filter(other => other.name !== host.name)]);
59
+ }
60
+ remove(name) {
61
+ this.write(this.list().filter(other => other.name !== name));
62
+ }
63
+ /** A connection to its exec server, made once; undefined for a name not added. */
64
+ client(name) {
65
+ let client = this.clients.get(name);
66
+ if (!client) {
67
+ const host = this.get(name);
68
+ if (!host) {
69
+ return undefined;
70
+ }
71
+ client = CloudHosts.connect(host);
72
+ this.clients.set(name, client);
73
+ }
74
+ return client;
75
+ }
76
+ /** What a connection to it would be, for a host not kept yet (checked before it is). */
77
+ static connect(host) {
78
+ return new ta_exec_1.ExecClient({ connect: ta_exec_1.ExecClient.webSocket(CloudHostsUtil.execUrl(host.url), host.token), epoch: Date.now() });
79
+ }
80
+ connected(name) {
81
+ var _a;
82
+ var _b;
83
+ return (_b = (_a = this.clients.get(name)) === null || _a === void 0 ? void 0 : _a.connected) !== null && _b !== void 0 ? _b : false;
84
+ }
85
+ /** Its connection ends; the next call connects again. */
86
+ drop(name) {
87
+ const client = this.clients.get(name);
88
+ this.clients.delete(name);
89
+ return client;
90
+ }
91
+ file() {
92
+ return (0, node_path_1.join)(this.dir(), 'cloud-hosts.json');
93
+ }
94
+ write(hosts) {
95
+ const file = this.file();
96
+ const temporary = `${file}.${process.pid}.tmp`;
97
+ (0, node_fs_1.writeFileSync)(temporary, JSON.stringify({ hosts }, undefined, 2), { mode: 0o600 });
98
+ (0, node_fs_1.chmodSync)(temporary, 0o600);
99
+ (0, node_fs_1.renameSync)(temporary, file);
100
+ }
101
+ }
102
+ exports.CloudHosts = CloudHosts;
103
+ //# sourceMappingURL=cloud-hosts.js.map
@@ -1,3 +1,4 @@
1
+ export * from './cloud-hosts';
1
2
  export * from './pi-directories';
2
3
  export * from './port-forwards';
3
4
  export * from './remote-hosts';
@@ -14,6 +14,7 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
14
  for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
15
  };
16
16
  Object.defineProperty(exports, "__esModule", { value: true });
17
+ __exportStar(require("./cloud-hosts"), exports);
17
18
  __exportStar(require("./pi-directories"), exports);
18
19
  __exportStar(require("./port-forwards"), exports);
19
20
  __exportStar(require("./remote-hosts"), exports);
@@ -2,7 +2,8 @@ import { type CodingAgentOptions } from '@celljs/ai-coding-agent';
2
2
  import { type TaExecOptions } from '../host-protocol';
3
3
  import { PiDirectories } from './remote-protocol';
4
4
  /**
5
- * `<agent directory>/remote/ssh/<host>/<path>` for `ssh://<host>/<path>`. With `ta.exec.url` every
5
+ * `<agent directory>/remote/ssh/<host>/<path>` for `ssh://<host>/<path>`, `remote/ta/<name>/<path>` for a cloud
6
+ * workspace, `ta://<name>/<path>`. With `ta.exec.url` every
6
7
  * directory is one of the machine of the exec server: `<agent directory>/remote/exec/<path>`.
7
8
  */
8
9
  export declare class DefaultPiDirectories implements PiDirectories {
@@ -19,14 +19,16 @@ const ta_protocol_1 = require("@celljs/ta-protocol");
19
19
  const host_protocol_1 = require("../host-protocol");
20
20
  const remote_protocol_1 = require("./remote-protocol");
21
21
  /**
22
- * `<agent directory>/remote/ssh/<host>/<path>` for `ssh://<host>/<path>`. With `ta.exec.url` every
22
+ * `<agent directory>/remote/ssh/<host>/<path>` for `ssh://<host>/<path>`, `remote/ta/<name>/<path>` for a cloud
23
+ * workspace, `ta://<name>/<path>`. With `ta.exec.url` every
23
24
  * directory is one of the machine of the exec server: `<agent directory>/remote/exec/<path>`.
24
25
  */
25
26
  let DefaultPiDirectories = class DefaultPiDirectories {
26
27
  toPi(location) {
27
28
  var _a;
28
29
  const remote = ta_protocol_1.TaLocation.parse(location);
29
- const prefix = remote ? (0, node_path_1.join)('ssh', remote.host) : ((_a = this.execOptions) === null || _a === void 0 ? void 0 : _a.url) ? 'exec' : undefined;
30
+ const cloud = remote && ta_protocol_1.TaLocation.cloudName(remote.host);
31
+ const prefix = cloud ? (0, node_path_1.join)('ta', cloud) : remote ? (0, node_path_1.join)('ssh', remote.host) : ((_a = this.execOptions) === null || _a === void 0 ? void 0 : _a.url) ? 'exec' : undefined;
30
32
  if (!prefix) {
31
33
  return location;
32
34
  }
@@ -44,6 +46,9 @@ let DefaultPiDirectories = class DefaultPiDirectories {
44
46
  if (kind === 'ssh' && rest.length > 0 && ta_protocol_1.TaLocation.isHost(rest[0])) {
45
47
  return ta_protocol_1.TaLocation.ssh(rest[0], `/${rest.slice(1).join('/')}`);
46
48
  }
49
+ if (kind === 'ta' && rest.length > 0 && ta_protocol_1.TaLocation.isCloudName(rest[0])) {
50
+ return ta_protocol_1.TaLocation.cloud(rest[0], `/${rest.slice(1).join('/')}`);
51
+ }
47
52
  return kind === 'exec' ? `/${rest.join('/')}` : cwd;
48
53
  }
49
54
  root() {
@@ -4,6 +4,7 @@ import type { RpcConnection } from '@celljs/rpc/lib/node';
4
4
  import { type ExecClient, SshHost, type SshQuestion } from '@celljs/ta-exec';
5
5
  import { type TaRemoteEvent, type TaRemoteHost, type TaRemotePrompt } from '@celljs/ta-protocol';
6
6
  import { TaWorkingDirectory } from '../working-directory';
7
+ import { CloudHosts } from './cloud-hosts';
7
8
  import { RemoteHosts, type TaRemoteOptions } from './remote-protocol';
8
9
  interface Waiting {
9
10
  prompt: TaRemotePrompt;
@@ -21,9 +22,13 @@ export declare class DefaultRemoteHosts implements RemoteHosts, ApplicationLifec
21
22
  protected readonly waiting: Map<string, Waiting>;
22
23
  protected readonly watchers: Set<RpcConnection>;
23
24
  protected readonly disconnectListeners: Set<(host: string) => void>;
25
+ protected readonly cloud: CloudHosts;
26
+ protected readonly watchedCloud: Set<string>;
24
27
  client(host: string): ExecClient;
25
28
  list(): TaRemoteHost[];
26
29
  add(host: string): void;
30
+ /** Checked by connecting and asking where its home is; kept only then. */
31
+ addCloud(name: string, url: string, token: string): Promise<TaRemoteHost>;
27
32
  remove(host: string): Promise<void>;
28
33
  disconnect(host: string): Promise<void>;
29
34
  onDisconnect(listener: (host: string) => void): () => void;
@@ -18,6 +18,7 @@ const ta_brand_1 = require("@celljs/ta-harness/lib/node/ta-brand");
18
18
  const ta_protocol_1 = require("@celljs/ta-protocol");
19
19
  const ta_errors_1 = require("../ta-errors");
20
20
  const working_directory_1 = require("../working-directory");
21
+ const cloud_hosts_1 = require("./cloud-hosts");
21
22
  const remote_protocol_1 = require("./remote-protocol");
22
23
  /** A prompt nobody answers is cancelled after this: ssh gives up. */
23
24
  const PROMPT_TIMEOUT_MS = 5 * 60 * 1000;
@@ -31,11 +32,25 @@ let DefaultRemoteHosts = class DefaultRemoteHosts {
31
32
  this.waiting = new Map();
32
33
  this.watchers = new Set();
33
34
  this.disconnectListeners = new Set();
35
+ this.cloud = new cloud_hosts_1.CloudHosts(() => { var _a; var _b; return (_b = (_a = this.codingAgentOptions) === null || _a === void 0 ? void 0 : _a.agentDir) !== null && _b !== void 0 ? _b : ta_brand_1.TaBrand.agentDir(); });
36
+ this.watchedCloud = new Set();
34
37
  }
35
38
  client(host) {
36
39
  var _a, _b, _c, _d;
37
40
  var _e;
38
41
  this.check(host);
42
+ const name = ta_protocol_1.TaLocation.cloudName(host);
43
+ if (name) {
44
+ const client = this.cloud.client(name);
45
+ if (!client) {
46
+ throw ta_errors_1.TaErrors.invalidArgument(`There is no cloud workspace ${name}.`, 'Add it in Settings, Remote hosts, with the address of its gateway and a token.');
47
+ }
48
+ if (!this.watchedCloud.has(name)) {
49
+ this.watchedCloud.add(name);
50
+ client.onState((connected, error) => this.broadcast(error ? { type: 'connection', host, connected, error } : { type: 'connection', host, connected }));
51
+ }
52
+ return client;
53
+ }
39
54
  let ssh = this.hosts.get(host);
40
55
  if (!ssh) {
41
56
  ssh = new ta_exec_1.SshHost({
@@ -61,18 +76,68 @@ let DefaultRemoteHosts = class DefaultRemoteHosts {
61
76
  const recent = this.workingDirectory.recentHosts();
62
77
  const config = ta_exec_1.SshConfig.hosts().filter(host => ta_protocol_1.TaLocation.isHost(host) && !recent.includes(host));
63
78
  return [
79
+ ...this.cloud
80
+ .list()
81
+ .map(host => ({ host: ta_protocol_1.TaLocation.cloud(host.name), source: 'cloud', url: host.url, connected: this.cloud.connected(host.name) })),
64
82
  ...recent.map(host => ({ host, source: 'recent', connected: this.connected(host) })),
65
83
  ...config.map(host => ({ host, source: 'config', connected: this.connected(host) })),
66
84
  ];
67
85
  }
68
86
  add(host) {
87
+ if (ta_protocol_1.TaLocation.isCloud(host)) {
88
+ throw ta_errors_1.TaErrors.invalidArgument('A cloud workspace is added with its address and token.', 'Call addCloudHost.');
89
+ }
69
90
  this.workingDirectory.addRecentHost(this.check(host));
70
91
  }
92
+ /** Checked by connecting and asking where its home is; kept only then. */
93
+ async addCloud(name, url, token) {
94
+ if (typeof name !== 'string' || !ta_protocol_1.TaLocation.isCloudName(name)) {
95
+ throw ta_errors_1.TaErrors.invalidArgument(`${JSON.stringify(name)} cannot name a cloud workspace.`, 'Use lower-case letters, digits and -, 40 at most.');
96
+ }
97
+ let address;
98
+ try {
99
+ address = cloud_hosts_1.CloudHostsUtil.url(String(url !== null && url !== void 0 ? url : ''));
100
+ }
101
+ catch (error) {
102
+ throw ta_errors_1.TaErrors.invalidArgument(error.message, 'Write the address of the Ta gateway, as its page is opened.');
103
+ }
104
+ if (typeof token !== 'string' || !token.trim()) {
105
+ throw ta_errors_1.TaErrors.invalidArgument('A cloud workspace is reached with a token.', 'Make one on the gateway: Settings, Environment, Use it from another Ta.');
106
+ }
107
+ const probe = cloud_hosts_1.CloudHosts.connect({ url: address, token: token.trim() });
108
+ try {
109
+ await probe.info();
110
+ }
111
+ catch (error) {
112
+ throw ta_errors_1.TaErrors.invalidArgument(`${address} did not let Ta in: ${error.message}`, 'Check the address and the token; a token signed out on the gateway no longer works.');
113
+ }
114
+ finally {
115
+ probe.close();
116
+ }
117
+ await this.disconnect(ta_protocol_1.TaLocation.cloud(name));
118
+ this.cloud.save({ name, url: address, token: token.trim(), addedAt: Date.now() });
119
+ return { host: ta_protocol_1.TaLocation.cloud(name), source: 'cloud', url: address, connected: false };
120
+ }
71
121
  async remove(host) {
72
122
  await this.disconnect(host);
123
+ const name = ta_protocol_1.TaLocation.cloudName(host);
124
+ if (name) {
125
+ this.cloud.remove(name);
126
+ return;
127
+ }
73
128
  this.workingDirectory.removeRecentHost(host);
74
129
  }
75
130
  async disconnect(host) {
131
+ const name = ta_protocol_1.TaLocation.cloudName(host);
132
+ if (name) {
133
+ const client = this.cloud.drop(name);
134
+ this.watchedCloud.delete(name);
135
+ for (const listener of this.disconnectListeners) {
136
+ listener(host);
137
+ }
138
+ client === null || client === void 0 ? void 0 : client.close();
139
+ return;
140
+ }
76
141
  const ssh = this.hosts.get(host);
77
142
  this.hosts.delete(host);
78
143
  for (const listener of this.disconnectListeners) {
@@ -100,7 +165,7 @@ let DefaultRemoteHosts = class DefaultRemoteHosts {
100
165
  for (const waiting of [...this.waiting.values()]) {
101
166
  waiting.settle(undefined);
102
167
  }
103
- await Promise.all([...this.hosts.keys()].map(host => this.disconnect(host)));
168
+ await Promise.all([...this.hosts.keys(), ...[...this.watchedCloud].map(name => ta_protocol_1.TaLocation.cloud(name))].map(host => this.disconnect(host)));
104
169
  }
105
170
  ask(host, question) {
106
171
  const prompt = { promptId: (0, node_crypto_1.randomUUID)(), host, ...question };
@@ -129,13 +194,17 @@ let DefaultRemoteHosts = class DefaultRemoteHosts {
129
194
  }
130
195
  check(host) {
131
196
  if (typeof host !== 'string' || !ta_protocol_1.TaLocation.isHost(host)) {
132
- throw ta_errors_1.TaErrors.invalidArgument(`${JSON.stringify(host)} is not a host.`, 'Name a Host of ~/.ssh/config, or [user@]host[:port].');
197
+ throw ta_errors_1.TaErrors.invalidArgument(`${JSON.stringify(host)} is not a host.`, 'Name a Host of ~/.ssh/config, [user@]host[:port], or ta://<name> of a cloud workspace.');
133
198
  }
134
199
  return host;
135
200
  }
136
201
  connected(host) {
137
202
  var _a;
138
203
  var _b;
204
+ const name = ta_protocol_1.TaLocation.cloudName(host);
205
+ if (name) {
206
+ return this.cloud.connected(name);
207
+ }
139
208
  return (_b = (_a = this.hosts.get(host)) === null || _a === void 0 ? void 0 : _a.client.connected) !== null && _b !== void 0 ? _b : false;
140
209
  }
141
210
  };
@@ -21,6 +21,8 @@ export interface RemoteHosts {
21
21
  list(): TaRemoteHost[];
22
22
  /** Keeps a host in the list without connecting; throws for what is not a host. */
23
23
  add(host: string): void;
24
+ /** A cloud workspace, `ta://<name>`, kept once a connection to it worked. */
25
+ addCloud(name: string, url: string, token: string): Promise<TaRemoteHost>;
24
26
  /** Disconnects and drops it from the list of those opened before. */
25
27
  remove(host: string): Promise<void>;
26
28
  disconnect(host: string): Promise<void>;
@@ -8,6 +8,7 @@ export declare class TaRemoteServerImpl implements TaRemoteServer {
8
8
  protected readonly environments: ExecEnvironmentFactory;
9
9
  listHosts(): Promise<TaRemoteHost[]>;
10
10
  addHost(host: string): Promise<void>;
11
+ addCloudHost(name: string, url: string, token: string): Promise<TaRemoteHost>;
11
12
  removeHost(host: string): Promise<void>;
12
13
  resolveLocation(location: string): Promise<string>;
13
14
  forwardPort(port: number, cwd?: string): Promise<TaForwardedPort>;
@@ -25,6 +25,9 @@ let TaRemoteServerImpl = class TaRemoteServerImpl {
25
25
  addHost(host) {
26
26
  return ta_errors_1.TaErrors.guard(() => this.hosts.add(host));
27
27
  }
28
+ addCloudHost(name, url, token) {
29
+ return ta_errors_1.TaErrors.guard(() => this.hosts.addCloud(name, url, token));
30
+ }
28
31
  removeHost(host) {
29
32
  return ta_errors_1.TaErrors.guard(() => this.hosts.remove(host));
30
33
  }
@@ -249,10 +249,16 @@ const RULES = {
249
249
  disallow: fixed('members.roles'),
250
250
  signOut: fixed('members.roles'),
251
251
  },
252
+ // What the agents took and did: for the owner (and the gateway, which calls as the owner).
253
+ TaUsageServer: {
254
+ getUsage: owner,
255
+ getActivity: owner,
256
+ },
252
257
  TaRemoteServer: {
253
258
  listHosts: fixed('hosts.use'),
254
259
  addHost: fixed('settings.manage'),
255
260
  removeHost: fixed('settings.manage'),
261
+ addCloudHost: fixed('settings.manage'),
256
262
  resolveLocation: fixed('hosts.use'),
257
263
  forwardPort: fixed('hosts.use'),
258
264
  listForwardedPorts: fixed('hosts.use'),
@@ -0,0 +1,14 @@
1
+ import type { TaAgentActivity } from '@celljs/ta-protocol';
2
+ export declare namespace AgentActivityUtil {
3
+ const DEFAULT_LIMIT = 50;
4
+ const MAX_LIMIT = 200;
5
+ function limit(value: unknown): number;
6
+ function summary(text: string | undefined): string | undefined;
7
+ /**
8
+ * The tool calls and failed calls of the model in the entries of a session, newest first: a call without a
9
+ * result yet is `running`. Arguments and results never: a tool's name, whether it worked, the first line of
10
+ * its error, its secrets hidden.
11
+ */
12
+ function from(entries: readonly unknown[], max: number): TaAgentActivity[];
13
+ }
14
+ //# sourceMappingURL=agent-activity.d.ts.map
@@ -0,0 +1,87 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.AgentActivityUtil = void 0;
4
+ const redactor_1 = require("@celljs/ta-protocol/lib/common/redactor");
5
+ /** The first line of an error, its secrets hidden, cut short: what a console shows of it. */
6
+ const ERROR_LENGTH = 160;
7
+ var AgentActivityUtil;
8
+ (function (AgentActivityUtil) {
9
+ AgentActivityUtil.DEFAULT_LIMIT = 50;
10
+ AgentActivityUtil.MAX_LIMIT = 200;
11
+ function limit(value) {
12
+ const count = Math.floor(Number(value !== null && value !== void 0 ? value : AgentActivityUtil.DEFAULT_LIMIT));
13
+ return Number.isFinite(count) && count > 0 ? Math.min(count, AgentActivityUtil.MAX_LIMIT) : AgentActivityUtil.DEFAULT_LIMIT;
14
+ }
15
+ AgentActivityUtil.limit = limit;
16
+ function summary(text) {
17
+ var _a;
18
+ const line = (_a = text === null || text === void 0 ? void 0 : text.split('\n').find(part => part.trim())) === null || _a === void 0 ? void 0 : _a.trim();
19
+ return line ? redactor_1.Redactor.cut(new redactor_1.Redactor().text(line), ERROR_LENGTH) : undefined;
20
+ }
21
+ AgentActivityUtil.summary = summary;
22
+ function text(content) {
23
+ if (typeof content === 'string') {
24
+ return content;
25
+ }
26
+ if (Array.isArray(content)) {
27
+ return content
28
+ .map(part => { var _a; return part && typeof part === 'object' && part.type === 'text' ? String((_a = part.text) !== null && _a !== void 0 ? _a : '') : ''; })
29
+ .join('\n');
30
+ }
31
+ return undefined;
32
+ }
33
+ /**
34
+ * The tool calls and failed calls of the model in the entries of a session, newest first: a call without a
35
+ * result yet is `running`. Arguments and results never: a tool's name, whether it worked, the first line of
36
+ * its error, its secrets hidden.
37
+ */
38
+ function from(entries, max) {
39
+ var _a, _b, _c;
40
+ const calls = new Map();
41
+ const list = [];
42
+ for (const raw of entries) {
43
+ const entry = raw;
44
+ const message = entry.message;
45
+ if (entry.type !== 'message' || !message) {
46
+ continue;
47
+ }
48
+ const at = (_a = message.timestamp) !== null && _a !== void 0 ? _a : (entry.timestamp ? Date.parse(entry.timestamp) : 0);
49
+ if (message.role === 'assistant') {
50
+ if (message.stopReason === 'error') {
51
+ list.push({ at, kind: 'model', name: (_b = message.model) !== null && _b !== void 0 ? _b : 'model', ok: false, error: summary(message.errorMessage) });
52
+ }
53
+ if (Array.isArray(message.content)) {
54
+ for (const part of message.content) {
55
+ if ((part === null || part === void 0 ? void 0 : part.type) === 'toolCall' && part.id) {
56
+ const call = { at, kind: 'tool', name: (_c = part.name) !== null && _c !== void 0 ? _c : 'tool', ok: true, running: true };
57
+ calls.set(part.id, call);
58
+ list.push(call);
59
+ }
60
+ }
61
+ }
62
+ }
63
+ else if (message.role === 'toolResult') {
64
+ const call = message.toolCallId ? calls.get(message.toolCallId) : undefined;
65
+ if (call) {
66
+ delete call.running;
67
+ call.ok = !message.isError;
68
+ if (at > call.at) {
69
+ call.ms = at - call.at;
70
+ }
71
+ const error = message.isError ? summary(text(message.content)) : undefined;
72
+ if (error) {
73
+ call.error = error;
74
+ }
75
+ }
76
+ }
77
+ }
78
+ for (const each of list) {
79
+ if (each.error === undefined) {
80
+ delete each.error;
81
+ }
82
+ }
83
+ return list.reverse().slice(0, max);
84
+ }
85
+ AgentActivityUtil.from = from;
86
+ })(AgentActivityUtil || (exports.AgentActivityUtil = AgentActivityUtil = {}));
87
+ //# sourceMappingURL=agent-activity.js.map
@@ -0,0 +1,4 @@
1
+ export * from './agent-activity';
2
+ export * from './usage-reader';
3
+ export * from './usage-server-impl';
4
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1,20 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
+ };
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ __exportStar(require("./agent-activity"), exports);
18
+ __exportStar(require("./usage-reader"), exports);
19
+ __exportStar(require("./usage-server-impl"), exports);
20
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1,29 @@
1
+ import type { TaUsageBucket } from '@celljs/ta-protocol';
2
+ interface FileUsage {
3
+ /** Bytes read so far: whole lines only. */
4
+ offset: number;
5
+ /** By `<hour>|<model>`. */
6
+ buckets: Map<string, TaUsageBucket>;
7
+ }
8
+ export declare namespace UsageReaderUtil {
9
+ const HOUR_MS = 3600000;
10
+ /** What one line adds to the buckets, if it is an answer of a model with its usage. */
11
+ function add(buckets: Map<string, TaUsageBucket>, text: string): void;
12
+ /** The buckets of many files from `since` on, an hour and a model once. */
13
+ function merge(lists: Iterable<Iterable<TaUsageBucket>>, since: number): TaUsageBucket[];
14
+ }
15
+ /**
16
+ * What the models took, by hour, from the session files under a directory (pi's `sessions/<dir>/*.jsonl`). A file
17
+ * is read once, then only what was appended to it; one unchanged since before the window is not read at all.
18
+ */
19
+ export declare class UsageReader {
20
+ protected readonly root: () => Promise<string>;
21
+ protected readonly files: Map<string, FileUsage>;
22
+ constructor(root: () => Promise<string>);
23
+ read(since: number): Promise<TaUsageBucket[]>;
24
+ protected file(path: string, since: number): Promise<FileUsage | undefined>;
25
+ /** The lines written since the last time; a line still being written waits for the next. */
26
+ protected append(path: string, usage: FileUsage, size: number): Promise<void>;
27
+ }
28
+ export {};
29
+ //# sourceMappingURL=usage-reader.d.ts.map