@celljs/ta-host 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 (105) hide show
  1. package/esm/node/app-commands.d.ts +111 -0
  2. package/esm/node/app-commands.js +629 -0
  3. package/esm/node/delegate-extension.d.ts +11 -0
  4. package/esm/node/delegate-extension.js +33 -0
  5. package/esm/node/directory-relocator.d.ts +49 -0
  6. package/esm/node/directory-relocator.js +267 -0
  7. package/esm/node/exec-endpoint.d.ts +14 -0
  8. package/esm/node/exec-endpoint.js +48 -0
  9. package/esm/node/extension-providers.d.ts +16 -1
  10. package/esm/node/extension-providers.js +23 -3
  11. package/esm/node/gateway-models.d.ts +38 -0
  12. package/esm/node/gateway-models.js +124 -0
  13. package/esm/node/index.d.ts +8 -0
  14. package/esm/node/index.js +8 -0
  15. package/esm/node/keep-awake.d.ts +5 -1
  16. package/esm/node/keep-awake.js +18 -2
  17. package/esm/node/message-page.d.ts +6 -1
  18. package/esm/node/message-page.js +50 -2
  19. package/esm/node/package-hosts.d.ts +6 -0
  20. package/esm/node/package-hosts.js +35 -0
  21. package/esm/node/package-webhooks.d.ts +26 -0
  22. package/esm/node/package-webhooks.js +101 -0
  23. package/esm/node/page-book.d.ts +48 -0
  24. package/esm/node/page-book.js +117 -0
  25. package/esm/node/relay-bridge.d.ts +2 -0
  26. package/esm/node/relay-bridge.js +35 -1
  27. package/esm/node/remote/cloud-hosts.d.ts +40 -0
  28. package/esm/node/remote/cloud-hosts.js +99 -0
  29. package/esm/node/remote/index.d.ts +1 -0
  30. package/esm/node/remote/index.js +1 -0
  31. package/esm/node/remote/pi-directories.d.ts +2 -1
  32. package/esm/node/remote/pi-directories.js +7 -2
  33. package/esm/node/remote/remote-hosts.d.ts +5 -0
  34. package/esm/node/remote/remote-hosts.js +71 -2
  35. package/esm/node/remote/remote-protocol.d.ts +2 -0
  36. package/esm/node/remote/remote-server-impl.d.ts +1 -0
  37. package/esm/node/remote/remote-server-impl.js +3 -0
  38. package/esm/node/rooms-bridge.d.ts +3 -0
  39. package/esm/node/rooms-bridge.js +4 -0
  40. package/esm/node/session-info-util.d.ts +3 -1
  41. package/esm/node/session-info-util.js +32 -6
  42. package/esm/node/ta-server-impl.d.ts +5 -1
  43. package/esm/node/ta-server-impl.js +22 -0
  44. package/esm/node/ta-session-factory.d.ts +13 -1
  45. package/esm/node/ta-session-factory.js +39 -4
  46. package/esm/node/ta-session.d.ts +2 -0
  47. package/esm/node/ta-session.js +1 -0
  48. package/esm/node/team/team-calls.js +23 -0
  49. package/esm/node/voice-bridge.d.ts +68 -0
  50. package/esm/node/voice-bridge.js +273 -0
  51. package/esm/node/voices-file.d.ts +33 -0
  52. package/esm/node/voices-file.js +89 -0
  53. package/lib/node/app-commands.d.ts +112 -0
  54. package/lib/node/app-commands.js +633 -0
  55. package/lib/node/delegate-extension.d.ts +12 -0
  56. package/lib/node/delegate-extension.js +37 -0
  57. package/lib/node/directory-relocator.d.ts +50 -0
  58. package/lib/node/directory-relocator.js +270 -0
  59. package/lib/node/exec-endpoint.d.ts +15 -0
  60. package/lib/node/exec-endpoint.js +51 -0
  61. package/lib/node/extension-providers.d.ts +16 -1
  62. package/lib/node/extension-providers.js +23 -3
  63. package/lib/node/gateway-models.d.ts +39 -0
  64. package/lib/node/gateway-models.js +127 -0
  65. package/lib/node/index.d.ts +8 -0
  66. package/lib/node/index.js +8 -0
  67. package/lib/node/keep-awake.d.ts +5 -1
  68. package/lib/node/keep-awake.js +18 -2
  69. package/lib/node/message-page.d.ts +6 -1
  70. package/lib/node/message-page.js +50 -2
  71. package/lib/node/package-hosts.d.ts +6 -0
  72. package/lib/node/package-hosts.js +35 -0
  73. package/lib/node/package-webhooks.d.ts +27 -0
  74. package/lib/node/package-webhooks.js +104 -0
  75. package/lib/node/page-book.d.ts +49 -0
  76. package/lib/node/page-book.js +120 -0
  77. package/lib/node/relay-bridge.d.ts +2 -0
  78. package/lib/node/relay-bridge.js +34 -0
  79. package/lib/node/remote/cloud-hosts.d.ts +41 -0
  80. package/lib/node/remote/cloud-hosts.js +103 -0
  81. package/lib/node/remote/index.d.ts +1 -0
  82. package/lib/node/remote/index.js +1 -0
  83. package/lib/node/remote/pi-directories.d.ts +2 -1
  84. package/lib/node/remote/pi-directories.js +7 -2
  85. package/lib/node/remote/remote-hosts.d.ts +5 -0
  86. package/lib/node/remote/remote-hosts.js +71 -2
  87. package/lib/node/remote/remote-protocol.d.ts +2 -0
  88. package/lib/node/remote/remote-server-impl.d.ts +1 -0
  89. package/lib/node/remote/remote-server-impl.js +3 -0
  90. package/lib/node/rooms-bridge.d.ts +3 -0
  91. package/lib/node/rooms-bridge.js +4 -0
  92. package/lib/node/session-info-util.d.ts +3 -1
  93. package/lib/node/session-info-util.js +31 -5
  94. package/lib/node/ta-server-impl.d.ts +5 -1
  95. package/lib/node/ta-server-impl.js +22 -0
  96. package/lib/node/ta-session-factory.d.ts +13 -1
  97. package/lib/node/ta-session-factory.js +38 -3
  98. package/lib/node/ta-session.d.ts +2 -0
  99. package/lib/node/ta-session.js +1 -0
  100. package/lib/node/team/team-calls.js +23 -0
  101. package/lib/node/voice-bridge.d.ts +69 -0
  102. package/lib/node/voice-bridge.js +274 -0
  103. package/lib/node/voices-file.d.ts +34 -0
  104. package/lib/node/voices-file.js +93 -0
  105. package/package.json +10 -10
