@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
@@ -0,0 +1,127 @@
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.GatewayModels = exports.GatewayModelsUtil = void 0;
13
+ const node_fs_1 = require("node:fs");
14
+ const node_path_1 = require("node:path");
15
+ const ai_coding_agent_1 = require("@celljs/ai-coding-agent");
16
+ const core_1 = require("@celljs/core");
17
+ /** How long ta serve waits for the catalog of the gateway as it starts. */
18
+ const CATALOG_TIMEOUT_MS = 5000;
19
+ var GatewayModelsUtil;
20
+ (function (GatewayModelsUtil) {
21
+ GatewayModelsUtil.URL_ENV = 'TA_MODEL_PROXY_URL';
22
+ GatewayModelsUtil.KEY_ENV = 'TA_MODEL_PROXY_KEY';
23
+ /**
24
+ * models.json with the providers of the gateway, each at the gateway (`<url>/api/models/<id>`) with the model key of
25
+ * this sandbox: those it gave before and no longer does go; those of the user stay.
26
+ */
27
+ function apply(models, catalog, url, key, before) {
28
+ var _a, _b;
29
+ const providers = { ...((_a = models.providers) !== null && _a !== void 0 ? _a : {}) };
30
+ for (const id of before) {
31
+ delete providers[id];
32
+ }
33
+ const managed = [];
34
+ for (const provider of (_b = catalog.providers) !== null && _b !== void 0 ? _b : []) {
35
+ if (typeof (provider === null || provider === void 0 ? void 0 : provider.id) !== 'string' || !/^[a-z0-9][a-z0-9._-]{0,63}$/i.test(provider.id) || !Array.isArray(provider.models)) {
36
+ continue;
37
+ }
38
+ providers[provider.id] = {
39
+ ...(provider.name ? { name: provider.name } : {}),
40
+ baseUrl: `${url}/api/models/${provider.id}`,
41
+ api: provider.api,
42
+ apiKey: key,
43
+ models: provider.models,
44
+ };
45
+ managed.push(provider.id);
46
+ }
47
+ return { models: { ...models, providers }, managed };
48
+ }
49
+ GatewayModelsUtil.apply = apply;
50
+ /** settings.json with the first model of the gateway as the default, when it has none. */
51
+ function defaults(settings, catalog) {
52
+ var _a, _b;
53
+ const first = (_a = catalog.providers) === null || _a === void 0 ? void 0 : _a.find(provider => { var _a; return (_a = provider.models) === null || _a === void 0 ? void 0 : _a.length; });
54
+ const model = (_b = first === null || first === void 0 ? void 0 : first.models[0]) === null || _b === void 0 ? void 0 : _b.id;
55
+ if (settings.defaultProvider || !first || typeof model !== 'string') {
56
+ return undefined;
57
+ }
58
+ return { ...settings, defaultProvider: first.id, defaultModel: model };
59
+ }
60
+ GatewayModelsUtil.defaults = defaults;
61
+ })(GatewayModelsUtil || (exports.GatewayModelsUtil = GatewayModelsUtil = {}));
62
+ /**
63
+ * The models of a gateway, for a Ta in its sandbox (docs/design/ta-cloud.md 3.4): with TA_MODEL_PROXY_URL and
64
+ * TA_MODEL_PROXY_KEY, ta serve reads the catalog of the gateway as it starts and puts its providers in pi's
65
+ * models.json, at the gateway with the model key of this sandbox. The keys of the providers stay with the gateway,
66
+ * which counts what each call takes. The two variables leave the environment, so that no command sees them.
67
+ */
68
+ let GatewayModels = class GatewayModels {
69
+ async onStart() {
70
+ var _a, _b;
71
+ var _c, _d;
72
+ const url = (_a = process.env[GatewayModelsUtil.URL_ENV]) === null || _a === void 0 ? void 0 : _a.replace(/\/+$/, '');
73
+ const key = process.env[GatewayModelsUtil.KEY_ENV];
74
+ delete process.env[GatewayModelsUtil.URL_ENV];
75
+ delete process.env[GatewayModelsUtil.KEY_ENV];
76
+ if (!url || !key) {
77
+ return;
78
+ }
79
+ try {
80
+ const answer = await fetch(`${url}/api/models`, { headers: { authorization: `Bearer ${key}` }, signal: AbortSignal.timeout(CATALOG_TIMEOUT_MS) });
81
+ if (!answer.ok) {
82
+ throw new Error(`it answered ${answer.status}`);
83
+ }
84
+ const catalog = (await answer.json());
85
+ const agentDir = (_c = (_b = this.codingAgentOptions) === null || _b === void 0 ? void 0 : _b.agentDir) !== null && _c !== void 0 ? _c : (await ai_coding_agent_1.PiSdkUtil.load()).getAgentDir();
86
+ const managedFile = (0, node_path_1.join)(agentDir, 'gateway-models.json');
87
+ const before = (_d = this.read(managedFile).providers) !== null && _d !== void 0 ? _d : [];
88
+ const modelsFile = (0, node_path_1.join)(agentDir, 'models.json');
89
+ const { models, managed } = GatewayModelsUtil.apply(this.read(modelsFile), catalog, url, key, before);
90
+ this.write(modelsFile, models);
91
+ this.write(managedFile, { providers: managed });
92
+ const settingsFile = (0, node_path_1.join)(agentDir, 'settings.json');
93
+ const settings = GatewayModelsUtil.defaults(this.read(settingsFile), catalog);
94
+ if (settings) {
95
+ this.write(settingsFile, settings);
96
+ }
97
+ console.log(`ta serve: models of the gateway: ${managed.join(', ') || 'none'}`);
98
+ }
99
+ catch (error) {
100
+ console.warn(`ta serve: the models of the gateway did not load: ${error.message}`);
101
+ }
102
+ }
103
+ read(file) {
104
+ try {
105
+ const value = JSON.parse((0, node_fs_1.readFileSync)(file, 'utf8'));
106
+ return value && typeof value === 'object' && !Array.isArray(value) ? value : {};
107
+ }
108
+ catch (_a) {
109
+ return {};
110
+ }
111
+ }
112
+ write(file, data) {
113
+ (0, node_fs_1.mkdirSync)((0, node_path_1.dirname)(file), { recursive: true });
114
+ const temporary = `${file}.${process.pid}.tmp`;
115
+ (0, node_fs_1.writeFileSync)(temporary, `${JSON.stringify(data, undefined, 2)}\n`, { mode: 0o600 });
116
+ (0, node_fs_1.renameSync)(temporary, file);
117
+ }
118
+ };
119
+ exports.GatewayModels = GatewayModels;
120
+ __decorate([
121
+ (0, core_1.Value)(ai_coding_agent_1.CODING_AGENT_OPTIONS),
122
+ __metadata("design:type", Object)
123
+ ], GatewayModels.prototype, "codingAgentOptions", void 0);
124
+ exports.GatewayModels = GatewayModels = __decorate([
125
+ (0, core_1.Component)(core_1.ApplicationLifecycle)
126
+ ], GatewayModels);
127
+ //# sourceMappingURL=gateway-models.js.map
@@ -1,16 +1,22 @@
1
+ export * from './app-commands';
1
2
  export * from './auth-server-impl';
