@celljs/ta-host 4.13.1 → 4.15.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 (89) hide show
  1. package/README.en.md +3 -1
  2. package/README.md +3 -1
  3. package/esm/node/auth-server-impl.d.ts +12 -2
  4. package/esm/node/auth-server-impl.js +102 -3
  5. package/esm/node/custom-providers.d.ts +50 -0
  6. package/esm/node/custom-providers.js +335 -0
  7. package/esm/node/host-protocol.d.ts +17 -1
  8. package/esm/node/host-protocol.js +1 -0
  9. package/esm/node/index.d.ts +2 -0
  10. package/esm/node/index.js +2 -0
  11. package/esm/node/package-hosts.d.ts +2 -1
  12. package/esm/node/package-hosts.js +6 -2
  13. package/esm/node/presence-book.d.ts +38 -0
  14. package/esm/node/presence-book.js +159 -0
  15. package/esm/node/presence-server-impl.d.ts +13 -0
  16. package/esm/node/presence-server-impl.js +45 -0
  17. package/esm/node/rooms-bridge.d.ts +6 -1
  18. package/esm/node/rooms-bridge.js +21 -3
  19. package/esm/node/session-list-feed.js +2 -1
  20. package/esm/node/sign-in/access-server-impl.d.ts +5 -1
  21. package/esm/node/sign-in/access-server-impl.js +22 -1
  22. package/esm/node/sign-in/sign-in-flow.d.ts +14 -1
  23. package/esm/node/sign-in/sign-in-flow.js +24 -7
  24. package/esm/node/sign-in/sign-in-provider.d.ts +84 -1
  25. package/esm/node/sign-in/sign-in-provider.js +194 -7
  26. package/esm/node/sign-in/ta-sign-in.d.ts +12 -3
  27. package/esm/node/sign-in/ta-sign-in.js +36 -4
  28. package/esm/node/ta-server-impl.d.ts +7 -0
  29. package/esm/node/ta-server-impl.js +44 -7
  30. package/esm/node/ta-session-registry.d.ts +10 -3
  31. package/esm/node/ta-session-registry.js +29 -3
  32. package/esm/node/ta-session.d.ts +2 -0
  33. package/esm/node/ta-session.js +6 -0
  34. package/esm/node/team/host-team.d.ts +2 -1
  35. package/esm/node/team/host-team.js +11 -1
  36. package/esm/node/team/index.d.ts +1 -0
  37. package/esm/node/team/index.js +1 -0
  38. package/esm/node/team/member-accounts.d.ts +30 -0
  39. package/esm/node/team/member-accounts.js +117 -0
  40. package/esm/node/team/team-calls.d.ts +2 -1
  41. package/esm/node/team/team-calls.js +11 -0
  42. package/esm/node/team/team-gate.js +1 -1
  43. package/esm/node/team/team-protocol.d.ts +5 -1
  44. package/esm/node/team/team-protocol.js +2 -0
  45. package/esm/node/web-extension-util.js +1 -0
  46. package/lib/node/auth-server-impl.d.ts +12 -2
  47. package/lib/node/auth-server-impl.js +101 -2
  48. package/lib/node/custom-providers.d.ts +51 -0
  49. package/lib/node/custom-providers.js +338 -0
  50. package/lib/node/host-protocol.d.ts +17 -1
  51. package/lib/node/host-protocol.js +2 -1
  52. package/lib/node/index.d.ts +2 -0
  53. package/lib/node/index.js +2 -0
  54. package/lib/node/package-hosts.d.ts +2 -1
  55. package/lib/node/package-hosts.js +5 -1
  56. package/lib/node/presence-book.d.ts +39 -0
  57. package/lib/node/presence-book.js +162 -0
  58. package/lib/node/presence-server-impl.d.ts +14 -0
  59. package/lib/node/presence-server-impl.js +48 -0
  60. package/lib/node/rooms-bridge.d.ts +6 -1
  61. package/lib/node/rooms-bridge.js +20 -2
  62. package/lib/node/session-list-feed.js +2 -1
  63. package/lib/node/sign-in/access-server-impl.d.ts +5 -1
  64. package/lib/node/sign-in/access-server-impl.js +21 -0
  65. package/lib/node/sign-in/sign-in-flow.d.ts +14 -1
  66. package/lib/node/sign-in/sign-in-flow.js +24 -7
  67. package/lib/node/sign-in/sign-in-provider.d.ts +84 -1
  68. package/lib/node/sign-in/sign-in-provider.js +197 -9
  69. package/lib/node/sign-in/ta-sign-in.d.ts +12 -3
  70. package/lib/node/sign-in/ta-sign-in.js +36 -4
  71. package/lib/node/ta-server-impl.d.ts +7 -0
  72. package/lib/node/ta-server-impl.js +43 -6
  73. package/lib/node/ta-session-registry.d.ts +10 -3
  74. package/lib/node/ta-session-registry.js +27 -1
  75. package/lib/node/ta-session.d.ts +2 -0
  76. package/lib/node/ta-session.js +6 -0
  77. package/lib/node/team/host-team.d.ts +2 -1
  78. package/lib/node/team/host-team.js +10 -0
  79. package/lib/node/team/index.d.ts +1 -0
  80. package/lib/node/team/index.js +1 -0
  81. package/lib/node/team/member-accounts.d.ts +31 -0
  82. package/lib/node/team/member-accounts.js +120 -0
  83. package/lib/node/team/team-calls.d.ts +2 -1
  84. package/lib/node/team/team-calls.js +11 -0
  85. package/lib/node/team/team-gate.js +1 -1
  86. package/lib/node/team/team-protocol.d.ts +5 -1
  87. package/lib/node/team/team-protocol.js +3 -1
  88. package/lib/node/web-extension-util.js +1 -0
  89. package/package.json +12 -12
