@celljs/ta-relay 4.15.2 → 4.17.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 (58) hide show
  1. package/esm/common/index.d.ts +1 -0
  2. package/esm/common/index.js +1 -0
  3. package/esm/common/relay-content.d.ts +13 -0
  4. package/esm/common/relay-content.js +42 -0
  5. package/esm/common/relay-conversation.d.ts +14 -0
  6. package/esm/common/relay-hub.js +2 -2
  7. package/esm/common/relay-hubs-identity.d.ts +36 -0
  8. package/esm/common/relay-hubs-identity.js +156 -0
  9. package/esm/common/relay-hubs-protocol.d.ts +4 -0
  10. package/esm/common/relay-hubs-util.d.ts +11 -0
  11. package/esm/common/relay-hubs-util.js +74 -0
  12. package/esm/common/relay-hubs.d.ts +17 -44
  13. package/esm/common/relay-hubs.js +37 -235
  14. package/esm/common/relay-protocol.d.ts +9 -0
  15. package/esm/common/relay-protocol.js +13 -0
  16. package/esm/common/relay-spot.d.ts +15 -3
  17. package/esm/common/relay-spot.js +17 -5
  18. package/esm/node/index.d.ts +1 -0
  19. package/esm/node/index.js +1 -0
  20. package/esm/node/relay-memory-storage.d.ts +26 -0
  21. package/esm/node/relay-memory-storage.js +60 -0
  22. package/esm/node/relay-server.d.ts +14 -26
  23. package/esm/node/relay-server.js +33 -60
  24. package/esm/node/relay-store.js +4 -4
  25. package/esm/node/relays-file.d.ts +27 -0
  26. package/esm/node/relays-file.js +59 -4
  27. package/esm/viewer/viewer.js +33 -1
  28. package/lib/common/index.d.ts +1 -0
  29. package/lib/common/index.js +1 -0
  30. package/lib/common/relay-content.d.ts +13 -0
  31. package/lib/common/relay-content.js +43 -1
  32. package/lib/common/relay-conversation.d.ts +14 -0
  33. package/lib/common/relay-hub.js +1 -1
  34. package/lib/common/relay-hubs-identity.d.ts +37 -0
  35. package/lib/common/relay-hubs-identity.js +160 -0
  36. package/lib/common/relay-hubs-protocol.d.ts +4 -0
  37. package/lib/common/relay-hubs-util.d.ts +12 -0
  38. package/lib/common/relay-hubs-util.js +77 -0
  39. package/lib/common/relay-hubs.d.ts +17 -44
  40. package/lib/common/relay-hubs.js +36 -234
  41. package/lib/common/relay-protocol.d.ts +9 -0
  42. package/lib/common/relay-protocol.js +15 -1
  43. package/lib/common/relay-spot.d.ts +15 -3
  44. package/lib/common/relay-spot.js +17 -5
  45. package/lib/node/index.d.ts +1 -0
  46. package/lib/node/index.js +1 -0
  47. package/lib/node/relay-memory-storage.d.ts +27 -0
  48. package/lib/node/relay-memory-storage.js +65 -0
  49. package/lib/node/relay-server.d.ts +14 -26
  50. package/lib/node/relay-server.js +34 -61
  51. package/lib/node/relay-store.js +3 -3
  52. package/lib/node/relays-file.d.ts +27 -0
  53. package/lib/node/relays-file.js +58 -3
  54. package/lib/viewer/viewer.js +32 -0
  55. package/package.json +3 -2
  56. package/viewer/join.html +3 -3
  57. package/viewer/page.html +9 -9
  58. package/viewer/room.html +10 -10
@@ -1,11 +1,13 @@
1
1
  import { type IncomingMessage, type Server, type ServerResponse } from 'node:http';
2
2
  import type { Duplex } from 'node:stream';
3
3
  import { WebSocketConnection } from '@celljs/rpc/lib/node/websocket/websocket-connection';
4
- import { type RelayBlobStorage, RelayBlobs } from '../common/relay-blobs.js';
5
- import { RelayHub, type RelayHubStorage, type RelayHubWho } from '../common/relay-hub.js';
4
+ import { type TaDeploymentEnv } from '@celljs/ta-protocol/lib/common/deployment-protocol';
5
+ import { RelayBlobs } from '../common/relay-blobs.js';
6
+ import { RelayHub, type RelayHubWho } from '../common/relay-hub.js';
6
7
  import { RelayRoom } from '../common/relay-room.js';
7
8
  import { RelaySpot, type RelaySpotSocket, type RelaySpotWho } from '../common/relay-spot.js';
8
9
  import { FileRelayStorage } from './relay-file-storage.js';