2
3
  export * from './client-channel';
3
4
  export * from './client-tool-broker';
5
+ export * from './directory-relocator';
4
6
  export * from './event-log';
7
+ export * from './exec-endpoint';
5
8
  export * from './exec-environment-factory';
6
9
  export * from './extension-data';
7
10
  export * from './extension-data-notifier';
8
11
  export * from './extension-providers';
12
+ export * from './gateway-models';
9
13
  export * from './host-protocol';
10
14
  export * from './keep-awake';
11
15
  export * from './package-host-extension';
12
16
  export * from './package-hosts';
13
17
  export * from './package-server-impl';
18
+ export * from './package-webhooks';
19
+ export * from './page-book';
14
20
  export * from './presence-book';
15
21
  export * from './presence-server-impl';
16
22
  export * from './receipt-book';
@@ -42,6 +48,8 @@ export * from './terminal-protocol';
42
48
  export * from './terminal-service';
43
49
  export * from './terminal-util';
44
50
  export * from './usage';
51
+ export * from './voice-bridge';
52
+ export * from './voices-file';
45
53
  export * from './web-extension-catalog';
46
54
  export * from './web-extension-util';
47
55
  export * from './working-directory';
package/lib/node/index.js CHANGED
@@ -14,19 +14,25 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
14
  for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