@@ -0,0 +1,338 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.CustomProviderUtil = exports.NO_KEY = void 0;
4
+ const ta_protocol_1 = require("@celljs/ta-protocol");
5
+ const ta_errors_1 = require("./ta-errors");
6
+ const OPTION_KEYS = ['contextWindow', 'maxTokens', 'reasoning', 'images'];
7
+ /** A name of a header, as HTTP has them. */
8
+ const HEADER_NAME = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;
9
+ /** More tokens than any model has. */
10
+ const MAX_TOKENS = 100000000;
11
+ /** The key of a provider added without one (a server on the user's computer): pi offers a provider's models only once it has a key. */
12
+ exports.NO_KEY = 'none';
13
+ /**
14
+ * The providers the user adds by their address, as entries of pi's models.json: `baseUrl`, `api`, `apiKey` and
15
+ * `models` of an id pi has no provider for. What else an entry or a model holds (headers, compat, a context window
16
+ * written by hand) stays when Ta changes it.
17
+ */
18
+ var CustomProviderUtil;
19
+ (function (CustomProviderUtil) {
20
+ function object(value) {
21
+ return value && typeof value === 'object' && !Array.isArray(value) ? value : undefined;
22
+ }
23
+ function api(value) {
24
+ return ta_protocol_1.TA_CUSTOM_APIS.find(each => each === value);
25
+ }
26
+ /** What a model of models.json says of an option. */
27
+ function option(model, key) {
28
+ switch (key) {
29
+ case 'reasoning':
30
+ return model.reasoning === true;
31
+ case 'images':
32
+ return Array.isArray(model.input) && model.input.includes('image');
33
+ default:
34
+ return typeof model[key] === 'number' ? model[key] : undefined;
35
+ }
36
+ }
37
+ /** The options every model has alike, and those they do not. */
38
+ function options(models) {
39
+ const options = {};
40
+ const mixed = [];
41
+ for (const key of OPTION_KEYS) {
42
+ const values = new Set(models.map(model => option(model, key)));
43
+ if (values.size > 1) {
44
+ mixed.push(key);
45
+ }
46
+ else if (values.size === 1) {
47
+ const [value] = values;
48
+ if (value !== undefined) {
49
+ options[key] = value;
50
+ }
51
+ }
52
+ }
53
+ return { options: options, mixed };
54
+ }
55
+ CustomProviderUtil.options = options;
56
+ /** A model with the options set: left out keeps, null or false removes. */
57
+ function withOptions(model, given) {
58
+ const next = { ...model };
59
+ for (const key of OPTION_KEYS) {
60
+ const value = given[key];
61
+ if (value === undefined) {
62
+ continue;
63
+ }
64
+ const field = key === 'images' ? 'input' : key;
65
+ if (value === null || value === false) {
66
+ delete next[field];
67
+ }
68
+ else if (key === 'images') {
69
+ next.input = ['text', 'image'];
70
+ }
71
+ else {
72
+ next[field] = value;
73
+ }
74
+ }
75
+ return next;
76
+ }
77
+ CustomProviderUtil.withOptions = withOptions;
78
+ /** A value pi resolves to itself (one Ta wrote), unescaped; undefined for a variable or a command. */
79
+ function plain(value) {
80
+ if (value.startsWith('!')) {
81
+ return undefined;
82
+ }
83
+ let text = '';
84
+ for (let at = 0; at < value.length; at++) {
85
+ if (value[at] !== '$') {
86
+ text += value[at];
87
+ }
88
+ else if (value[at + 1] === '$' || value[at + 1] === '!') {
89
+ text += value[++at];
90
+ }
91
+ else {
92
+ return undefined;
93
+ }
94
+ }
95
+ return text;
96
+ }
97
+ CustomProviderUtil.plain = plain;
98
+ /** The headers a provider sends that are plain values, by name. */
99
+ function storedHeaders(entry) {
100
+ var _a;
101
+ var _b;
102
+ const headers = (_b = object((_a = object(entry)) === null || _a === void 0 ? void 0 : _a.headers)) !== null && _b !== void 0 ? _b : {};
103
+ const found = {};
104
+ for (const [name, value] of Object.entries(headers)) {
105
+ const resolved = typeof value === 'string' ? plain(value) : undefined;
106
+ if (resolved !== undefined) {
107
+ found[name] = resolved;
108
+ }
109
+ }
110
+ return found;
111
+ }
112
+ CustomProviderUtil.storedHeaders = storedHeaders;
113
+ /** The headers given, with an empty value taking the one kept of that name. */
114
+ function headersWith(given, kept) {
115
+ const headers = {};
116
+ for (const [name, value] of Object.entries(given !== null && given !== void 0 ? given : {})) {
117
+ const resolved = value || kept[name];
118
+ if (resolved) {
119
+ headers[name] = resolved;
120
+ }
121
+ }
122
+ return headers;
123
+ }
124
+ CustomProviderUtil.headersWith = headersWith;
125
+ /** The entries of models.json, by id. */
126
+ function entries(data) {
127
+ var _a;
128
+ return (_a = object(data.providers)) !== null && _a !== void 0 ? _a : {};
129
+ }
130
+ CustomProviderUtil.entries = entries;
131
+ /** An entry Ta shows as one added by its address: an address, an API of the list and models of its own. */
132
+ function read(id, value) {
133
+ var _a;
134
+ const entry = object(value);
135
+ const kind = api(entry === null || entry === void 0 ? void 0 : entry.api);
136
+ if (!entry || !kind || typeof entry.baseUrl !== 'string' || !Array.isArray(entry.models)) {
137
+ return undefined;
138
+ }
139
+ const entries = entry.models.map(model => object(model)).filter((model) => typeof (model === null || model === void 0 ? void 0 : model.id) === 'string');
140
+ const models = entries.map(model => model.id);
141
+ const key = entry.apiKey;
142
+ return {
143
+ id,
144
+ name: typeof entry.name === 'string' && entry.name ? entry.name : id,
145
+ api: kind,
146
+ baseUrl: entry.baseUrl,
147
+ hasKey: typeof key === 'string' && key !== '' && key !== exports.NO_KEY,
148
+ models,
149
+ ...options(entries),
150
+ headers: Object.keys((_a = object(entry.headers)) !== null && _a !== void 0 ? _a : {}),
151
+ };
152
+ }
153
+ CustomProviderUtil.read = read;
154
+ function list(data) {
155
+ return Object.entries(entries(data))
156
+ .map(([id, value]) => read(id, value))
157
+ .filter((provider) => !!provider)
158
+ .sort((a, b) => a.name.localeCompare(b.name));
159
+ }
160
+ CustomProviderUtil.list = list;
161
+ /**
162
+ * A key as pi reads it literally: pi runs a value that starts with `!` as a command and puts in the variable of
163
+ * `$NAME`, so `$` is written `$$` and a first `!` `$!`.
164
+ */
165
+ function literal(key) {
166
+ const escaped = key.replace(/\$/g, '$$$$');
167
+ return escaped.startsWith('!') ? `$${escaped}` : escaped;
168
+ }
169
+ CustomProviderUtil.literal = literal;
170
+ /** The input made plain, or the reason it is not one. */
171
+ function clean(input) {
172
+ const kind = api(input === null || input === void 0 ? void 0 : input.api);
173
+ if (!kind) {
174
+ throw ta_errors_1.TaErrors.invalidArgument(`${String(input === null || input === void 0 ? void 0 : input.api)} is not an API Ta takes.`, `Use one of ${ta_protocol_1.TA_CUSTOM_APIS.join(', ')}.`);
175
+ }
176
+ const baseUrl = typeof input.baseUrl === 'string' ? input.baseUrl.trim().replace(/\/+$/, '') : '';
177
+ let url;
178
+ try {
179
+ url = new URL(baseUrl);
180
+ }
181
+ catch (_a) {
182
+ url = undefined;
183
+ }
184
+ if (!url || (url.protocol !== 'http:' && url.protocol !== 'https:')) {
185
+ throw ta_errors_1.TaErrors.invalidArgument(`${baseUrl || 'An empty address'} is not an address of a service.`, 'Give its http(s) URL, e.g. https://api.example.com/v1.');
186
+ }
187
+ const models = [...new Set((Array.isArray(input.models) ? input.models : []).map(model => String(model).trim()).filter(Boolean))];
188
+ const name = typeof input.name === 'string' && input.name.trim() ? input.name.trim() : url.host;
189
+ const apiKey = typeof input.apiKey === 'string' ? input.apiKey.trim() : undefined;
190
+ return { ...input, name, api: kind, baseUrl, apiKey, models, options: cleanOptions(input.options), headers: cleanHeaders(input.headers) };
191
+ }
192
+ CustomProviderUtil.clean = clean;
193
+ function cleanOptions(given) {
194
+ const options = object(given);
195
+ if (!options) {
196
+ return undefined;
197
+ }
198
+ const clean = {};
199
+ for (const key of OPTION_KEYS) {
200
+ const value = options[key];
201
+ if (value === undefined || value === null) {
202
+ clean[key] = value;
203
+ }
204
+ else if (key === 'reasoning' || key === 'images') {
205
+ if (typeof value !== 'boolean') {
206
+ throw ta_errors_1.TaErrors.invalidArgument(`${key} is ${JSON.stringify(value)}, not true or false.`, 'Give a boolean, or null to remove it.');
207
+ }
208
+ clean[key] = value;
209
+ }
210
+ else if (typeof value === 'number' && Number.isInteger(value) && value > 0 && value <= MAX_TOKENS) {
211
+ clean[key] = value;
212
+ }
213
+ else {
214
+ throw ta_errors_1.TaErrors.invalidArgument(`${key} is ${JSON.stringify(value)}, not a number of tokens.`, 'Give a whole number above 0, or null to remove it.');
215
+ }
216
+ }
217
+ return clean;
218
+ }
219
+ function cleanHeaders(given) {
220
+ const headers = object(given);
221
+ if (!headers) {
222
+ return undefined;
223
+ }
224
+ const clean = {};
225
+ for (const [raw, value] of Object.entries(headers)) {
226
+ const name = raw.trim();
227
+ if (!name) {
228
+ continue;
229
+ }
230
+ if (!HEADER_NAME.test(name) || typeof value !== 'string' || /[\r\n]/.test(value)) {
231
+ throw ta_errors_1.TaErrors.invalidArgument(`${name} is not a header Ta sends.`, 'Give a name of letters, digits and dashes, and a value of one line.');
232
+ }
233
+ clean[name] = value.trim();
234
+ }
235
+ return clean;
236
+ }
237
+ /** An id for a new provider of that name: of letters, digits and dashes, and none that is taken. */
238
+ function newId(name, taken) {
239
+ const base = name
240
+ .toLowerCase()
241
+ .replace(/[^a-z0-9]+/g, '-')
242
+ .replace(/^-+|-+$/g, '')
243
+ .slice(0, 40) || 'custom';
244
+ let id = base;
245
+ for (let n = 2; taken(id); n++) {
246
+ id = `${base}-${n}`;
247
+ }
248
+ return id;
249
+ }
250
+ CustomProviderUtil.newId = newId;
251
+ /** models.json with the provider saved; its other entries, and what Ta does not change of this one, stay. */
252
+ function save(data, id, input) {
253
+ var _a, _b;
254
+ const providers = { ...entries(data) };
255
+ const before = (_a = object(providers[id])) !== null && _a !== void 0 ? _a : {};
256
+ const models = Array.isArray(before.models) ? before.models : [];
257
+ const entry = {
258
+ ...before,
259
+ name: input.name,
260
+ baseUrl: input.baseUrl,
261
+ api: input.api,
262
+ models: input.models.map(model => { var _a, _b; return withOptions((_a = object(models.find(each => { var _a; return ((_a = object(each)) === null || _a === void 0 ? void 0 : _a.id) === model; }))) !== null && _a !== void 0 ? _a : { id: model }, (_b = input.options) !== null && _b !== void 0 ? _b : {}); }),
263
+ };
264
+ if (input.headers) {
265
+ const kept = (_b = object(before.headers)) !== null && _b !== void 0 ? _b : {};
266
+ const headers = {};
267
+ for (const [name, value] of Object.entries(input.headers)) {
268
+ if (value) {
269
+ headers[name] = literal(value);
270
+ }
271
+ else if (typeof kept[name] === 'string') {
272
+ headers[name] = kept[name];
273
+ }
274
+ }
275
+ if (Object.keys(headers).length > 0) {
276
+ entry.headers = headers;
277
+ }
278
+ else {
279
+ delete entry.headers;
280
+ }
281
+ }
282
+ if (input.apiKey) {
283
+ entry.apiKey = literal(input.apiKey);
284
+ }
285
+ else if (input.apiKey === '' || typeof before.apiKey !== 'string') {
286
+ entry.apiKey = exports.NO_KEY;
287
+ }
288
+ providers[id] = entry;
289
+ return { ...data, providers };
290
+ }
291
+ CustomProviderUtil.save = save;
292
+ function remove(data, id) {
293
+ const providers = { ...entries(data) };
294
+ delete providers[id];
295
+ return { ...data, providers };
296
+ }
297
+ CustomProviderUtil.remove = remove;
298
+ /** Where a service lists its models, and the headers that carry the key, by its API. */
299
+ function modelsRequest(kind, baseUrl, key, extra = {}) {
300
+ const request = authRequest(kind, baseUrl, key);
301
+ // Those of the provider last: a gateway may take its key in a header of its own.
302
+ return { url: request.url, headers: { ...request.headers, ...extra } };
303
+ }
304
+ CustomProviderUtil.modelsRequest = modelsRequest;
305
+ function authRequest(kind, baseUrl, key) {
306
+ const base = baseUrl.replace(/\/+$/, '');
307
+ const real = key && key !== exports.NO_KEY ? key : undefined;
308
+ switch (kind) {
309
+ case 'anthropic-messages':
310
+ // pi's address of Anthropic has no /v1, which its client adds.
311
+ return {
312
+ url: /\/v\d+$/.test(base) ? `${base}/models` : `${base}/v1/models`,
313
+ headers: { 'anthropic-version': '2023-06-01', ...(real ? { 'x-api-key': real } : {}) },
314
+ };
315
+ case 'google-generative-ai':
316
+ return { url: `${base}/models`, headers: real ? { 'x-goog-api-key': real } : {} };
317
+ default:
318
+ return { url: `${base}/models`, headers: real ? { Authorization: `Bearer ${real}` } : {} };
319
+ }
320
+ }
321
+ /** The ids of a list of models: OpenAI's and Anthropic's `data[].id`, Google's `models[].name` without `models/`. */
322
+ function modelIds(body) {
323
+ var _a;
324
+ const json = (_a = object(body)) !== null && _a !== void 0 ? _a : {};
325
+ const ids = [
326
+ ...(Array.isArray(json.data) ? json.data : []).map(model => { var _a; return (_a = object(model)) === null || _a === void 0 ? void 0 : _a.id; }),
327
+ ...(Array.isArray(json.models) ? json.models : []).map(model => {
328
+ var _a, _b;
329
+ const item = object(model);
330
+ const name = (_b = (_a = item === null || item === void 0 ? void 0 : item.name) !== null && _a !== void 0 ? _a : item === null || item === void 0 ? void 0 : item.id) !== null && _b !== void 0 ? _b : item === null || item === void 0 ? void 0 : item.model;
331
+ return typeof name === 'string' ? name.replace(/^models\//, '') : undefined;
332
+ }),
333
+ ];
334
+ return [...new Set(ids.filter((id) => typeof id === 'string' && id !== ''))].sort((a, b) => a.localeCompare(b));
335
+ }
336
+ CustomProviderUtil.modelIds = modelIds;
337
+ })(CustomProviderUtil || (exports.CustomProviderUtil = CustomProviderUtil = {}));
338
+ //# sourceMappingURL=custom-providers.js.map
@@ -1,5 +1,5 @@
1
1
  import type { RpcConnection } from '@celljs/rpc/lib/node';
2
- import type { TaEvent, TaOpenSessionOptions, TaPackageInfo, TaSavedSessionInfo, TaSavedSessionQuery, TaSessionInfo, TaSettingsScope, TaSlashCommand, TaTemporaryFrom, TaWebExtensionInfo, TaWebExtensionSource } from '@celljs/ta-protocol';
2
+ import type { TaEvent, TaOpenSessionOptions, TaPackageInfo, TaPresencePerson, TaPresenceReport, TaSavedSessionInfo, TaSavedSessionQuery, TaSessionInfo, TaSessionPerson, TaSettingsScope, TaSlashCommand, TaTemporaryFrom, TaWebExtensionInfo, TaWebExtensionSource } from '@celljs/ta-protocol';
3
3
  import type { ClientChannel } from './client-channel';
4
4
  import type { TaSession } from './ta-session';
5
5
  export declare const TaSessionFactory: unique symbol;
@@ -7,6 +7,7 @@ export declare const TaSessionRegistry: unique symbol;
7
7
  export declare const TaSessionCatalog: unique symbol;
8
8
  export declare const WebExtensionCatalog: unique symbol;
9
9
  export declare const KeepAwake: unique symbol;
10
+ export declare const TaPresenceBook: unique symbol;
10
11
  export declare const TA_HOST_OPTIONS = "ta.host";
11
12
  export declare const TA_EXEC_OPTIONS = "ta.exec";
12
13
  /** `ta.host`. */
@@ -44,6 +45,8 @@ export interface TaSessionRegistry {
44
45
  */
45
46
  resolve(sessionId: string): Promise<TaSession>;
46
47
  list(): TaSession[];
48
+ /** The infos of the open sessions a connection may see, with who else is at each (TaSessionInfo.people). */
49
+ infos(connection: RpcConnection | undefined): TaSessionInfo[];
47
50
  /** The infos of the open sessions; the connection is told of each change from now on (TaServer.watchSessions). */
48
51
  watch(connection: RpcConnection): TaSessionInfo[];
49
52
  /** `idle`: closed to save its memory (idle, or the service stops), it keeps its id and opens again when called; otherwise for good. */
@@ -107,4 +110,17 @@ export interface KeepAwake {
107
110
  /** Holds or lets go as things are now: at once after the setting changed. */
108
111
  check(): void;
109
112
  }
113
+ /**
114
+ * What each page is at (TaPresenceServer.report), in memory only: who looks at which conversation and types in it. A page
115
+ * leaves it as its connection closes, or once it said nothing for TA_PRESENCE_EXPIRY_MS.
116
+ */
117
+ export interface TaPresenceBook {
118
+ report(connection: RpcConnection, state: TaPresenceReport): void;
119
+ /** The others at a session, as `principal` is told: those who look at it or type in it, and who asked its run while `streaming`. */
120
+ people(sessionId: string, principal: string, streaming: boolean): TaSessionPerson[] | undefined;
121
+ /** Each one with pages that report, and where the latest of them is. */
122
+ everyone(): TaPresencePerson[];
123
+ /** What `people` gives may have changed. */
124
+ onChange(listener: () => void): () => void;
125
+ }
110
126
  //# sourceMappingURL=host-protocol.d.ts.map
@@ -1,11 +1,12 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.TA_EXEC_OPTIONS = exports.TA_HOST_OPTIONS = exports.KeepAwake = exports.WebExtensionCatalog = exports.TaSessionCatalog = exports.TaSessionRegistry = exports.TaSessionFactory = void 0;
3
+ exports.TA_EXEC_OPTIONS = exports.TA_HOST_OPTIONS = exports.TaPresenceBook = exports.KeepAwake = exports.WebExtensionCatalog = exports.TaSessionCatalog = exports.TaSessionRegistry = exports.TaSessionFactory = void 0;
4
4
  exports.TaSessionFactory = Symbol('TaSessionFactory');
5
5
  exports.TaSessionRegistry = Symbol('TaSessionRegistry');
6
6
  exports.TaSessionCatalog = Symbol('TaSessionCatalog');
7
7
  exports.WebExtensionCatalog = Symbol('WebExtensionCatalog');
8
8
  exports.KeepAwake = Symbol('KeepAwake');
9
+ exports.TaPresenceBook = Symbol('TaPresenceBook');
9
10
  exports.TA_HOST_OPTIONS = 'ta.host';
10
11
  exports.TA_EXEC_OPTIONS = 'ta.exec';
11
12
  //# sourceMappingURL=host-protocol.js.map
@@ -11,6 +11,8 @@ export * from './keep-awake';
11
11
  export * from './package-host-extension';
12
12
  export * from './package-hosts';
13
13
  export * from './package-server-impl';
14
+ export * from './presence-book';
15
+ export * from './presence-server-impl';
14
16
  export * from './receipt-book';
15
17
  export * from './relay-bridge';
16
18
  export * from './remote';
package/lib/node/index.js CHANGED
@@ -27,6 +27,8 @@ __exportStar(require("./keep-awake"), exports);
27
27
  __exportStar(require("./package-host-extension"), exports);
28
28
  __exportStar(require("./package-hosts"), exports);
29
29
  __exportStar(require("./package-server-impl"), exports);
30
+ __exportStar(require("./presence-book"), exports);
31
+ __exportStar(require("./presence-server-impl"), exports);
30
32
  __exportStar(require("./receipt-book"), exports);
31
33
  __exportStar(require("./relay-bridge"), exports);
32
34
  __exportStar(require("./remote"), exports);
@@ -2,7 +2,7 @@ import { type CodingAgentOptions } from '@celljs/ai-coding-agent';
2
2
  import { type Application, ApplicationLifecycle } from '@celljs/core';
3
3
  import { type TaExtensionHost, type TaHostAnswer, type TaHostSessionEvent, TaPackageServer, type TaPackageService, TaServer } from '@celljs/ta-protocol';
4
4
  import { ExtensionDataStore } from './extension-data';
5
- import { TaSessionRegistry } from './host-protocol';
5
+ import { TaPresenceBook, TaSessionRegistry } from './host-protocol';
6
6
  import { type RelayBridge } from './relay-bridge';
7
7
  import { PiDirectories } from './remote/remote-protocol';
8
8
  import { type RoomsBridge } from './rooms-bridge';
@@ -56,6 +56,7 @@ export declare class PackageHostsImpl implements PackageHosts, ApplicationLifecy
56
56
  protected readonly roomsBridge: RoomsBridge;
57
57
  protected readonly settings: TaSettingsStore;
58
58
  protected readonly sessions: TaSessionRegistry;
59
+ protected readonly presenceBook: TaPresenceBook;
59
60
  protected readonly teamProvider: TaHostTeamProvider;
60
61
  protected readonly running: Map<string, Running>;
61
62
  protected extensionHost?: TaExtensionHost;
@@ -212,7 +212,7 @@ let PackageHostsImpl = class PackageHostsImpl {
212
212
  listener(turn);
213
213
  }
214
214
  }),