@@ -1,16 +1,22 @@
1
+ export * from './app-commands.js';
1
2
  export * from './auth-server-impl.js';
2
3
  export * from './client-channel.js';
3
4
  export * from './client-tool-broker.js';
5
+ export * from './directory-relocator.js';
4
6
  export * from './event-log.js';
7
+ export * from './exec-endpoint.js';
5
8
  export * from './exec-environment-factory.js';
6
9
  export * from './extension-data.js';
7
10
  export * from './extension-data-notifier.js';
8
11
  export * from './extension-providers.js';
12
+ export * from './gateway-models.js';
9
13
  export * from './host-protocol.js';
10
14
  export * from './keep-awake.js';
11
15
  export * from './package-host-extension.js';
12
16
  export * from './package-hosts.js';
13
17
  export * from './package-server-impl.js';
18
+ export * from './package-webhooks.js';
19
+ export * from './page-book.js';
14
20
  export * from './presence-book.js';
15
21
  export * from './presence-server-impl.js';
16
22
  export * from './receipt-book.js';
@@ -42,6 +48,8 @@ export * from './terminal-protocol.js';
42
48
  export * from './terminal-service.js';
43
49
  export * from './terminal-util.js';
44
50
  export * from './usage/index.js';
51
+ export * from './voice-bridge.js';
52
+ export * from './voices-file.js';
45
53
  export * from './web-extension-catalog.js';
46
54
  export * from './web-extension-util.js';
47
55
  export * from './working-directory.js';
package/esm/node/index.js CHANGED
@@ -1,16 +1,22 @@
1
+ export * from './app-commands.js';
1
2
  export * from './auth-server-impl.js';
2
3
  export * from './client-channel.js';
3
4
  export * from './client-tool-broker.js';
5
+ export * from './directory-relocator.js';
4
6
  export * from './event-log.js';
7
+ export * from './exec-endpoint.js';
5
8
  export * from './exec-environment-factory.js';
6
9
  export * from './extension-data.js';
7
10
  export * from './extension-data-notifier.js';
8
11
  export * from './extension-providers.js';
12
+ export * from './gateway-models.js';
9
13
  export * from './host-protocol.js';
10
14
  export * from './keep-awake.js';
11
15
  export * from './package-host-extension.js';
12
16
  export * from './package-hosts.js';
13
17
  export * from './package-server-impl.js';
18
+ export * from './package-webhooks.js';
19
+ export * from './page-book.js';
14
20
  export * from './presence-book.js';
15
21
  export * from './presence-server-impl.js';
16
22
  export * from './receipt-book.js';
@@ -42,6 +48,8 @@ export * from './terminal-protocol.js';
42
48
  export * from './terminal-service.js';
43
49
  export * from './terminal-util.js';
44
50
  export * from './usage/index.js';
51
+ export * from './voice-bridge.js';
52
+ export * from './voices-file.js';
45
53
  export * from './web-extension-catalog.js';
46
54
  export * from './web-extension-util.js';
47
55
  export * from './working-directory.js';
@@ -22,7 +22,9 @@ export declare namespace KeepAwakeUtil {
22
22
  /**
23
23
  * Keeps the computer from sleeping while idle as long as a session runs or a paired device was connected of
24
24
  * late: asleep, ta serve answers no phone, and a phone that cannot reach it cannot wake it. It holds
25
- * `caffeinate -i` (idle sleep only: the display sleeps, a closed lid sleeps), which ends with ta serve.
25
+ * `caffeinate -i -s`, which ends with ta serve: idle sleep, and on power any sleep but of a closed lid, since a Mac
26
+ * that slept wakes only in the dark for minutes, where an assertion of idle sleep does not keep it; the display
27
+ * still sleeps. Stopping while it held it, it leaves one of BRIDGE_S, for the Ta that starts after.
26
28
  * Turned off in relay.json (TaRelayServer.setKeepAwake); nothing where it is not supported.
27
29
  */
28
30
  export declare class KeepAwakeImpl implements KeepAwake, ApplicationLifecycle<Application> {
@@ -41,4 +43,6 @@ export declare class KeepAwakeImpl implements KeepAwake, ApplicationLifecycle<Ap
41
43
  protected release(): void;
42
44
  /** `-w`: it ends when this process does, killed too. */
43
45
  protected spawn(): ChildProcess;
46
+ /** Awake for a while after this process, on its own. */
47
+ protected spawnBridge(): ChildProcess;
44
48
  }
@@ -27,10 +27,17 @@ export var KeepAwakeUtil;
27
27
  })(KeepAwakeUtil || (KeepAwakeUtil = {}));