15
  };
16
16
  Object.defineProperty(exports, "__esModule", { value: true });
17
+ __exportStar(require("./app-commands"), exports);
17
18
  __exportStar(require("./auth-server-impl"), exports);
18
19
  __exportStar(require("./client-channel"), exports);
19
20
  __exportStar(require("./client-tool-broker"), exports);
21
+ __exportStar(require("./directory-relocator"), exports);
20
22
  __exportStar(require("./event-log"), exports);
23
+ __exportStar(require("./exec-endpoint"), exports);
21
24
  __exportStar(require("./exec-environment-factory"), exports);
22
25
  __exportStar(require("./extension-data"), exports);
23
26
  __exportStar(require("./extension-data-notifier"), exports);
24
27
  __exportStar(require("./extension-providers"), exports);
28
+ __exportStar(require("./gateway-models"), exports);
25
29
  __exportStar(require("./host-protocol"), exports);
26
30
  __exportStar(require("./keep-awake"), exports);
27
31
  __exportStar(require("./package-host-extension"), exports);
28
32
  __exportStar(require("./package-hosts"), exports);
29
33
  __exportStar(require("./package-server-impl"), exports);
34
+ __exportStar(require("./package-webhooks"), exports);
35
+ __exportStar(require("./page-book"), exports);
30
36
  __exportStar(require("./presence-book"), exports);
31
37
  __exportStar(require("./presence-server-impl"), exports);
32
38
  __exportStar(require("./receipt-book"), exports);
@@ -58,6 +64,8 @@ __exportStar(require("./terminal-protocol"), exports);
58
64
  __exportStar(require("./terminal-service"), exports);
59
65
  __exportStar(require("./terminal-util"), exports);
60
66
  __exportStar(require("./usage"), exports);
67
+ __exportStar(require("./voice-bridge"), exports);
68
+ __exportStar(require("./voices-file"), exports);
61
69
  __exportStar(require("./web-extension-catalog"), exports);
62
70
  __exportStar(require("./web-extension-util"), exports);
63
71
  __exportStar(require("./working-directory"), exports);
@@ -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,5 +43,7 @@ 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
  }
45
49
  //# sourceMappingURL=keep-awake.d.ts.map
@@ -30,10 +30,17 @@ var KeepAwakeUtil;
30
30
  })(KeepAwakeUtil || (exports.KeepAwakeUtil = KeepAwakeUtil = {}));
31
31
  /** How often what keeps the computer awake is looked at. */
32
32
  const CHECK_MS = 15000;
33
+ /**
34
+ * How long the computer stays awake after ta serve stops while it held it: a restart of Ta (an update, Restart Ta)
35
+ * takes seconds, and a Mac idle past its sleep time falls asleep the moment the assertion goes, before the new one.
36
+ */
37
+ const BRIDGE_S = 120;
33
38
  /**
34
39
  * Keeps the computer from sleeping while idle as long as a session runs or a paired device was connected of
35
40
  * late: asleep, ta serve answers no phone, and a phone that cannot reach it cannot wake it. It holds
36
- * `caffeinate -i` (idle sleep only: the display sleeps, a closed lid sleeps), which ends with ta serve.
41
+ * `caffeinate -i -s`, which ends with ta serve: idle sleep, and on power any sleep but of a closed lid, since a Mac
42
+ * that slept wakes only in the dark for minutes, where an assertion of idle sleep does not keep it; the display
43
+ * still sleeps. Stopping while it held it, it leaves one of BRIDGE_S, for the Ta that starts after.
37
44
  * Turned off in relay.json (TaRelayServer.setKeepAwake); nothing where it is not supported.
38
45
  */
39
46
  let KeepAwakeImpl = class KeepAwakeImpl {
@@ -54,10 +61,15 @@ let KeepAwakeImpl = class KeepAwakeImpl {
54
61
  }
55
62
  this.timer = setInterval(() => this.check(), CHECK_MS);
56
63
  (_b = (_a = this.timer).unref) === null || _b === void 0 ? void 0 : _b.call(_a);
64
+ this.check();
57
65
  }
58
66
  onStop() {
59
67
  clearInterval(this.timer);
68
+ const held = this.held;
60
69
  this.release();
70
+ if (held) {
71
+ this.spawnBridge().unref();
72
+ }
61
73
  }