10
+ import { MemoryBlobStorage, MemoryHubStorage } from './relay-memory-storage.js';
9
11
  export interface RelayServerOptions {
10
12
  host?: string;
11
13
  port?: number;
@@ -19,6 +21,14 @@ export interface RelayServerOptions {
19
21
  * (`ta relay` gives its own); without it, a link that invites still asks from a browser, but leads nowhere.
20
22
  */
21
23
  web?: string;
24
+ /**
25
+ * What it says of the deployment it is part of (TA_WELL_KNOWN_PATH, docs/design/ta-deploy.md 2): its name, its
26
+ * gateway, and its own address (TA_PUBLIC_URL; else the one it was reached at).
27
+ */
28
+ deployment?: TaDeploymentEnv & {
29
+ TA_PUBLIC_URL?: string;
30
+ };
31
+ version?: string;
22
32
  }
23
33
  interface Room {
24
34
  secretHash: string;
@@ -26,30 +36,6 @@ interface Room {
26
36
  clients: Map<string, WebSocketConnection>;
27
37
  relay: RelayRoom;
28
38
  }
29
- /** A copy of content in memory, deleted when it runs out. */
30
- declare class MemoryBlobStorage implements RelayBlobStorage {
31
- protected readonly values: Map<string, unknown>;
32
- protected timer?: ReturnType<typeof setTimeout>;
33
- get<T>(key: string): Promise<T | undefined>;
34
- put(key: string, value: unknown): Promise<void>;
35
- deleteAll(): Promise<void>;
36
- /** No copy is kept: nothing of it need stay in the relay's memory. */
37
- get empty(): boolean;
38
- setAlarm(at: number): Promise<void>;
39
- }
40
- /** A room in memory, as a Durable Object keeps it. */
41
- declare class MemoryHubStorage implements RelayHubStorage {
42
- protected readonly values: Map<string, unknown>;
43
- get<T>(key: string): Promise<T | undefined>;
44
- put(key: string, value: unknown): Promise<void>;
45
- delete(key: string): Promise<boolean>;
46
- list<T>(options: {
47
- prefix: string;
48
- }): Promise<Map<string, T>>;
49
- deleteAll(): Promise<void>;
50
- /** No room was made, or it was closed. */
51
- get empty(): boolean;
52
- }
53
39
  interface Hub {
54
40
  hub: RelayHub;
55
41
  storage: MemoryHubStorage | FileRelayStorage;
@@ -86,6 +72,8 @@ export declare class RelayServer {
86
72
  protected readonly spotAddresses: WeakMap<WebSocketConnection, string>;
87
73
  protected server?: Server;
88
74
  constructor(options?: RelayServerOptions);
75
+ /** What it is part of, and whether it runs and can keep what it holds: for anyone, and the probes of a platform. */
76
+ protected describe(path: string, request: IncomingMessage, response: ServerResponse): void;
89
77
  listen(): Promise<string>;
90
78
  /** A file of Ta's web page (RelayWebUtil), from the directory of the options. */
91
79
  protected web(path: string, response: ServerResponse): void;
@@ -1,8 +1,9 @@
1
1
  import { createHash, randomBytes, timingSafeEqual } from 'node:crypto';
2
- import { mkdirSync, readFileSync, renameSync, statSync, writeFileSync } from 'node:fs';
2
+ import { accessSync, constants, mkdirSync, readFileSync, renameSync, statSync, writeFileSync } from 'node:fs';
3
3
  import { createServer } from 'node:http';
4
4
  import { join } from 'node:path';
5
5
  import { WebSocketConnection } from '@celljs/rpc/lib/node/websocket/websocket-connection';
6
+ import { TA_WELL_KNOWN_PATH, TaDeploymentUtil } from '@celljs/ta-protocol/lib/common/deployment-protocol';
6
7
  import { RelayBlobs } from '../common/relay-blobs.js';
7
8
  import { RelayHub } from '../common/relay-hub.js';
8
9
  import { RELAY_INFO_PATH, RelayInfoUtil } from '../common/relay-info.js';
@@ -12,67 +13,9 @@ import { RELAY_SPOT_PATH, RelaySpot, RelaySpotCloseCode, RelaySpotTries } from '
12
13
  import { RELAY_JOIN_PATH, RELAY_WEB_PATH } from '../common/relay-team.js';
13
14
  import { RelayWebUtil } from '../common/relay-web.js';
14
15
  import { FileRelayStorage } from './relay-file-storage.js';
16
+ import { MemoryBlobStorage, MemoryHubStorage } from './relay-memory-storage.js';
15
17
  import { RelayViewer } from './relay-viewer.js';
16
18
  const WEBSOCKET = { maxPayload: 32 * 1024 * 1024, heartbeat: 30000 };
17
- /** A copy of content in memory, deleted when it runs out. */
18
- class MemoryBlobStorage {
19
- constructor() {
20
- this.values = new Map();
21
- }
22
- async get(key) {
23
- return this.values.get(key);
24
- }
25
- async put(key, value) {
26
- this.values.set(key, value);
27
- }
28
- async deleteAll() {
29
- this.values.clear();
30
- clearTimeout(this.timer);
31
- }
32
- /** No copy is kept: nothing of it need stay in the relay's memory. */
33
- get empty() {
34
- return this.values.size === 0;
35
- }
36
- async setAlarm(at) {
37
- var _a, _b;
38
- clearTimeout(this.timer);
39
- // Past the 24 days of a timer, it is found run out on the next read.
40
- this.timer = setTimeout(() => this.values.clear(), Math.min(Math.max(at - Date.now(), 0), 2 ** 31 - 1));
41
- (_b = (_a = this.timer).unref) === null || _b === void 0 ? void 0 : _b.call(_a);
42
- }
43
- }
44
- /** A room in memory, as a Durable Object keeps it. */
45
- class MemoryHubStorage {
46
- constructor() {
47
- this.values = new Map();
48
- }
49
- async get(key) {
50
- const value = this.values.get(key);
51
- return value === undefined ? undefined : structuredClone(value);
52
- }
53
- async put(key, value) {
54
- this.values.set(key, structuredClone(value));
55
- }
56
- async delete(key) {
57
- return this.values.delete(key);
58
- }
59
- async list(options) {
60
- const found = new Map();
61
- for (const [key, value] of [...this.values].sort(([a], [b]) => a.localeCompare(b))) {
62
- if (key.startsWith(options.prefix)) {
63
- found.set(key, structuredClone(value));
64
- }
65
- }
66
- return found;
67
- }
68
- async deleteAll() {
69
- this.values.clear();
70
- }
71
- /** No room was made, or it was closed. */
72
- get empty() {
73
- return this.values.size === 0;
74
- }
75
- }
76
19
  const peer = (connection) => ({ send: text => connection.send(text), close: (code, reason) => connection.close(code, reason) });
77
20
  /**
78
21
  * `ta relay`: the relay on a machine of one's own, as the Cloudflare Worker is in the cloud. It forwards,
@@ -111,10 +54,40 @@ export class RelayServer {
111
54
  }
112
55
  }
113
56
  }
57
+ /** What it is part of, and whether it runs and can keep what it holds: for anyone, and the probes of a platform. */
58
+ describe(path, request, response) {
59
+ var _a, _b;
60
+ const version = this.options.version;
61
+ let body = { ok: true, ...(version ? { version } : {}) };
62
+ let status = 200;
63
+ if (path === TA_WELL_KNOWN_PATH) {
64
+ const env = (_a = this.options.deployment) !== null && _a !== void 0 ? _a : {};
65
+ const forwarded = String((_b = request.headers['x-forwarded-proto']) !== null && _b !== void 0 ? _b : '')
66
+ .split(',')[0]
67
+ .trim();
68
+ const origin = request.headers.host ? `${forwarded === 'https' ? 'https' : 'http'}://${request.headers.host}` : undefined;
69
+ body = TaDeploymentUtil.describe(env, { relay: env.TA_PUBLIC_URL || origin }, version);
70
+ }
71
+ else if (path === '/readyz' && this.options.data) {
72
+ try {
73
+ accessSync(this.options.data, constants.W_OK);
74
+ }
75
+ catch (error) {
76
+ status = 503;
77
+ body = { ok: false, error: `${this.options.data} cannot be written: ${error.message}` };
78
+ }
79
+ }
80
+ response.writeHead(status, TaDeploymentUtil.HEADERS);
81
+ response.end(JSON.stringify(body));
82
+ }
114
83
  listen() {
115
84
  const server = createServer((request, response) => {
116
85
  var _a;
117
86
  const path = ((_a = request.url) !== null && _a !== void 0 ? _a : '/').split(/[?#]/)[0];
87
+ if (path === TA_WELL_KNOWN_PATH || path === '/healthz' || path === '/readyz') {
88
+ this.describe(path, request, response);
89
+ return;
90
+ }
118
91
  if (path === RELAY_INFO_PATH) {
119
92
  // Without a directory for its data, rooms and copies live in memory: gone when the relay restarts.
120
93
  const info = RelayInfoUtil.of(!!this.options.data);
@@ -5,7 +5,7 @@ import { dirname, join } from 'node:path';
5
5
  import { RelayBytes } from '../common/relay-bytes.js';
6
6
  import { RelayContentUtil } from '../common/relay-content.js';
7
7
  import { RelayIdentityUtil } from '../common/relay-identity.js';
8
- import { RELAY_BLOB_MAX_DAYS, RELAY_DEFAULT_URL, RELAY_SHARE_DAYS } from '../common/relay-protocol.js';
8
+ import { RELAY_BLOB_MAX_DAYS, RELAY_SHARE_DAYS, relayDefaultUrl } from '../common/relay-protocol.js';
9
9
  const id = () => randomBytes(16).toString('base64url');
10
10
  /** The devices paired with this ta serve. Read again on every use: `ta pair` changes it while ta serve runs. */
11
11
  export class RelayStore {
@@ -38,7 +38,7 @@ export class RelayStore {
38
38
  /** The relay of a device, a link or content shared: its own, else the one of relay.json, else the official one. */
39
39
  static relayOf(item, config) {
40
40
  var _a, _b;
41
- return (_b = (_a = item.relay) !== null && _a !== void 0 ? _a : config.url) !== null && _b !== void 0 ? _b : RELAY_DEFAULT_URL;
41
+ return (_b = (_a = item.relay) !== null && _a !== void 0 ? _a : config.url) !== null && _b !== void 0 ? _b : relayDefaultUrl();
42
42
  }
43
43
  /** A share still on, by its id. */
44
44
  share(shareId, now = Date.now()) {
@@ -86,7 +86,7 @@ export class RelayStore {
86
86
  const expiresAt = days ? now + days * 24 * 60 * 60 * 1000 : undefined;
87
87
  const offline = input.offline && input.access !== 'self' && input.access !== 'people';
88
88
  const before = this.read();
89
- const relay = ((_b = (_a = input.relay) !== null && _a !== void 0 ? _a : before.url) !== null && _b !== void 0 ? _b : RELAY_DEFAULT_URL).replace(/\/+$/, '');
89
+ const relay = ((_b = (_a = input.relay) !== null && _a !== void 0 ? _a : before.url) !== null && _b !== void 0 ? _b : relayDefaultUrl()).replace(/\/+$/, '');
90
90
  const content = {
91
91
  id,
92
92
  relay,
@@ -167,7 +167,7 @@ export class RelayStore {
167
167
  shareRoot(root, name, now = Date.now(), relay) {
168
168
  var _a, _b, _c, _d;
169
169
  const before = this.read();
170
- const wanted = ((_a = relay !== null && relay !== void 0 ? relay : before.url) !== null && _a !== void 0 ? _a : RELAY_DEFAULT_URL).replace(/\/+$/, '');
170
+ const wanted = ((_a = relay !== null && relay !== void 0 ? relay : before.url) !== null && _a !== void 0 ? _a : relayDefaultUrl()).replace(/\/+$/, '');
171
171
  const url = (_b = before.url) !== null && _b !== void 0 ? _b : wanted;
172
172
  const host = (_c = before.host) !== null && _c !== void 0 ? _c : { id: id(), secret: randomBytes(32).toString('base64url') };
173
173
  const live = ((_d = before.shares) !== null && _d !== void 0 ? _d : []).filter(share => share.expiresAt > now);
@@ -49,12 +49,23 @@ export interface RelayStoreServiceEntry {
49
49
  options: Record<string, unknown>;
50
50
  builtin: false;
51
51
  }
52
+ /**
53
+ * A deployment of Ta the user joined (docs/design/ta-deploy.md 8): where it was found, what it said of itself, and the id
54
+ * of its relay in relays.json, which is then the default of new pairings, rooms and links.
55
+ */
56
+ export interface RelaysDeployment {
57
+ url: string;
58
+ name?: string;
59
+ gateway?: string;
60
+ relay?: string;
61
+ }
52
62
  /** relays.json in the agent directory: the relays, and which one each feature uses. Written by hand or by Ta. */
53
63
  export interface RelaysConfig {
54
64
  relays?: Record<string, RelayService>;
55
65
  use?: Record<string, string>;
56
66
  /** What a feature not in `use` takes. */
57
67
  default?: string;
68
+ deployment?: RelaysDeployment;
58
69
  }
59
70
  export type RelayServiceEntry = (({
60
71
  type: 'ta-relay';
@@ -131,6 +142,22 @@ export declare class RelaysFile {
131
142
  addStore(type: string, options: Record<string, unknown>, name?: string): string;
132
143
  /** Removes a relay that no feature uses; the official one stays. What is on it (devices, rooms, links) stays on it. */
133
144
  remove(id: string): void;
145
+ /**
146
+ * Joins a deployment, as it said of itself: its relay added and made the default (what a feature not in `use` takes),
147
+ * the deployment kept. What was made before (devices, rooms, links) stays on its relay; a choice in `use` stays too.
148
+ */
149
+ join(url: string, deployment: {
150
+ name?: string;
151
+ gateway?: string;
152
+ relay?: string;
153
+ }): RelaysDeployment;
154
+ /**
155
+ * Leaves the deployment joined: the default is the relay of this build again, and its relay goes from the list when
156
+ * no feature names it. What is on it (rooms, links) stays there, each remembering its relay.
157
+ */
158
+ leave(): void;
159
+ /** The deployment joined, as relays.json holds it: none when a hand wrote something else there. */
160
+ deployment(config?: RelaysConfig): RelaysDeployment | undefined;
134
161
  /** Which relay a feature uses from now on; `undefined` leaves it to the default. */
135
162
  use(feature: RelayFeature, id: string | undefined): void;
136
163
  /** Written whole, its other keys as they were, through a temporary file. */
@@ -2,7 +2,7 @@ import { accessSync, chmodSync, constants, mkdirSync, readdirSync, readFileSync,
2
2
  import { homedir } from 'node:os';
3
3
  import { dirname, isAbsolute, join, resolve } from 'node:path';
4
4
  import { RelayInfoUtil } from '../common/relay-info.js';
5
- import { RELAY_DEFAULT_URL } from '../common/relay-protocol.js';
5
+ import { relayDefaultUrl } from '../common/relay-protocol.js';
6
6
  export const RELAY_FEATURES = ['devices', 'share', 'rooms', 'sync'];
7
7
  /** The relay that comes with Ta, by its id in relays.json. */
8
8
  export const OFFICIAL_RELAY = 'cellbang';
@@ -166,7 +166,7 @@ export class RelaysFile {
166
166
  const entries = [];
167
167
  const own = config.relays && typeof config.relays === 'object' ? config.relays : {};
168
168
  if (!own[OFFICIAL_RELAY]) {
169
- entries.push({ id: OFFICIAL_RELAY, type: 'ta-relay', url: RELAY_DEFAULT_URL, name: 'relay.cellbang.com', builtin: true });
169
+ entries.push({ id: OFFICIAL_RELAY, type: 'ta-relay', url: relayDefaultUrl(), name: new URL(relayDefaultUrl()).host, builtin: true });
170
170
  }
171
171
  for (const [id, service] of Object.entries(own)) {
172
172
  if (!ID.test(id) || !service || typeof service !== 'object') {
@@ -200,7 +200,7 @@ export class RelaysFile {
200
200
  if (service) {
201
201
  return service;
202
202
  }
203
- const url = fallback !== null && fallback !== void 0 ? fallback : RELAY_DEFAULT_URL;
203
+ const url = fallback !== null && fallback !== void 0 ? fallback : relayDefaultUrl();
204
204
  return (_a = this.services(config).find(entry => RelayServiceUtil.isRelay(entry) && entry.url === url)) !== null && _a !== void 0 ? _a : { id: '', type: 'ta-relay', url, builtin: false };
205
205
  }
206
206
  /**
@@ -218,7 +218,7 @@ export class RelaysFile {
218
218
  /** The address a feature uses: its service, else `fallback` (the relay of relay.json), else the official one. */
219
219
  urlFor(feature, fallback) {
220
220
  const service = this.serviceFor(feature, fallback);
221
- return RelayServiceUtil.isRelay(service) ? service.url : (fallback !== null && fallback !== void 0 ? fallback : RELAY_DEFAULT_URL);
221
+ return RelayServiceUtil.isRelay(service) ? service.url : (fallback !== null && fallback !== void 0 ? fallback : relayDefaultUrl());
222
222
  }
223
223
  /** Adds a relay by its address: its id from its host name. The id, and the one before for the same address. */
224
224
  add(url, name) {
@@ -326,6 +326,61 @@ export class RelaysFile {
326
326
  delete relays[id];
327
327
  this.write({ ...config, relays });
328
328
  }
329
+ /**
330
+ * Joins a deployment, as it said of itself: its relay added and made the default (what a feature not in `use` takes),
331
+ * the deployment kept. What was made before (devices, rooms, links) stays on its relay; a choice in `use` stays too.
332
+ */
333
+ join(url, deployment) {
334
+ var _a, _b;
335
+ const relay = deployment.relay ? this.add(deployment.relay, deployment.name) : undefined;
336
+ const config = this.read();
337
+ const name = (_a = deployment.name) === null || _a === void 0 ? void 0 : _a.trim().slice(0, 80);
338
+ const joined = {
339
+ url,
340
+ ...(name ? { name } : {}),
341
+ ...(deployment.gateway ? { gateway: deployment.gateway } : {}),
342
+ ...(relay ? { relay } : {}),
343
+ };
344
+ const { default: before, ...rest } = config;
345
+ const fallback = relay !== null && relay !== void 0 ? relay : (before === ((_b = config.deployment) === null || _b === void 0 ? void 0 : _b.relay) ? undefined : before);
346
+ this.write({ ...rest, ...(fallback ? { default: fallback } : {}), deployment: joined });
347
+ return joined;
348
+ }
349
+ /**
350
+ * Leaves the deployment joined: the default is the relay of this build again, and its relay goes from the list when
351
+ * no feature names it. What is on it (rooms, links) stays there, each remembering its relay.
352
+ */
353
+ leave() {
354
+ var _a, _b;
355
+ const config = this.read();
356
+ const joined = config.deployment;
357
+ if (!joined) {
358
+ return;
359
+ }
360
+ const { deployment: _left, default: before, ...rest } = config;
361
+ const relays = { ...((_a = rest.relays) !== null && _a !== void 0 ? _a : {}) };
362
+ const used = Object.values((_b = rest.use) !== null && _b !== void 0 ? _b : {});
363
+ if (joined.relay && joined.relay !== OFFICIAL_RELAY && !used.includes(joined.relay)) {
364
+ delete relays[joined.relay];
365
+ }
366
+ const kept = before && before !== joined.relay ? before : undefined;
367
+ this.write({ ...rest, relays, ...(kept ? { default: kept } : {}) });
368
+ }
369
+ /** The deployment joined, as relays.json holds it: none when a hand wrote something else there. */
370
+ deployment(config = this.safeRead().config) {
371
+ const joined = config.deployment;
372
+ if (!joined || typeof joined !== 'object' || typeof joined.url !== 'string') {
373
+ return undefined;
374
+ }
375
+ const text = (value) => (typeof value === 'string' && value ? value : undefined);
376
+ const relay = text(joined.relay);
377
+ return {
378
+ url: joined.url,
379
+ ...(text(joined.name) ? { name: text(joined.name) } : {}),
380
+ ...(text(joined.gateway) ? { gateway: text(joined.gateway) } : {}),
381
+ ...(relay && this.services(config).some(service => service.id === relay) ? { relay } : {}),
382
+ };
383
+ }
329
384
  /** Which relay a feature uses from now on; `undefined` leaves it to the default. */
330
385
  use(feature, id) {
331
386
  var _a;
@@ -1,7 +1,8 @@
1
1
  import { RELAY_AGENT_KIND, RelayAgentCards } from '../common/relay-card.js';
2
- import { RelayContentError, RelayContentUtil } from '../common/relay-content.js';
2
+ import { RelayContentError, RelayContentHandoff, RelayContentUtil } from '../common/relay-content.js';
3
3
  import { RELAY_CONVERSATION_KIND } from '../common/relay-conversation.js';
4
4
  import { RELAY_FRAME_PATH } from '../common/relay-protocol.js';
5
+ import { RELAY_WEB_PATH } from '../common/relay-team.js';
5
6
  import { ViewerI18n } from './viewer-i18n.js';
6
7
  import { ViewerMarkdown } from './viewer-markdown.js';
7
8
  import { VIEWER_STYLE } from './viewer-style.js';
@@ -105,6 +106,19 @@ function conversation(main, item) {
105
106
  row.append(Object.assign(el('div', said), { className: 'bubble' }));
106
107
  main.append(row);
107
108
  }
109
+ else if (message.role === 'custom') {
110
+ // A card of an extension, as its words: Ta's page draws the card itself.
111
+ const { words } = text(message.content);
112
+ if (words.trim()) {
113
+ const row = el('div');
114
+ row.className = 'msg ta';
115
+ const block = el('div');
116
+ block.className = 'text';
117
+ block.append(ViewerMarkdown.render(words));
118
+ row.append(block);
119
+ main.append(row);
120
+ }
121
+ }
108
122
  else if (message.role === 'assistant') {
109
123
  const row = el('div');
110
124
  row.className = 'msg ta';
@@ -314,6 +328,17 @@ function footer(card) {
314
328
  foot.append(...(card ? [] : [el('span', t('footer'))]), el('span', t('secure')));
315
329
  document.body.append(foot);
316
330
  }
331
+ /** Whether the relay serves Ta's web page (apps/ta-relay with its assets, `ta relay` given its files). */
332
+ async function richPage() {
333
+ var _a;
334
+ try {
335
+ const response = await fetch(RELAY_WEB_PATH, { method: 'HEAD', cache: 'no-store' });
336
+ return response.ok && ((_a = response.headers.get('content-type')) !== null && _a !== void 0 ? _a : '').startsWith('text/html');
337
+ }
338
+ catch (_b) {
339
+ return false;
340
+ }
341
+ }
317
342
  async function show() {
318
343
  var _a;
319
344
  const main = chrome(t('title'));
@@ -329,6 +354,8 @@ async function show() {
329
354
  card(main, 'self', t(link.access));
330
355
  return;
331
356
  }
357
+ // Ta's own page, where the relay has it (RELAY_WEB_PATH), draws a conversation as Ta does: its cards, plots and 3D.
358
+ const rich = new URLSearchParams(location.search).has('plain') ? Promise.resolve(false) : richPage();
332
359
  let password;
333
360
  let error;
334
361
  for (;;) {
@@ -341,6 +368,11 @@ async function show() {
341
368
  }
342
369
  try {
343
370
  const item = await RelayContentUtil.fetch(link, { password });
371
+ if (item.kind === RELAY_CONVERSATION_KIND && (await rich)) {
372
+ RelayContentHandoff.keep(link.share, item, password);
373
+ location.replace(RELAY_WEB_PATH + location.hash);
374
+ return;
375
+ }
344
376
  main.replaceChildren();
345
377
  const name = document.querySelector('.top .name');
346
378
  if (name) {
@@ -13,6 +13,7 @@ export * from './relay-hub';
13
13
  export * from './relay-hub-util';
14
14
  export * from './relay-hubs';
15
15
  export * from './relay-hubs-protocol';
16
+ export * from './relay-hubs-util';
16
17
  export * from './relay-identity';
17
18
  export * from './relay-info';
18
19
  export * from './relay-pairing';
@@ -29,6 +29,7 @@ __exportStar(require("./relay-hub"), exports);
29
29
  __exportStar(require("./relay-hub-util"), exports);
30
30
  __exportStar(require("./relay-hubs"), exports);
31
31
  __exportStar(require("./relay-hubs-protocol"), exports);
32
+ __exportStar(require("./relay-hubs-util"), exports);
32
33
  __exportStar(require("./relay-identity"), exports);
33
34
  __exportStar(require("./relay-info"), exports);
34
35
  __exportStar(require("./relay-pairing"), exports);
@@ -102,4 +102,17 @@ export declare namespace RelayContentUtil {
102
102
  */
103
103
  function fetch(text: string | RelayContentLink, options?: RelayContentFetchOptions): Promise<RelayContentItem>;
104
104
  }
105
+ /**
106
+ * What the viewer of the relay opened, handed to Ta's web page of the same relay (RELAY_WEB_PATH), which draws a
107
+ * conversation as Ta does: kept in the session of the tab, by the share, for the page that comes next and for it
108
+ * loaded again; the password alone when the whole is too large to keep, so that it is not asked again.
109
+ */
110
+ export declare namespace RelayContentHandoff {
111
+ function keep(share: string, item: RelayContentItem, password?: string): void;
112
+ /** What was kept for `share`: the content opened, or its password. */
113
+ function take(share: string): {
114
+ item?: RelayContentItem;
115
+ password?: string;
116
+ };
117
+ }
105
118
  //# sourceMappingURL=relay-content.d.ts.map
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.RelayContentUtil = exports.RelayContentError = void 0;
3
+ exports.RelayContentHandoff = exports.RelayContentUtil = exports.RelayContentError = void 0;
4
4
  const relay_bytes_1 = require("./relay-bytes");
5
5
  const relay_identity_1 = require("./relay-identity");
6
6
  const relay_protocol_1 = require("./relay-protocol");
@@ -317,4 +317,46 @@ var RelayContentUtil;
317
317
  return new Uint8Array(bits);
318
318
  }
319
319
  })(RelayContentUtil || (exports.RelayContentUtil = RelayContentUtil = {}));
320
+ /**
321
+ * What the viewer of the relay opened, handed to Ta's web page of the same relay (RELAY_WEB_PATH), which draws a
322
+ * conversation as Ta does: kept in the session of the tab, by the share, for the page that comes next and for it
323
+ * loaded again; the password alone when the whole is too large to keep, so that it is not asked again.
324
+ */
325
+ var RelayContentHandoff;
326
+ (function (RelayContentHandoff) {
327
+ const KEY = 'ta.shared';
328
+ function keep(share, item, password) {
329
+ const { data, ...header } = item;
330
+ const store = (kept) => { var _a; return (_a = globalThis.sessionStorage) === null || _a === void 0 ? void 0 : _a.setItem(KEY, JSON.stringify(kept)); };
331
+ try {
332
+ store({ share, ...(password === undefined ? {} : { password }), item: { ...header, data: relay_bytes_1.RelayBytes.toBase64(data) } });
333
+ }
334
+ catch (_a) {
335
+ try {
336
+ store({ share, ...(password === undefined ? {} : { password }) });
337
+ }
338
+ catch (_b) {
339
+ // Kept nowhere: the page asks again.
340
+ }
341
+ }
342
+ }
343
+ RelayContentHandoff.keep = keep;
344
+ /** What was kept for `share`: the content opened, or its password. */
345
+ function take(share) {
346
+ var _a;
347
+ var _b;
348
+ try {
349
+ const kept = JSON.parse((_b = (_a = globalThis.sessionStorage) === null || _a === void 0 ? void 0 : _a.getItem(KEY)) !== null && _b !== void 0 ? _b : 'null');
350
+ if ((kept === null || kept === void 0 ? void 0 : kept.share) !== share) {
351
+ return {};
352
+ }
353
+ const item = kept.item && { ...kept.item, data: relay_bytes_1.RelayBytes.fromBase64(kept.item.data) };
354
+ return { ...(item ? { item } : {}), ...(kept.password === undefined ? {} : { password: kept.password }) };
355
+ }
356
+ catch (_c) {
357
+ return {};
358
+ }
359
+ }
360
+ RelayContentHandoff.take = take;
361
+ })(RelayContentHandoff || (exports.RelayContentHandoff = RelayContentHandoff = {}));
320
362
  //# sourceMappingURL=relay-content.js.map
@@ -27,6 +27,15 @@ export type RelayConversationMessage = {
27
27
  role: 'user';
28
28
  content: string | RelayConversationPart[];
29
29
  timestamp?: number;
30
+ }
31
+ /** What an extension showed in the conversation (pi's custom message with `display`): its card, drawn by its renderer. */
32
+ | {
33
+ role: 'custom';
34
+ customType: string;
35
+ content: string | RelayConversationPart[];
36
+ display: true;
37
+ details?: unknown;
38
+ timestamp?: number;
30
39
  } | {
31
40
  role: 'assistant';
32
41
  content: RelayConversationPart[];
@@ -49,6 +58,11 @@ export interface RelayConversation {
49
58
  /** The name of its directory, for a line under the title. */
50
59
  place?: string;
51
60
  messages: RelayConversationMessage[];
61
+ /**
62
+ * The pictures of the workspace its replies show (`![](shots/a.png)`), as data URLs by the path written there:
63
+ * the link shows them as the conversation did.
64
+ */
65
+ files?: Record<string, string>;
52
66
  /** What was left out when it was shared: the outputs of its tools, and how many images. */
53
67
  omitted?: {
54
68
  outputs?: boolean;
@@ -254,7 +254,7 @@ class RelayHub {
254
254
  this.send(socket, { t: 'error', code: 'invalid', message: 'An invitation needs a hash and a time.' });
255
255
  return;
256
256
  }
257
- meta.invite = { hash: request.hash, expiresAt: Math.min(request.expiresAt, this.now() + 30 * DAY_MS) };
257
+ meta.invite = { hash: request.hash, expiresAt: Math.min(request.expiresAt, this.now() + relay_protocol_1.RELAY_INVITE_MAX_DAYS * DAY_MS) };
258
258
  await this.storage.put('meta', meta);
259
259
  return;
260
260
  case 'admit':
@@ -0,0 +1,37 @@
1
+ import type { RelayFriends } from './relay-friends';
2
+ import { RelayHubsConnection } from './relay-hubs-connection';
3
+ import type { RelayIdentityBundle, RelayIdentityImport, RelayRoomRecord } from './relay-hubs-protocol';
4
+ import { type RelayIdentity, type RelayPublicIdentity } from './relay-identity';
5
+ export declare abstract class RelayHubsIdentity extends RelayHubsConnection {
6
+ protected abstract readonly book: RelayFriends;
7
+ /** The name others see; the owners of rooms this Ta is in hear it. */
8
+ setName(name: string): Promise<RelayPublicIdentity>;
9
+ /**
10
+ * The kind of dinosaur the double of this Ta is (RelayPublicIdentity.look), which others draw it by; none for a
11
+ * look that is none. The owners of rooms this Ta is in hear it, as a name.
12
+ */
13
+ setLook(look: string | undefined): Promise<RelayPublicIdentity>;
14
+ /** Keeps the identity with a new name or look, and tells the rooms this Ta is in. */
15
+ protected changeSelf(identity: RelayIdentity): Promise<RelayPublicIdentity>;
16
+ /** What makes this Ta who it is in rooms, private keys and all (RelayIdentityBundle): for the user's own computers alone. */
17
+ exportIdentity(): Promise<RelayIdentityBundle>;
18
+ /**
19
+ * Takes on the identity of the user's other computer, with its rooms and friends (a move, or the identity shared by
20
+ * sync). Another identity than this Ta's: each room this Ta is in keeps the identity it joined with
21
+ * (RelayRoomRecord.identity), new rooms are the other's. A room this Ta is in as another member is left as it is.
22
+ */
23
+ importIdentity(bundle: RelayIdentityBundle, options?: {
24
+ shared?: boolean;
25
+ }): Promise<RelayIdentityImport>;
26
+ /** Whether the user's other computers are this Ta too (RelayIdentity.shared). */
27
+ setShared(shared: boolean): Promise<void>;
28
+ /**
29
+ * A room as the user's other computer has it: added, or merged with this Ta's record of the same membership
30
+ * (RelayHubsUtil.merge), connected or not as its status says. False when nothing changed, or this Ta is in the room
31
+ * as another member.
32
+ */
33
+ upsert(record: RelayRoomRecord): boolean;
34
+ /** A room the user's other computer left or forgot: forgotten here, without a word to the relay (that computer said it). */
35
+ forget(roomId: string, member: string): boolean;
36
+ }
37
+ //# sourceMappingURL=relay-hubs-identity.d.ts.map