28
28
  /** How often what keeps the computer awake is looked at. */
29
29
  const CHECK_MS = 15000;
30
+ /**
31
+ * How long the computer stays awake after ta serve stops while it held it: a restart of Ta (an update, Restart Ta)
32
+ * takes seconds, and a Mac idle past its sleep time falls asleep the moment the assertion goes, before the new one.
33
+ */
34
+ const BRIDGE_S = 120;
30
35
  /**
31
36
  * Keeps the computer from sleeping while idle as long as a session runs or a paired device was connected of
32
37
  * late: asleep, ta serve answers no phone, and a phone that cannot reach it cannot wake it. It holds
33
- * `caffeinate -i` (idle sleep only: the display sleeps, a closed lid sleeps), which ends with ta serve.
38
+ * `caffeinate -i -s`, which ends with ta serve: idle sleep, and on power any sleep but of a closed lid, since a Mac
39
+ * that slept wakes only in the dark for minutes, where an assertion of idle sleep does not keep it; the display
40
+ * still sleeps. Stopping while it held it, it leaves one of BRIDGE_S, for the Ta that starts after.
34
41
  * Turned off in relay.json (TaRelayServer.setKeepAwake); nothing where it is not supported.
35
42
  */
36
43
  let KeepAwakeImpl = class KeepAwakeImpl {
@@ -51,10 +58,15 @@ let KeepAwakeImpl = class KeepAwakeImpl {
51
58
  }
52
59
  this.timer = setInterval(() => this.check(), CHECK_MS);
53
60
  (_b = (_a = this.timer).unref) === null || _b === void 0 ? void 0 : _b.call(_a);
61
+ this.check();
54
62
  }
55
63
  onStop() {
56
64
  clearInterval(this.timer);
65
+ const held = this.held;
57
66
  this.release();
67
+ if (held) {
68
+ this.spawnBridge().unref();
69
+ }
58
70
  }
59
71
  check(now = Date.now()) {
60
72
  if (!this.supported) {
@@ -94,7 +106,11 @@ let KeepAwakeImpl = class KeepAwakeImpl {
94
106
  }
95
107
  /** `-w`: it ends when this process does, killed too. */
96
108
  spawn() {
97
- return spawn('/usr/bin/caffeinate', ['-i', '-w', String(process.pid)], { stdio: 'ignore' });
109
+ return spawn('/usr/bin/caffeinate', ['-i', '-s', '-w', String(process.pid)], { stdio: 'ignore' });
110
+ }
111
+ /** Awake for a while after this process, on its own. */
112
+ spawnBridge() {
113
+ return spawn('/usr/bin/caffeinate', ['-i', '-s', '-t', String(BRIDGE_S)], { stdio: 'ignore', detached: true });
98
114
  }
99
115
  };
100
116
  __decorate([
@@ -1,4 +1,4 @@
1
- import type { TaConversation, TaMessage, TaMessagePage } from '@celljs/ta-protocol';
1
+ import type { TaConversation, TaMessage, TaMessagePage, TaTurnHead } from '@celljs/ta-protocol';
2
2
  /**
3
3
  * The parts of a long conversation a client loads one at a time, the latest first: about so many bytes
4
4
  * of JSON each, as the client gets them.
@@ -10,6 +10,11 @@ export declare namespace MessagePage {
10
10
  * asked for their turn if that takes no more than twice the budget, so that a turn shows whole.
11
11
  */
12
12
  function start(messages: readonly TaMessage[], end: number, budget: number): number;
13
+ /**
14
+ * When the messages from `from` start in the middle of a turn (the first of the user or the agent among them
15
+ * is a step of it): the message of the user that asked for the turn.
16
+ */
17
+ function head(messages: readonly TaMessage[], from: number): TaTurnHead | undefined;
13
18
  /** The latest part of a conversation, or all of it without a budget. */
14
19
  function recent(conversation: TaConversation, budget: number | undefined): TaConversation;
15
20
  /** The part before message `before`, found again by its timestamp if messages came or went before it. */
@@ -42,13 +42,60 @@ export var MessagePage;
42
42
  return start;
43
43
  }
44
44
  MessagePage.start = start;
45
+ /**
46
+ * A message of the user that the agent was given on the way, after the result of a tool it was written before:
47
+ * a step of the turn, not the start of another (as the web page reads it).
48
+ */
49
+ function steered(messages, index) {
50
+ var _a;
51
+ if (role(messages[index]) !== 'user') {
52
+ return false;
53
+ }
54
+ for (let before = index - 1; before >= 0; before--) {
55
+ const was = (_a = role(messages[before])) !== null && _a !== void 0 ? _a : '';
56
+ if (was === 'user') {
57
+ return steered(messages, before);
58
+ }
59
+ if (TURN_ROLES.has(was)) {
60
+ const at = timestamp(messages[index]);
61
+ const came = timestamp(messages[before]);
62
+ return was === 'toolResult' && at !== undefined && came !== undefined && at < came;
63
+ }
64
+ }
65
+ return false;
66
+ }
67
+ /**
68
+ * When the messages from `from` start in the middle of a turn (the first of the user or the agent among them
69
+ * is a step of it): the message of the user that asked for the turn.
70
+ */
71
+ function head(messages, from) {
72
+ var _a;
73
+ let first = from;
74
+ while (first < messages.length && role(messages[first]) !== 'user' && !TURN_ROLES.has((_a = role(messages[first])) !== null && _a !== void 0 ? _a : '')) {
75
+ first++;
76
+ }
77
+ if (from <= 0 || first >= messages.length || (role(messages[first]) === 'user' && !steered(messages, first))) {
78
+ return undefined;
79
+ }
80
+ for (let index = from - 1; index >= 0; index--) {
81
+ if (role(messages[index]) === 'user' && !steered(messages, index)) {
82
+ return { index, message: messages[index] };
83
+ }
84
+ }
85
+ return undefined;
86
+ }
87
+ MessagePage.head = head;
45
88
  /** The latest part of a conversation, or all of it without a budget. */
46
89
  function recent(conversation, budget) {
47
90
  if (!budget || budget <= 0) {
48
91
  return conversation;
49
92
  }
50
93
  const from = start(conversation.messages, conversation.messages.length, budget);
51
- return from === 0 ? conversation : { ...conversation, messages: conversation.messages.slice(from), start: from };
94
+ if (from === 0) {
95
+ return conversation;
96
+ }
97
+ const turn = head(conversation.messages, from);
98
+ return { ...conversation, messages: conversation.messages.slice(from), start: from, ...(turn ? { head: turn } : {}) };
52
99
  }
53
100
  MessagePage.recent = recent;
54
101
  /** The part before message `before`, found again by its timestamp if messages came or went before it. */
@@ -64,7 +111,8 @@ export var MessagePage;
64
111
  }
65
112
  }