62
74
  check(now = Date.now()) {
63
75
  if (!this.supported) {
@@ -97,7 +109,11 @@ let KeepAwakeImpl = class KeepAwakeImpl {
97
109
  }
98
110
  /** `-w`: it ends when this process does, killed too. */
99
111
  spawn() {
100
- return (0, node_child_process_1.spawn)('/usr/bin/caffeinate', ['-i', '-w', String(process.pid)], { stdio: 'ignore' });
112
+ return (0, node_child_process_1.spawn)('/usr/bin/caffeinate', ['-i', '-s', '-w', String(process.pid)], { stdio: 'ignore' });
113
+ }
114
+ /** Awake for a while after this process, on its own. */
115
+ spawnBridge() {
116
+ return (0, node_child_process_1.spawn)('/usr/bin/caffeinate', ['-i', '-s', '-t', String(BRIDGE_S)], { stdio: 'ignore', detached: true });
101
117
  }
102
118
  };
103
119
  exports.KeepAwakeImpl = KeepAwakeImpl;
@@ -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. */
@@ -45,13 +45,60 @@ var MessagePage;
45
45
  return start;
46
46
  }
47
47
  MessagePage.start = start;
48
+ /**
49
+ * A message of the user that the agent was given on the way, after the result of a tool it was written before:
50
+ * a step of the turn, not the start of another (as the web page reads it).
51
+ */
52
+ function steered(messages, index) {
53
+ var _a;
54
+ if (role(messages[index]) !== 'user') {
55
+ return false;
56
+ }
57
+ for (let before = index - 1; before >= 0; before--) {
58
+ const was = (_a = role(messages[before])) !== null && _a !== void 0 ? _a : '';
59
+ if (was === 'user') {
60
+ return steered(messages, before);
61
+ }
62
+ if (TURN_ROLES.has(was)) {
63
+ const at = timestamp(messages[index]);
64
+ const came = timestamp(messages[before]);
65
+ return was === 'toolResult' && at !== undefined && came !== undefined && at < came;
66
+ }
67
+ }
68
+ return false;
69
+ }
70
+ /**
71
+ * When the messages from `from` start in the middle of a turn (the first of the user or the agent among them
72
+ * is a step of it): the message of the user that asked for the turn.
73
+ */
74
+ function head(messages, from) {
75
+ var _a;
76
+ let first = from;
77
+ while (first < messages.length && role(messages[first]) !== 'user' && !TURN_ROLES.has((_a = role(messages[first])) !== null && _a !== void 0 ? _a : '')) {
78
+ first++;
79
+ }
80
+ if (from <= 0 || first >= messages.length || (role(messages[first]) === 'user' && !steered(messages, first))) {
81
+ return undefined;
82
+ }
83
+ for (let index = from - 1; index >= 0; index--) {
84
+ if (role(messages[index]) === 'user' && !steered(messages, index)) {
85
+ return { index, message: messages[index] };
86
+ }
87
+ }
88
+ return undefined;
89
+ }
90
+ MessagePage.head = head;
48
91
  /** The latest part of a conversation, or all of it without a budget. */
49
92
  function recent(conversation, budget) {
50
93
  if (!budget || budget <= 0) {
51
94
  return conversation;
52
95
  }
53
96
  const from = start(conversation.messages, conversation.messages.length, budget);
54
- return from === 0 ? conversation : { ...conversation, messages: conversation.messages.slice(from), start: from };
97
+ if (from === 0) {
98
+ return conversation;
99
+ }
100
+ const turn = head(conversation.messages, from);
101
+ return { ...conversation, messages: conversation.messages.slice(from), start: from, ...(turn ? { head: turn } : {}) };
55
102
  }
56
103
  MessagePage.recent = recent;
57
104
  /** The part before message `before`, found again by its timestamp if messages came or went before it. */
@@ -67,7 +114,8 @@ var MessagePage;
67
114
  }
68
115
  }
69
116
  const from = start(messages, end, Math.max(1, budget));
70
- return { messages: messages.slice(from, end), start: from, found: true };
117
+ const turn = head(messages, from);
118
+ return { messages: messages.slice(from, end), start: from, found: true, ...(turn ? { head: turn } : {}) };
71
119
  }
72
120
  MessagePage.before = before;