215
- presence: () => ({ pages: this.sessions.watching, seenAt: this.sessions.watchedAt }),
215
+ presence: () => ({ pages: this.sessions.watching, seenAt: this.sessions.watchedAt, people: this.presenceBook.everyone() }),
216
216
  team: this.teamProvider.team,
217
217
  installPackage: (source, scope, cwd) => packages.installPackage(source, scope, cwd),
218
218
  removePackage: (id, cwd) => packages.removePackage(id, cwd),
@@ -285,6 +285,10 @@ __decorate([
285
285
  (0, core_1.Autowired)({ id: host_protocol_1.TaSessionRegistry, detached: true }),
286
286
  __metadata("design:type", Object)
287
287
  ], PackageHostsImpl.prototype, "sessions", void 0);
288
+ __decorate([
289
+ (0, core_1.Autowired)({ id: host_protocol_1.TaPresenceBook, detached: true }),
290
+ __metadata("design:type", Object)
291
+ ], PackageHostsImpl.prototype, "presenceBook", void 0);
288
292
  __decorate([
289
293
  (0, core_1.Autowired)({ id: team_protocol_1.TaHostTeamProvider, detached: true }),
290
294
  __metadata("design:type", Object)
@@ -0,0 +1,39 @@
1
+ import type { RpcConnection } from '@celljs/rpc/lib/node';
2
+ import { type TaPresencePerson, type TaPresenceReport, type TaSessionPerson } from '@celljs/ta-protocol';
3
+ import { TaPresenceBook } from './host-protocol';
4
+ import { TaAuthority, TaPrincipals, TaRunActors } from './team/team-protocol';
5
+ interface Entry {
6
+ principal: string;
7
+ sessionId?: string;
8
+ typing: boolean;
9
+ /** `Date.now()` time of its last report. */
10
+ at: number;
11
+ }
12
+ /**
13
+ * What each page is at, by connection (docs/design/ta-team.md 7.1): who looks at which conversation and types in it,
14
+ * named as the page of members names them. Nothing of it is written anywhere; a connection closed, or silent for
15
+ * TA_PRESENCE_EXPIRY_MS, is out of it.
16
+ */
17
+ export declare class DefaultTaPresenceBook implements TaPresenceBook {
18
+ protected readonly principals: TaPrincipals;
19
+ protected readonly authority: TaAuthority;
20
+ protected readonly runs: TaRunActors;
21
+ protected readonly entries: Map<RpcConnection, Entry>;
22
+ protected readonly watched: WeakSet<RpcConnection>;
23
+ protected readonly listeners: Set<() => void>;
24
+ protected sweeper?: ReturnType<typeof setInterval>;
25
+ protected ownerName?: string;
26
+ /** How long a page may say nothing; less in specs. */
27
+ protected expiryMs: number;
28
+ report(connection: RpcConnection, state: TaPresenceReport): void;
29
+ people(sessionId: string, principal: string, streaming: boolean): TaSessionPerson[] | undefined;
30
+ everyone(): TaPresencePerson[];
31
+ onChange(listener: () => void): () => void;
32
+ protected nameOf(principal: string): string;
33
+ protected leave(connection: RpcConnection): void;
34
+ /** Pages silent too long are gone; looked for only while there are pages. */
35
+ protected sweep(): void;
36
+ protected changed(): void;
37
+ }
38
+ export {};
39
+ //# sourceMappingURL=presence-book.d.ts.map
@@ -0,0 +1,162 @@
1
+ "use strict";
2
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
3
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
4
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
5
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
6
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
7
+ };
8
+ var __metadata = (this && this.__metadata) || function (k, v) {
9
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
10
+ };
11
+ Object.defineProperty(exports, "__esModule", { value: true });
12
+ exports.DefaultTaPresenceBook = void 0;
13
+ const node_os_1 = require("node:os");
14
+ const core_1 = require("@celljs/core");
15
+ const ta_protocol_1 = require("@celljs/ta-protocol");
16
+ const host_protocol_1 = require("./host-protocol");
17
+ const team_protocol_1 = require("./team/team-protocol");
18
+ /**
19
+ * What each page is at, by connection (docs/design/ta-team.md 7.1): who looks at which conversation and types in it,
20
+ * named as the page of members names them. Nothing of it is written anywhere; a connection closed, or silent for
21
+ * TA_PRESENCE_EXPIRY_MS, is out of it.
22
+ */
23
+ let DefaultTaPresenceBook = class DefaultTaPresenceBook {
24
+ constructor() {
25
+ this.entries = new Map();
26
+ this.watched = new WeakSet();
27
+ this.listeners = new Set();
28
+ /** How long a page may say nothing; less in specs. */
29
+ this.expiryMs = ta_protocol_1.TA_PRESENCE_EXPIRY_MS;
30
+ }
31
+ report(connection, state) {
32
+ if (connection.closed) {
33
+ return;
34
+ }
35
+ const sessionId = typeof (state === null || state === void 0 ? void 0 : state.sessionId) === 'string' && state.sessionId ? state.sessionId : undefined;
36
+ const entry = { principal: this.principals.of(connection), sessionId, typing: !!sessionId && (state === null || state === void 0 ? void 0 : state.typing) === true, at: Date.now() };
37
+ const before = this.entries.get(connection);
38
+ this.entries.set(connection, entry);
39
+ if (!this.watched.has(connection)) {
40
+ this.watched.add(connection);
41
+ connection.onClose(() => this.leave(connection));
42
+ }
43
+ this.sweep();
44
+ if (!before || before.sessionId !== entry.sessionId || before.typing !== entry.typing) {
45
+ this.changed();
46
+ }
47
+ }
48
+ people(sessionId, principal, streaming) {
49
+ var _a;
50
+ const found = new Map();
51
+ const person = (id) => {
52
+ let one = found.get(id);
53
+ if (!one) {
54
+ one = { id, name: this.nameOf(id) };
55
+ found.set(id, one);
56
+ }
57
+ return one;
58
+ };
59
+ for (const entry of this.entries.values()) {
60
+ if (entry.sessionId === sessionId && entry.principal !== principal) {
61
+ const one = person(entry.principal);
62
+ one.viewing = true;
63
+ if (entry.typing) {
64
+ one.typing = true;
65
+ }
66
+ }
67
+ }
68
+ if (streaming) {
69
+ for (const actor of (_a = this.runs.actorsOfSession(sessionId)) !== null && _a !== void 0 ? _a : []) {
70
+ if (actor !== principal) {
71
+ person(actor).asked = true;
72
+ }
73
+ }
74
+ }
75
+ // The same order each time: a list told again only when it differs.
76
+ return found.size ? [...found.values()].sort((a, b) => (a.id < b.id ? -1 : a.id > b.id ? 1 : 0)) : undefined;
77
+ }
78
+ everyone() {
79
+ var _a;
80
+ const people = new Map();
81
+ for (const entry of this.entries.values()) {
82
+ const one = (_a = people.get(entry.principal)) !== null && _a !== void 0 ? _a : { id: entry.principal, name: this.nameOf(entry.principal), pages: 0, at: 0 };
83
+ one.pages++;
84
+ if (entry.at >= one.at) {
85
+ one.at = entry.at;
86
+ one.sessionId = entry.sessionId;
87
+ one.typing = entry.typing || undefined;
88
+ }
89
+ people.set(entry.principal, one);
90
+ }
91
+ return [...people.values()].map(({ at: _at, sessionId, typing, ...one }) => ({
92
+ ...one,
93
+ ...(sessionId ? { sessionId } : {}),
94
+ ...(typing ? { typing } : {}),
95
+ }));
96
+ }
97
+ onChange(listener) {
98
+ this.listeners.add(listener);
99
+ return () => this.listeners.delete(listener);
100
+ }
101
+ nameOf(principal) {
102
+ var _a;
103
+ var _b, _c;
104
+ if (principal === ta_protocol_1.TA_OWNER) {
105
+ (_b = this.ownerName) !== null && _b !== void 0 ? _b : (this.ownerName = (0, node_os_1.userInfo)().username);
106
+ return this.ownerName;
107
+ }
108
+ return (_c = (_a = this.authority.describe(principal)) === null || _a === void 0 ? void 0 : _a.name) !== null && _c !== void 0 ? _c : principal;
109
+ }
110
+ leave(connection) {
111
+ if (this.entries.delete(connection)) {
112
+ this.changed();
113
+ }
114
+ }
115
+ /** Pages silent too long are gone; looked for only while there are pages. */
116
+ sweep() {
117
+ var _a, _b;
118
+ if (this.sweeper || !this.entries.size) {
119
+ return;
120
+ }
121
+ this.sweeper = setInterval(() => {
122
+ const before = Date.now() - this.expiryMs;
123
+ let gone = false;
124
+ for (const [connection, entry] of this.entries) {
125
+ if (entry.at < before) {
126
+ this.entries.delete(connection);
127
+ gone = true;
128
+ }
129
+ }
130
+ if (!this.entries.size) {
131
+ clearInterval(this.sweeper);
132
+ this.sweeper = undefined;
133
+ }
134
+ if (gone) {
135
+ this.changed();
136
+ }
137
+ }, Math.max(1, Math.floor(this.expiryMs / 3)));
138
+ (_b = (_a = this.sweeper).unref) === null || _b === void 0 ? void 0 : _b.call(_a);
139
+ }
140
+ changed() {
141
+ for (const listener of this.listeners) {
142
+ listener();
143
+ }
144
+ }
145
+ };
146
+ exports.DefaultTaPresenceBook = DefaultTaPresenceBook;
147
+ __decorate([
148
+ (0, core_1.Autowired)(team_protocol_1.TaPrincipals),
149
+ __metadata("design:type", Object)
150
+ ], DefaultTaPresenceBook.prototype, "principals", void 0);
151
+ __decorate([
152
+ (0, core_1.Autowired)(team_protocol_1.TaAuthority),
153
+ __metadata("design:type", Object)
154
+ ], DefaultTaPresenceBook.prototype, "authority", void 0);
155
+ __decorate([
156
+ (0, core_1.Autowired)(team_protocol_1.TaRunActors),
157
+ __metadata("design:type", Object)
158
+ ], DefaultTaPresenceBook.prototype, "runs", void 0);
159
+ exports.DefaultTaPresenceBook = DefaultTaPresenceBook = __decorate([
160
+ (0, core_1.Component)(host_protocol_1.TaPresenceBook)
161
+ ], DefaultTaPresenceBook);
162
+ //# sourceMappingURL=presence-book.js.map
@@ -0,0 +1,14 @@
1
+ import { type TaPresenceReport, TaPresenceServer } from '@celljs/ta-protocol';
2
+ import { TaPresenceBook, TaSessionRegistry } from './host-protocol';
3
+ import { TaVisibility } from './team/team-protocol';
4
+ /**
5
+ * What each page says it is at (TaPresenceServer). A page is at a conversation only when it is open and the page may
6
+ * see it: no one shows at one they may not see, nor at one made up.
7
+ */
8
+ export declare class TaPresenceServerImpl implements TaPresenceServer {
9
+ protected readonly book: TaPresenceBook;
10
+ protected readonly sessions: TaSessionRegistry;
11
+ protected readonly visibility: TaVisibility;
12
+ report(state: TaPresenceReport): Promise<void>;
13
+ }
14
+ //# sourceMappingURL=presence-server-impl.d.ts.map