66
113
  const from = start(messages, end, Math.max(1, budget));
67
- return { messages: messages.slice(from, end), start: from, found: true };
114
+ const turn = head(messages, from);
115
+ return { messages: messages.slice(from, end), start: from, found: true, ...(turn ? { head: turn } : {}) };
68
116
  }
69
117
  MessagePage.before = before;
70
118
  })(MessagePage || (MessagePage = {}));
@@ -1,13 +1,16 @@
1
1
  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
+ import { TaAppCommands } from './app-commands.js';
4
5
  import { ExtensionDataStore } from './extension-data.js';
5
6
  import { TaPresenceBook, TaSessionRegistry } from './host-protocol.js';
7
+ import { TaPageBook } from './page-book.js';
6
8
  import { type RelayBridge } from './relay-bridge.js';
7
9
  import { PiDirectories } from './remote/remote-protocol.js';
8
10
  import { type RoomsBridge } from './rooms-bridge.js';
9
11
  import { TaSettingsStore } from './settings-store.js';
10
12
  import { TaHostTeamProvider } from './team/team-protocol.js';
13
+ import { type VoiceBridge } from './voice-bridge.js';
11
14
  export declare const PackageHosts: unique symbol;
12
15
  /**
13
16
  * The server side of built-in packages under `ta serve`: the module a package names in `pi.host` of its
@@ -54,9 +57,12 @@ export declare class PackageHostsImpl implements PackageHosts, ApplicationLifecy
54
57
  protected readonly packages: TaPackageServer;
55
58
  protected readonly relay: RelayBridge;
56
59
  protected readonly roomsBridge: RoomsBridge;
60
+ protected readonly voiceBridge: VoiceBridge;
57
61
  protected readonly settings: TaSettingsStore;
58
62
  protected readonly sessions: TaSessionRegistry;
59
63
  protected readonly presenceBook: TaPresenceBook;
64
+ protected readonly appCommands: TaAppCommands;
65
+ protected readonly pageBook: TaPageBook;
60
66
  protected readonly teamProvider: TaHostTeamProvider;
61
67
  protected readonly running: Map<string, Running>;
62
68
  protected extensionHost?: TaExtensionHost;
@@ -16,14 +16,18 @@ import { ApplicationLifecycle, Autowired, Component, Value } from '@celljs/core'
16
16
  import { TaBrand } from '@celljs/ta-harness/lib/node/ta-brand';
17
17
  import { TaPackages } from '@celljs/ta-harness/lib/node/ta-packages';
18
18
  import { TaMessageSource, TaPackageServer, TaServer, } from '@celljs/ta-protocol';
19
+ import { TaAppCommands } from './app-commands.js';
19
20
  import { ExtensionDataStore } from './extension-data.js';
20
21
  import { TaPresenceBook, TaSessionRegistry } from './host-protocol.js';
22
+ import { TaPageBook } from './page-book.js';
21
23
  import { RELAY_BRIDGE } from './relay-bridge.js';
22
24
  import { PiDirectories } from './remote/remote-protocol.js';
23
25
  import { ROOMS_BRIDGE } from './rooms-bridge.js';
26
+ import { SessionCatalogUtil } from './session-catalog.js';
24
27
  import { TaSettingsStore } from './settings-store.js';
25
28
  import { TaErrors } from './ta-errors.js';
26
29
  import { TaHostTeamProvider } from './team/team-protocol.js';
30
+ import { VOICE_BRIDGE } from './voice-bridge.js';
27
31
  export const PackageHosts = Symbol('PackageHosts');
28
32
  export var PackageHostUtil;
29
33
  (function (PackageHostUtil) {
@@ -155,6 +159,7 @@ let PackageHostsImpl = class PackageHostsImpl {
155
159
  var _a, _b;
156
160
  const running = this.running.get(name);
157
161
  this.running.delete(name);
162
+ this.appCommands.dropOwner(name);
158
163
  try {
159
164
  await ((_b = (_a = (await (running === null || running === void 0 ? void 0 : running.service))) === null || _a === void 0 ? void 0 : _a.dispose) === null || _b === void 0 ? void 0 : _b.call(_a));
160
165
  }
@@ -168,6 +173,12 @@ let PackageHostsImpl = class PackageHostsImpl {
168
173
  const mark = (input) => ({ ...input, message: TaMessageSource.mark(input.message, name) });
169
174
  return {
170
175
  ...host,
176
+ commands: { ...host.commands, register: command => this.appCommands.registerOf(name, command) },
177
+ // A package asks the requests of its own web extension (`pi.ui.answer`), named after it.
178
+ pages: {
179
+ ask: (kind, payload, options = {}) => this.pageBook.ask(this.pageBook.principalOf(options), `${name}/${kind}`, payload, options.timeoutMs),
180
+ has: (kind, options = {}) => this.pageBook.has(this.pageBook.principalOf(options), `${name}/${kind}`),
181
+ },
171
182
  prompt: (sessionId, input) => host.prompt(sessionId, mark(input)),
172
183
  followUp: (sessionId, input) => host.followUp(sessionId, mark(input)),
173
184
  };
@@ -188,7 +199,9 @@ let PackageHostsImpl = class PackageHostsImpl {
188
199
  shares: this.relay.shares,
189
200
  rooms: this.roomsBridge.rooms,
190
201
  relays: this.relay.extensionRelays,
202
+ voices: this.voiceBridge.extensionVoices,
191
203
  sessionMessages: file => this.sessionMessages(file),
204
+ sessionRole: async (file) => SessionCatalogUtil.roleOf((await PiSdkUtil.load()).SessionManager.open(file).getEntries()),
192
205
  createSession: (cwd, messages, name) => this.createSession(cwd, messages, name),
193
206
  getServerInfo: () => server.getServerInfo(),
194
207
  listSessions: () => server.listSessions(),
@@ -200,6 +213,7 @@ let PackageHostsImpl = class PackageHostsImpl {
200
213
  abort: sessionId => server.abort(sessionId),
201
214
  getState: sessionId => server.getState(sessionId),
202
215
  getLastAssistantText: sessionId => server.getLastAssistantText(sessionId),
216
+ relocateDirectory: (from, to) => server.relocateDirectory(from, to),
203
217
  getExtensionData: (name, key, cwd) => packages.getExtensionData(name, key, cwd),
204
218
  setExtensionData: (name, key, value, cwd) => packages.setExtensionData(name, key, value, cwd),
205
219
  onExtensionData: listener => this.data.onChange(listener),
@@ -211,6 +225,15 @@ let PackageHostsImpl = class PackageHostsImpl {
211
225
  }),
212
226
  presence: () => ({ pages: this.sessions.watching, seenAt: this.sessions.watchedAt, people: this.presenceBook.everyone() }),
213
227
  team: this.teamProvider.team,
228
+ commands: {
229
+ list: () => this.appCommands.list(),
230
+ run: (id, input, options) => this.appCommands.run(id, input, options),
231
+ register: command => this.appCommands.register(command),
232
+ },
233
+ pages: {
234
+ ask: () => Promise.reject(new Error('Only a package asks a page: through its own host.')),
235
+ has: () => false,
236
+ },
214
237
  installPackage: (source, scope, cwd) => packages.installPackage(source, scope, cwd),
215
238
  removePackage: (id, cwd) => packages.removePackage(id, cwd),
216
239
  updateSettings: update => this.settings.rewriteUser(update),
@@ -273,6 +296,10 @@ __decorate([
273
296
  Autowired({ id: ROOMS_BRIDGE, detached: true }),
274
297
  __metadata("design:type", Function)
275
298
  ], PackageHostsImpl.prototype, "roomsBridge", void 0);
299
+ __decorate([
300
+ Autowired({ id: VOICE_BRIDGE, detached: true }),
301
+ __metadata("design:type", Function)
302
+ ], PackageHostsImpl.prototype, "voiceBridge", void 0);
276
303
  __decorate([
277
304
  Autowired({ id: TaSettingsStore, detached: true }),
278
305
  __metadata("design:type", Object)
@@ -285,6 +312,14 @@ __decorate([
285
312
  Autowired({ id: TaPresenceBook, detached: true }),
286
313
  __metadata("design:type", Object)
287
314
  ], PackageHostsImpl.prototype, "presenceBook", void 0);
315
+ __decorate([
316
+ Autowired({ id: TaAppCommands, detached: true }),
317
+ __metadata("design:type", Object)
318
+ ], PackageHostsImpl.prototype, "appCommands", void 0);
319
+ __decorate([
320
+ Autowired({ id: TaPageBook, detached: true }),
321
+ __metadata("design:type", Object)
322
+ ], PackageHostsImpl.prototype, "pageBook", void 0);
288
323
  __decorate([
289
324
  Autowired({ id: TaHostTeamProvider, detached: true }),
290
325
  __metadata("design:type", Object)
@@ -0,0 +1,26 @@
1
+ import type { IncomingMessage } from 'node:http';
2
+ import { type Context, Middleware } from '@celljs/web/lib/node';
3
+ import { PackageHosts } from './package-hosts.js';
4
+ /** Where ta serve takes the webhooks of packages: the directory name of a package, then its own path. */
5
+ export declare const WEBHOOK_PATH = "/api/hooks/";
6
+ export declare namespace PackageWebhookUtil {
7
+ /** The package and its path of a request to a webhook; undefined for another request. */
8
+ function target(request: Pick<IncomingMessage, 'url'>): {
9
+ name: string;
10
+ path: string;
11
+ } | undefined;
12
+ /** The body as text; undefined when it is larger than TA_WEBHOOK_MAX_BYTES. */
13
+ function body(request: IncomingMessage): Promise<string | undefined>;
14
+ }
15
+ /**
16
+ * The webhooks of the packages that come with Ta (TaPackageService.webhook): a POST to `/api/hooks/<package>/<path>`
17
+ * goes to its host without the token of ta serve; the package checks the secret of its path. Anything else (another
18
+ * method, a package without a webhook, a secret it does not know) is a 404 that says nothing more.
19
+ */
20
+ export declare class PackageWebhooks implements Middleware {
21
+ /** Before TaAccess, which would ask for the token. */
22
+ readonly priority: number;
23
+ protected readonly hosts: PackageHosts;
24
+ protected readonly host?: string;
25
+ handle(ctx: Context, next: () => Promise<void>): Promise<void>;
26
+ }
@@ -0,0 +1,101 @@
1
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
2
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
3
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
4
+ 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;
5
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
6
+ };
7
+ var __metadata = (this && this.__metadata) || function (k, v) {
8
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
9
+ };
10
+ import { Autowired, Component, Value } from '@celljs/core';
11
+ import { TaPackages } from '@celljs/ta-harness/lib/node/ta-packages';
12
+ import { TA_WEBHOOK_MAX_BYTES } from '@celljs/ta-protocol';
13
+ import { Middleware } from '@celljs/web/lib/node';
14
+ import { PackageHosts } from './package-hosts.js';
15
+ import { ACCESS_MIDDLEWARE_PRIORITY, TaAccessUtil } from './ta-access.js';
16
+ /** Where ta serve takes the webhooks of packages: the directory name of a package, then its own path. */
17
+ export const WEBHOOK_PATH = '/api/hooks/';
18
+ export var PackageWebhookUtil;
19
+ (function (PackageWebhookUtil) {
20
+ /** The package and its path of a request to a webhook; undefined for another request. */
21
+ function target(request) {
22
+ var _a;
23
+ const path = ((_a = request.url) !== null && _a !== void 0 ? _a : '/').split('?')[0];
24
+ if (!path.startsWith(WEBHOOK_PATH)) {
25
+ return undefined;
26
+ }
27
+ const [directory, ...rest] = path.slice(WEBHOOK_PATH.length).split('/');
28
+ const name = TaPackages.BUILTIN.find(builtin => TaPackages.directoryName(builtin) === directory);
29
+ return name ? { name, path: rest.map(part => decodeURIComponent(part)).join('/') } : { name: '', path: '' };
30
+ }
31
+ PackageWebhookUtil.target = target;
32
+ /** The body as text; undefined when it is larger than TA_WEBHOOK_MAX_BYTES. */
33
+ async function body(request) {
34
+ const chunks = [];
35
+ let size = 0;
36
+ for await (const chunk of request) {
37
+ size += chunk.length;
38
+ if (size > TA_WEBHOOK_MAX_BYTES) {
39
+ return undefined;
40
+ }
41
+ chunks.push(chunk);
42
+ }
43
+ return Buffer.concat(chunks).toString('utf8');
44
+ }
45
+ PackageWebhookUtil.body = body;
46
+ })(PackageWebhookUtil || (PackageWebhookUtil = {}));
47
+ function end(response, status, value) {
48
+ response.statusCode = status;
49
+ response.setHeader('Content-Type', 'application/json; charset=utf-8');
50
+ response.end(JSON.stringify(value));
51
+ }
52
+ /**
53
+ * The webhooks of the packages that come with Ta (TaPackageService.webhook): a POST to `/api/hooks/<package>/<path>`
54
+ * goes to its host without the token of ta serve; the package checks the secret of its path. Anything else (another
55
+ * method, a package without a webhook, a secret it does not know) is a 404 that says nothing more.
56
+ */
57
+ let PackageWebhooks = class PackageWebhooks {
58
+ constructor() {
59
+ /** Before TaAccess, which would ask for the token. */
60
+ this.priority = ACCESS_MIDDLEWARE_PRIORITY + 2;
61
+ }
62
+ async handle(ctx, next) {
63
+ const request = ctx.request;
64
+ const target = PackageWebhookUtil.target(request);
65
+ if (!target) {
66
+ await next();
67
+ return;
68
+ }
69
+ const response = ctx.response;
70
+ // A page that rebinds its domain to a ta serve of 127.0.0.1 reaches nothing, as with TaAccess.
71
+ if (!target.name || request.method !== 'POST' || (TaAccessUtil.isLoopbackHost(this.host) && !TaAccessUtil.isLoopbackHost(request.headers.host))) {
72
+ end(response, 404, { error: 'Not found' });
73
+ return;
74
+ }
75
+ const body = await PackageWebhookUtil.body(request);
76
+ if (body === undefined) {
77
+ end(response, 413, { error: 'Too large' });
78
+ return;
79
+ }
80
+ try {
81
+ const answer = await this.hosts.call(target.name, 'webhook', [{ path: target.path, body, contentType: request.headers['content-type'] }]);
82
+ end(response, 202, answer !== null && answer !== void 0 ? answer : { ok: true });
83
+ }
84
+ catch (_a) {
85
+ end(response, 404, { error: 'Not found' });
86
+ }
87
+ }
88
+ };
89
+ __decorate([
90
+ Autowired(PackageHosts),
91
+ __metadata("design:type", Object)
92
+ ], PackageWebhooks.prototype, "hosts", void 0);
93
+ __decorate([
94
+ Value('server.host'),
95
+ __metadata("design:type", String)
96
+ ], PackageWebhooks.prototype, "host", void 0);
97
+ PackageWebhooks = __decorate([
98
+ Component(Middleware)
99
+ ], PackageWebhooks);
100
+ export { PackageWebhooks };
101
+ //# sourceMappingURL=package-webhooks.js.map
@@ -0,0 +1,48 @@
1
+ import { type RpcConnection } from '@celljs/rpc/lib/node';
2
+ import { type TaPageAskOptions, type TaPageInfo, TaPageServer } from '@celljs/ta-protocol';
3
+ import { TaHostTeamProvider, TaPrincipals } from './team/team-protocol.js';
4
+ export declare const TaPageBook: unique symbol;
5
+ /** The pages that answer requests (TaPageServer.attach), by connection, in memory only. */
6
+ export interface TaPageBook {
7
+ attach(connection: RpcConnection, info: TaPageInfo): void;
8
+ /** Asks the page of `principal` that answers `kind` (PageChoice.pick) and resolves to its answer. */
9
+ ask(principal: string, kind: string, payload: unknown, timeoutMs?: number): Promise<unknown>;
10
+ has(principal: string, kind: string): boolean;
11
+ /** Whom a package's request is for: who asked the run of the session file, or the principal given. */
12
+ principalOf(options: TaPageAskOptions): string;
13
+ }
14
+ /** A page as the book keeps it. */
15
+ export interface PageEntry {
16
+ principal: string;
17
+ info: TaPageInfo;
18
+ /** `Date.now()` time it was last said active, or attached. */
19
+ activeAt: number;
20
+ }
21
+ export declare namespace PageChoice {
22
+ /**
23
+ * The page to ask among those of one person that answer the kind: the one in front of them, the latest touched of
24
+ * those; else the window of Ta Desktop, kept while closed; else the latest touched.
25
+ */
26
+ function pick<T extends PageEntry>(entries: readonly T[]): T | undefined;
27
+ /** What a page said of itself, made safe: only strings of kinds, a device it knows. */
28
+ function clean(info: TaPageInfo | undefined): TaPageInfo;
29
+ }
30
+ export declare class DefaultTaPageBook implements TaPageBook {
31
+ protected readonly principals: TaPrincipals;
32
+ protected readonly teamProvider: TaHostTeamProvider;
33
+ protected readonly entries: Map<RpcConnection, PageEntry & {
34
+ connection: RpcConnection;
35
+ }>;
36
+ attach(connection: RpcConnection, info: TaPageInfo): void;
37
+ ask(principal: string, kind: string, payload: unknown, timeoutMs?: number): Promise<unknown>;
38
+ has(principal: string, kind: string): boolean;
39
+ principalOf(options: TaPageAskOptions): string;
40
+ protected of(principal: string, kind: string): (PageEntry & {
41
+ connection: RpcConnection;
42
+ })[];
43
+ }
44
+ /** A page says which requests it answers (TaPageServer). */
45
+ export declare class TaPageServerImpl implements TaPageServer {
46
+ protected readonly book: TaPageBook;
47
+ attach(info: TaPageInfo): Promise<void>;
48
+ }
@@ -0,0 +1,117 @@
1
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
2
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
3
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
4
+ 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;
5
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
6
+ };
7
+ var __metadata = (this && this.__metadata) || function (k, v) {
8
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
9
+ };
10
+ import { Autowired, Component } from '@celljs/core';
11
+ import { Rpc } from '@celljs/rpc';
12
+ import { RpcContext } from '@celljs/rpc/lib/node';
13
+ import { TA_OWNER, TA_PAGE_ASK_MS, TaClient, TaPageServer } from '@celljs/ta-protocol';
14
+ import { TaErrors } from './ta-errors.js';
15
+ import { TaHostTeamProvider, TaPrincipals } from './team/team-protocol.js';
16
+ export const TaPageBook = Symbol('TaPageBook');
17
+ export var PageChoice;
18
+ (function (PageChoice) {
19
+ /**
20
+ * The page to ask among those of one person that answer the kind: the one in front of them, the latest touched of
21
+ * those; else the window of Ta Desktop, kept while closed; else the latest touched.
22
+ */
23
+ function pick(entries) {
24
+ var _a, _b;
25
+ const latest = (list) => list.reduce((best, one) => (!best || one.activeAt > best.activeAt ? one : best), undefined);
26
+ return (_b = (_a = latest(entries.filter(entry => entry.info.visible))) !== null && _a !== void 0 ? _a : latest(entries.filter(entry => entry.info.desktop))) !== null && _b !== void 0 ? _b : latest(entries);
27
+ }
28
+ PageChoice.pick = pick;
29
+ /** What a page said of itself, made safe: only strings of kinds, a device it knows. */
30
+ function clean(info) {
31
+ const kinds = Array.isArray(info === null || info === void 0 ? void 0 : info.kinds) ? info.kinds.filter(kind => typeof kind === 'string' && kind.length <= 100).slice(0, 100) : [];
32
+ const device = (info === null || info === void 0 ? void 0 : info.device) === 'phone' || (info === null || info === void 0 ? void 0 : info.device) === 'tablet' ? info.device : 'computer';
33
+ return { kinds, device, ...((info === null || info === void 0 ? void 0 : info.desktop) === true ? { desktop: true } : {}), ...((info === null || info === void 0 ? void 0 : info.visible) === true ? { visible: true } : {}) };
34
+ }
35
+ PageChoice.clean = clean;
36
+ })(PageChoice || (PageChoice = {}));
37
+ let DefaultTaPageBook = class DefaultTaPageBook {
38
+ constructor() {
39
+ this.entries = new Map();
40
+ }
41
+ attach(connection, info) {
42
+ if (connection.closed) {
43
+ return;
44
+ }
45
+ const before = this.entries.get(connection);
46
+ const clean = PageChoice.clean(info);
47
+ this.entries.set(connection, {
48
+ connection,
49
+ principal: this.principals.of(connection),
50
+ info: clean,
51
+ activeAt: (info === null || info === void 0 ? void 0 : info.active) === true || !before ? Date.now() : before.activeAt,
52
+ });
53
+ if (!before) {
54
+ connection.onClose(() => this.entries.delete(connection));
55
+ }
56
+ }
57
+ async ask(principal, kind, payload, timeoutMs = TA_PAGE_ASK_MS) {
58
+ const page = PageChoice.pick(this.of(principal, kind));
59
+ if (!page) {
60
+ throw TaErrors.invalidArgument('No page of Ta is open for this.', 'The user opens Ta on a phone or a computer; meanwhile do it without the screen.');
61
+ }
62
+ let timer;
63
+ try {
64
+ return await Promise.race([
65
+ page.connection.client(TaClient).onPageAsk(kind, payload),
66
+ new Promise((_resolve, reject) => {
67
+ timer = setTimeout(() => reject(TaErrors.invalidArgument('The page of Ta did not answer in time.', 'Try again in a moment.')), timeoutMs);
68
+ }),
69
+ ]);
70
+ }
71
+ finally {
72
+ clearTimeout(timer);
73
+ }
74
+ }
75
+ has(principal, kind) {
76
+ return this.of(principal, kind).length > 0;
77
+ }
78
+ principalOf(options) {
79
+ var _a;
80
+ if (options.principal) {
81
+ return options.principal;
82
+ }
83
+ const team = this.teamProvider.team;
84
+ const actors = options.sessionFile ? team.actorsOf(options.sessionFile) : [team.current()];
85
+ return (_a = actors.find(actor => actor !== TA_OWNER)) !== null && _a !== void 0 ? _a : TA_OWNER;
86
+ }
87
+ of(principal, kind) {
88
+ return [...this.entries.values()].filter(entry => !entry.connection.closed && entry.principal === principal && entry.info.kinds.includes(kind));
89
+ }
90
+ };
91
+ __decorate([
92
+ Autowired(TaPrincipals),
93
+ __metadata("design:type", Object)
94
+ ], DefaultTaPageBook.prototype, "principals", void 0);
95
+ __decorate([
96
+ Autowired({ id: TaHostTeamProvider, detached: true }),
97
+ __metadata("design:type", Object)
98
+ ], DefaultTaPageBook.prototype, "teamProvider", void 0);
99
+ DefaultTaPageBook = __decorate([
100
+ Component(TaPageBook)
101
+ ], DefaultTaPageBook);
102
+ export { DefaultTaPageBook };
103
+ /** A page says which requests it answers (TaPageServer). */
104
+ let TaPageServerImpl = class TaPageServerImpl {
105
+ async attach(info) {
106
+ this.book.attach(RpcContext.requireConnection(), info);
107
+ }
108
+ };
109
+ __decorate([
110
+ Autowired(TaPageBook),
111
+ __metadata("design:type", Object)
112
+ ], TaPageServerImpl.prototype, "book", void 0);
113
+ TaPageServerImpl = __decorate([
114
+ Rpc(TaPageServer)
115
+ ], TaPageServerImpl);
116
+ export { TaPageServerImpl };
117
+ //# sourceMappingURL=page-book.js.map
@@ -80,6 +80,8 @@ export declare class TaRelayServerImpl implements TaRelayServer {
80
80
  addStore(type: string, options: Record<string, unknown>, name?: string): Promise<string>;
81
81
  removeRelay(id: string): Promise<void>;
82
82
  chooseRelay(feature: TaRelayFeature, id: string | null): Promise<TaRelays>;
83
+ joinDeployment(url: string): Promise<TaRelays>;
84
+ leaveDeployment(): Promise<TaRelays>;
83
85
  probeRelay(idOrUrl: string): Promise<TaRelayProbe>;
84
86
  /** A change of relays.json; what it refuses is said as the errors of Ta. */
85
87
  protected relaysCall<T>(change: () => T): T;