73
121
  })(MessagePage || (exports.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';
4
5
  import { ExtensionDataStore } from './extension-data';
5
6
  import { TaPresenceBook, TaSessionRegistry } from './host-protocol';
7
+ import { TaPageBook } from './page-book';
6
8
  import { type RelayBridge } from './relay-bridge';
7
9
  import { PiDirectories } from './remote/remote-protocol';
8
10
  import { type RoomsBridge } from './rooms-bridge';
9
11
  import { TaSettingsStore } from './settings-store';
10
12
  import { TaHostTeamProvider } from './team/team-protocol';
13
+ import { type VoiceBridge } from './voice-bridge';
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;
@@ -19,14 +19,18 @@ const core_1 = require("@celljs/core");
19
19
  const ta_brand_1 = require("@celljs/ta-harness/lib/node/ta-brand");
20
20
  const ta_packages_1 = require("@celljs/ta-harness/lib/node/ta-packages");
21
21
  const ta_protocol_1 = require("@celljs/ta-protocol");
22
+ const app_commands_1 = require("./app-commands");
22
23
  const extension_data_1 = require("./extension-data");
23
24
  const host_protocol_1 = require("./host-protocol");
25
+ const page_book_1 = require("./page-book");
24
26
  const relay_bridge_1 = require("./relay-bridge");
25
27
  const remote_protocol_1 = require("./remote/remote-protocol");
26
28
  const rooms_bridge_1 = require("./rooms-bridge");
29
+ const session_catalog_1 = require("./session-catalog");
27
30
  const settings_store_1 = require("./settings-store");
28
31
  const ta_errors_1 = require("./ta-errors");
29
32
  const team_protocol_1 = require("./team/team-protocol");
33
+ const voice_bridge_1 = require("./voice-bridge");
30
34
  exports.PackageHosts = Symbol('PackageHosts');
31
35
  var PackageHostUtil;
32
36
  (function (PackageHostUtil) {
@@ -158,6 +162,7 @@ let PackageHostsImpl = class PackageHostsImpl {
158
162
  var _a, _b;
159
163
  const running = this.running.get(name);
160
164
  this.running.delete(name);
165
+ this.appCommands.dropOwner(name);
161
166
  try {
162
167
  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));
163
168
  }
@@ -171,6 +176,12 @@ let PackageHostsImpl = class PackageHostsImpl {
171
176
  const mark = (input) => ({ ...input, message: ta_protocol_1.TaMessageSource.mark(input.message, name) });
172
177
  return {
173
178
  ...host,
179
+ commands: { ...host.commands, register: command => this.appCommands.registerOf(name, command) },
180
+ // A package asks the requests of its own web extension (`pi.ui.answer`), named after it.
181
+ pages: {
182
+ ask: (kind, payload, options = {}) => this.pageBook.ask(this.pageBook.principalOf(options), `${name}/${kind}`, payload, options.timeoutMs),
183
+ has: (kind, options = {}) => this.pageBook.has(this.pageBook.principalOf(options), `${name}/${kind}`),
184
+ },
174
185
  prompt: (sessionId, input) => host.prompt(sessionId, mark(input)),
175
186
  followUp: (sessionId, input) => host.followUp(sessionId, mark(input)),
176
187
  };
@@ -191,7 +202,9 @@ let PackageHostsImpl = class PackageHostsImpl {
191
202
  shares: this.relay.shares,
192
203
  rooms: this.roomsBridge.rooms,
193
204
  relays: this.relay.extensionRelays,
205
+ voices: this.voiceBridge.extensionVoices,
194
206
  sessionMessages: file => this.sessionMessages(file),
207
+ sessionRole: async (file) => session_catalog_1.SessionCatalogUtil.roleOf((await ai_coding_agent_1.PiSdkUtil.load()).SessionManager.open(file).getEntries()),
195
208
  createSession: (cwd, messages, name) => this.createSession(cwd, messages, name),
196
209
  getServerInfo: () => server.getServerInfo(),
197
210
  listSessions: () => server.listSessions(),
@@ -203,6 +216,7 @@ let PackageHostsImpl = class PackageHostsImpl {
203
216
  abort: sessionId => server.abort(sessionId),
204
217
  getState: sessionId => server.getState(sessionId),
205
218
  getLastAssistantText: sessionId => server.getLastAssistantText(sessionId),
219
+ relocateDirectory: (from, to) => server.relocateDirectory(from, to),
206
220
  getExtensionData: (name, key, cwd) => packages.getExtensionData(name, key, cwd),
207
221
  setExtensionData: (name, key, value, cwd) => packages.setExtensionData(name, key, value, cwd),
208
222
  onExtensionData: listener => this.data.onChange(listener),
@@ -214,6 +228,15 @@ let PackageHostsImpl = class PackageHostsImpl {
214
228
  }),
215
229
  presence: () => ({ pages: this.sessions.watching, seenAt: this.sessions.watchedAt, people: this.presenceBook.everyone() }),
216
230
  team: this.teamProvider.team,
231
+ commands: {
232
+ list: () => this.appCommands.list(),
233
+ run: (id, input, options) => this.appCommands.run(id, input, options),
234
+ register: command => this.appCommands.register(command),
235
+ },
236
+ pages: {
237
+ ask: () => Promise.reject(new Error('Only a package asks a page: through its own host.')),
238
+ has: () => false,
239
+ },
217
240
  installPackage: (source, scope, cwd) => packages.installPackage(source, scope, cwd),
218
241
  removePackage: (id, cwd) => packages.removePackage(id, cwd),
219
242
  updateSettings: update => this.settings.rewriteUser(update),
@@ -277,6 +300,10 @@ __decorate([
277
300
  (0, core_1.Autowired)({ id: rooms_bridge_1.ROOMS_BRIDGE, detached: true }),
278
301
  __metadata("design:type", Function)
279
302
  ], PackageHostsImpl.prototype, "roomsBridge", void 0);
303
+ __decorate([
304
+ (0, core_1.Autowired)({ id: voice_bridge_1.VOICE_BRIDGE, detached: true }),
305
+ __metadata("design:type", Function)
306
+ ], PackageHostsImpl.prototype, "voiceBridge", void 0);
280
307
  __decorate([
281
308
  (0, core_1.Autowired)({ id: settings_store_1.TaSettingsStore, detached: true }),
282
309
  __metadata("design:type", Object)
@@ -289,6 +316,14 @@ __decorate([
289
316
  (0, core_1.Autowired)({ id: host_protocol_1.TaPresenceBook, detached: true }),
290
317
  __metadata("design:type", Object)
291
318
  ], PackageHostsImpl.prototype, "presenceBook", void 0);
319
+ __decorate([
320
+ (0, core_1.Autowired)({ id: app_commands_1.TaAppCommands, detached: true }),
321
+ __metadata("design:type", Object)
322
+ ], PackageHostsImpl.prototype, "appCommands", void 0);
323
+ __decorate([
324
+ (0, core_1.Autowired)({ id: page_book_1.TaPageBook, detached: true }),
325
+ __metadata("design:type", Object)
326
+ ], PackageHostsImpl.prototype, "pageBook", void 0);
292
327
  __decorate([
293
328
  (0, core_1.Autowired)({ id: team_protocol_1.TaHostTeamProvider, detached: true }),
294
329
  __metadata("design:type", Object)
@@ -0,0 +1,27 @@
1
+ import type { IncomingMessage } from 'node:http';
2
+ import { type Context, Middleware } from '@celljs/web/lib/node';
3
+ import { PackageHosts } from './package-hosts';
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
+ }
27
+ //# sourceMappingURL=package-webhooks.d.ts.map
@@ -0,0 +1,104 @@
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.PackageWebhooks = exports.PackageWebhookUtil = exports.WEBHOOK_PATH = void 0;
13
+ const core_1 = require("@celljs/core");
14
+ const ta_packages_1 = require("@celljs/ta-harness/lib/node/ta-packages");
15
+ const ta_protocol_1 = require("@celljs/ta-protocol");
16
+ const node_1 = require("@celljs/web/lib/node");
17
+ const package_hosts_1 = require("./package-hosts");
18
+ const ta_access_1 = require("./ta-access");
19
+ /** Where ta serve takes the webhooks of packages: the directory name of a package, then its own path. */
20
+ exports.WEBHOOK_PATH = '/api/hooks/';
21
+ var PackageWebhookUtil;
22
+ (function (PackageWebhookUtil) {
23
+ /** The package and its path of a request to a webhook; undefined for another request. */
24
+ function target(request) {
25
+ var _a;
26
+ const path = ((_a = request.url) !== null && _a !== void 0 ? _a : '/').split('?')[0];
27
+ if (!path.startsWith(exports.WEBHOOK_PATH)) {
28
+ return undefined;
29
+ }
30
+ const [directory, ...rest] = path.slice(exports.WEBHOOK_PATH.length).split('/');
31
+ const name = ta_packages_1.TaPackages.BUILTIN.find(builtin => ta_packages_1.TaPackages.directoryName(builtin) === directory);
32
+ return name ? { name, path: rest.map(part => decodeURIComponent(part)).join('/') } : { name: '', path: '' };
33
+ }
34
+ PackageWebhookUtil.target = target;
35
+ /** The body as text; undefined when it is larger than TA_WEBHOOK_MAX_BYTES. */
36
+ async function body(request) {
37
+ const chunks = [];
38
+ let size = 0;
39
+ for await (const chunk of request) {
40
+ size += chunk.length;
41
+ if (size > ta_protocol_1.TA_WEBHOOK_MAX_BYTES) {
42
+ return undefined;
43
+ }
44
+ chunks.push(chunk);
45
+ }
46
+ return Buffer.concat(chunks).toString('utf8');
47
+ }
48
+ PackageWebhookUtil.body = body;
49
+ })(PackageWebhookUtil || (exports.PackageWebhookUtil = PackageWebhookUtil = {}));
50
+ function end(response, status, value) {
51
+ response.statusCode = status;
52
+ response.setHeader('Content-Type', 'application/json; charset=utf-8');
53
+ response.end(JSON.stringify(value));
54
+ }
55
+ /**
56
+ * The webhooks of the packages that come with Ta (TaPackageService.webhook): a POST to `/api/hooks/<package>/<path>`
57
+ * goes to its host without the token of ta serve; the package checks the secret of its path. Anything else (another
58
+ * method, a package without a webhook, a secret it does not know) is a 404 that says nothing more.
59
+ */
60
+ let PackageWebhooks = class PackageWebhooks {
61
+ constructor() {
62
+ /** Before TaAccess, which would ask for the token. */
63
+ this.priority = ta_access_1.ACCESS_MIDDLEWARE_PRIORITY + 2;
64
+ }
65
+ async handle(ctx, next) {
66
+ const request = ctx.request;
67
+ const target = PackageWebhookUtil.target(request);
68
+ if (!target) {
69
+ await next();
70
+ return;
71
+ }
72
+ const response = ctx.response;
73
+ // A page that rebinds its domain to a ta serve of 127.0.0.1 reaches nothing, as with TaAccess.
74
+ if (!target.name || request.method !== 'POST' || (ta_access_1.TaAccessUtil.isLoopbackHost(this.host) && !ta_access_1.TaAccessUtil.isLoopbackHost(request.headers.host))) {
75
+ end(response, 404, { error: 'Not found' });
76
+ return;
77
+ }
78
+ const body = await PackageWebhookUtil.body(request);
79
+ if (body === undefined) {
80
+ end(response, 413, { error: 'Too large' });
81
+ return;
82
+ }
83
+ try {
84
+ const answer = await this.hosts.call(target.name, 'webhook', [{ path: target.path, body, contentType: request.headers['content-type'] }]);
85
+ end(response, 202, answer !== null && answer !== void 0 ? answer : { ok: true });
86
+ }
87
+ catch (_a) {
88
+ end(response, 404, { error: 'Not found' });
89
+ }
90
+ }
91
+ };
92
+ exports.PackageWebhooks = PackageWebhooks;
93
+ __decorate([
94
+ (0, core_1.Autowired)(package_hosts_1.PackageHosts),
95
+ __metadata("design:type", Object)
96
+ ], PackageWebhooks.prototype, "hosts", void 0);
97
+ __decorate([
98
+ (0, core_1.Value)('server.host'),
99
+ __metadata("design:type", String)
100
+ ], PackageWebhooks.prototype, "host", void 0);
101
+ exports.PackageWebhooks = PackageWebhooks = __decorate([
102
+ (0, core_1.Component)(node_1.Middleware)
103
+ ], PackageWebhooks);
104
+ //# sourceMappingURL=package-webhooks.js.map