@celljs/ta-host 4.10.0 → 4.12.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 (83) hide show
  1. package/README.en.md +4 -4
  2. package/README.md +4 -4
  3. package/esm/node/client-tool-broker.d.ts +6 -2
  4. package/esm/node/client-tool-broker.js +11 -4
  5. package/esm/node/host-protocol.d.ts +12 -7
  6. package/esm/node/index.d.ts +1 -0
  7. package/esm/node/index.js +1 -0
  8. package/esm/node/package-hosts.d.ts +6 -0
  9. package/esm/node/package-hosts.js +36 -1
  10. package/esm/node/package-server-impl.d.ts +0 -1
  11. package/esm/node/package-server-impl.js +0 -3
  12. package/esm/node/relay-bridge.d.ts +12 -2
  13. package/esm/node/relay-bridge.js +93 -3
  14. package/esm/node/rooms-bridge.d.ts +60 -0
  15. package/esm/node/rooms-bridge.js +155 -0
  16. package/esm/node/session-catalog.d.ts +7 -3
  17. package/esm/node/session-catalog.js +12 -4
  18. package/esm/node/session-info-util.d.ts +2 -1
  19. package/esm/node/session-info-util.js +34 -7
  20. package/esm/node/session-list-feed.d.ts +28 -0
  21. package/esm/node/session-list-feed.js +62 -0
  22. package/esm/node/sign-in/sign-in-flow.d.ts +2 -0
  23. package/esm/node/sign-in/sign-in-flow.js +9 -0
  24. package/esm/node/sign-in/sign-in-provider.js +3 -2
  25. package/esm/node/slash-command-util.d.ts +43 -0
  26. package/esm/node/slash-command-util.js +105 -0
  27. package/esm/node/ta-event-util.d.ts +9 -2
  28. package/esm/node/ta-event-util.js +31 -5
  29. package/esm/node/ta-server-impl.d.ts +14 -5
  30. package/esm/node/ta-server-impl.js +39 -18
  31. package/esm/node/ta-session-factory.d.ts +16 -1
  32. package/esm/node/ta-session-factory.js +42 -14
  33. package/esm/node/ta-session-registry.d.ts +4 -1
  34. package/esm/node/ta-session-registry.js +8 -0
  35. package/esm/node/ta-session.d.ts +8 -2
  36. package/esm/node/ta-session.js +41 -4
  37. package/esm/node/web-extension-catalog.d.ts +5 -1
  38. package/esm/node/web-extension-catalog.js +15 -19
  39. package/esm/node/web-extension-util.js +7 -3
  40. package/esm/node/workspace-files.d.ts +16 -12
  41. package/esm/node/workspace-files.js +14 -10
  42. package/esm/node/workspace-protocol.d.ts +1 -1
  43. package/lib/node/client-tool-broker.d.ts +6 -2
  44. package/lib/node/client-tool-broker.js +11 -4
  45. package/lib/node/host-protocol.d.ts +12 -7
  46. package/lib/node/index.d.ts +1 -0
  47. package/lib/node/index.js +1 -0
  48. package/lib/node/package-hosts.d.ts +6 -0
  49. package/lib/node/package-hosts.js +35 -0
  50. package/lib/node/package-server-impl.d.ts +0 -1
  51. package/lib/node/package-server-impl.js +0 -3
  52. package/lib/node/relay-bridge.d.ts +12 -2
  53. package/lib/node/relay-bridge.js +91 -1
  54. package/lib/node/rooms-bridge.d.ts +61 -0
  55. package/lib/node/rooms-bridge.js +158 -0
  56. package/lib/node/session-catalog.d.ts +7 -3
  57. package/lib/node/session-catalog.js +12 -4
  58. package/lib/node/session-info-util.d.ts +2 -1
  59. package/lib/node/session-info-util.js +34 -7
  60. package/lib/node/session-list-feed.d.ts +29 -0
  61. package/lib/node/session-list-feed.js +66 -0
  62. package/lib/node/sign-in/sign-in-flow.d.ts +2 -0
  63. package/lib/node/sign-in/sign-in-flow.js +10 -1
  64. package/lib/node/sign-in/sign-in-provider.js +3 -2
  65. package/lib/node/slash-command-util.d.ts +44 -0
  66. package/lib/node/slash-command-util.js +108 -0
  67. package/lib/node/ta-event-util.d.ts +9 -2
  68. package/lib/node/ta-event-util.js +31 -5
  69. package/lib/node/ta-server-impl.d.ts +14 -5
  70. package/lib/node/ta-server-impl.js +37 -16
  71. package/lib/node/ta-session-factory.d.ts +16 -1
  72. package/lib/node/ta-session-factory.js +42 -14
  73. package/lib/node/ta-session-registry.d.ts +4 -1
  74. package/lib/node/ta-session-registry.js +8 -0
  75. package/lib/node/ta-session.d.ts +8 -2
  76. package/lib/node/ta-session.js +41 -4
  77. package/lib/node/web-extension-catalog.d.ts +5 -1
  78. package/lib/node/web-extension-catalog.js +15 -19
  79. package/lib/node/web-extension-util.js +7 -3
  80. package/lib/node/workspace-files.d.ts +16 -12
  81. package/lib/node/workspace-files.js +13 -9
  82. package/lib/node/workspace-protocol.d.ts +1 -1
  83. package/package.json +10 -10
@@ -0,0 +1,158 @@
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
+ var RoomsBridge_1;
12
+ Object.defineProperty(exports, "__esModule", { value: true });
13
+ exports.TaRoomServerImpl = exports.RoomsBridge = exports.ROOMS_BRIDGE = void 0;
14
+ const core_1 = require("@celljs/core");
15
+ const rpc_1 = require("@celljs/rpc");
16
+ const node_1 = require("@celljs/rpc/lib/node");
17
+ const ta_protocol_1 = require("@celljs/ta-protocol");
18
+ const relay_bridge_1 = require("./relay-bridge");
19
+ const ta_errors_1 = require("./ta-errors");
20
+ /** The id of {@link RoomsBridge}. */
21
+ exports.ROOMS_BRIDGE = Symbol('RoomsBridge');
22
+ /**
23
+ * The rooms of this Ta (docs/design/ta-link.md 3): RelayHubs, connected to its rooms while ta serve runs, so that
24
+ * the owner hears who asks to join without a page open; the clients that watch hear what happens in them, and
25
+ * the server side of packages has them as TaExtensionHost.rooms.
26
+ */
27
+ let RoomsBridge = RoomsBridge_1 = class RoomsBridge {
28
+ constructor() {
29
+ /** The connections that watch, and what they hear: messages and the state too, or the state of some keys. */
30
+ this.watchers = new Map();
31
+ this.rooms = {
32
+ getIdentity: async () => RoomsBridge_1.identity(await this.hubs.identity()),
33
+ setName: async (name) => RoomsBridge_1.identity(await this.hubs.setName(name)),
34
+ listRooms: async () => this.hubs.list(),
35
+ createRoom: input => this.hubs.create(input),
36
+ invite: (room, options) => this.hubs.invite(room, options !== null && options !== void 0 ? options : {}),
37
+ join: link => this.hubs.join(link),
38
+ listRequests: () => this.hubs.requests(),
39
+ answer: (room, ask, accept) => this.hubs.answer(room, ask, accept),
40
+ removeMember: (room, member) => this.hubs.remove(room, member),
41
+ leave: room => this.hubs.leave(room),
42
+ send: (room, data, to) => this.hubs.send(room, data, to),
43
+ getState: (room, prefix) => this.hubs.getState(room, prefix),
44
+ setState: (room, key, value, version) => this.hubs.setState(room, key, value, version),
45
+ listFriends: async () => this.hubs.friends().map(({ id, name, rooms, metAt, seenAt }) => ({ id, name, rooms, metAt, seenAt })),
46
+ removeFriend: async (id) => this.hubs.removeFriend(id),
47
+ onEvent: listener => this.hubs.onEvent(listener),
48
+ };
49
+ }
50
+ get hubs() {
51
+ return this.relay.hubs;
52
+ }
53
+ onStart() {
54
+ this.hubs.onEvent(event => this.broadcast(event));
55
+ this.hubs.start();
56
+ }
57
+ onStop() {
58
+ this.hubs.stop();
59
+ }
60
+ /** `watch` undefined: no more. */
61
+ watch(connection, watch) {
62
+ if (watch === undefined) {
63
+ this.watchers.delete(connection);
64
+ return;
65
+ }
66
+ if (!this.watchers.has(connection)) {
67
+ connection.onClose(() => this.watchers.delete(connection));
68
+ }
69
+ this.watchers.set(connection, watch);
70
+ }
71
+ broadcast(event) {
72
+ for (const [connection, watch] of this.watchers) {
73
+ if (!connection.closed && ta_protocol_1.TaRoomWatchUtil.hears(watch, event)) {
74
+ connection
75
+ .client(ta_protocol_1.TaClient)
76
+ .onRoomEvent(event)
77
+ .catch(() => undefined);
78
+ }
79
+ }
80
+ }
81
+ static identity({ id, name }) {
82
+ return { id, name };
83
+ }
84
+ };
85
+ exports.RoomsBridge = RoomsBridge;
86
+ __decorate([
87
+ (0, core_1.Autowired)({ id: relay_bridge_1.RELAY_BRIDGE, detached: true }),
88
+ __metadata("design:type", Function)
89
+ ], RoomsBridge.prototype, "relay", void 0);
90
+ exports.RoomsBridge = RoomsBridge = RoomsBridge_1 = __decorate([
91
+ (0, core_1.Component)([exports.ROOMS_BRIDGE, core_1.ApplicationLifecycle])
92
+ ], RoomsBridge);
93
+ /** The rooms for clients (TaRoomServer): those of RoomsBridge, what goes wrong said as the errors of Ta. */
94
+ let TaRoomServerImpl = class TaRoomServerImpl {
95
+ get rooms() {
96
+ return this.bridge.rooms;
97
+ }
98
+ getIdentity() {
99
+ return ta_errors_1.TaErrors.guard(() => this.rooms.getIdentity());
100
+ }
101
+ setName(name) {
102
+ return ta_errors_1.TaErrors.guard(() => this.rooms.setName(name));
103
+ }
104
+ listRooms() {
105
+ return ta_errors_1.TaErrors.guard(() => this.rooms.listRooms());
106
+ }
107
+ createRoom(input) {
108
+ return ta_errors_1.TaErrors.guard(() => this.rooms.createRoom(input));
109
+ }
110
+ invite(room, options) {
111
+ return ta_errors_1.TaErrors.guard(() => this.rooms.invite(room, options !== null && options !== void 0 ? options : undefined));
112
+ }
113
+ join(link) {
114
+ return ta_errors_1.TaErrors.guard(() => this.rooms.join(link));
115
+ }
116
+ listRequests() {
117
+ return ta_errors_1.TaErrors.guard(() => this.rooms.listRequests());
118
+ }
119
+ answer(room, ask, accept) {
120
+ return ta_errors_1.TaErrors.guard(() => this.rooms.answer(room, ask, accept === true));
121
+ }
122
+ removeMember(room, member) {
123
+ return ta_errors_1.TaErrors.guard(() => this.rooms.removeMember(room, member));
124
+ }
125
+ leave(room) {
126
+ return ta_errors_1.TaErrors.guard(() => this.rooms.leave(room));
127
+ }
128
+ send(room, data, to) {
129
+ return ta_errors_1.TaErrors.guard(() => this.rooms.send(room, data, to !== null && to !== void 0 ? to : undefined));
130
+ }
131
+ getState(room, prefix) {
132
+ return ta_errors_1.TaErrors.guard(() => this.rooms.getState(room, prefix !== null && prefix !== void 0 ? prefix : undefined));
133
+ }
134
+ setState(room, key, value, version) {
135
+ return ta_errors_1.TaErrors.guard(() => this.rooms.setState(room, key, value, version !== null && version !== void 0 ? version : undefined));
136
+ }
137
+ listFriends() {
138
+ return ta_errors_1.TaErrors.guard(() => this.rooms.listFriends());
139
+ }
140
+ removeFriend(id) {
141
+ return ta_errors_1.TaErrors.guard(() => this.rooms.removeFriend(id));
142
+ }
143
+ async watch(messages, state) {
144
+ this.bridge.watch(node_1.RpcContext.requireConnection(), ta_protocol_1.TaRoomWatchUtil.of(messages !== null && messages !== void 0 ? messages : undefined, state));
145
+ }
146
+ async unwatch() {
147
+ this.bridge.watch(node_1.RpcContext.requireConnection(), undefined);
148
+ }
149
+ };
150
+ exports.TaRoomServerImpl = TaRoomServerImpl;
151
+ __decorate([
152
+ (0, core_1.Autowired)(exports.ROOMS_BRIDGE),
153
+ __metadata("design:type", RoomsBridge)
154
+ ], TaRoomServerImpl.prototype, "bridge", void 0);
155
+ exports.TaRoomServerImpl = TaRoomServerImpl = __decorate([
156
+ (0, rpc_1.Rpc)(ta_protocol_1.TaRoomServer)
157
+ ], TaRoomServerImpl);
158
+ //# sourceMappingURL=rooms-bridge.js.map
@@ -1,5 +1,5 @@
1
1
  import { type CodingAgentOptions } from '@celljs/ai-coding-agent';
2
- import type { TaSavedSessionInfo } from '@celljs/ta-protocol';
2
+ import type { TaSavedSessionInfo, TaSavedSessionQuery } from '@celljs/ta-protocol';
3
3
  import { TaSessionCatalog } from './host-protocol';
4
4
  import { PiDirectories } from './remote/remote-protocol';
5
5
  /** What a list shows of a session file, with the directory pi worked in, before it is a location. */
@@ -60,11 +60,15 @@ export declare class DefaultTaSessionCatalog implements TaSessionCatalog {
60
60
  version: string;
61
61
  summary?: SessionSummary;
62
62
  }>;
63
- list(open?: ReadonlySet<string>): Promise<TaSavedSessionInfo[]>;
63
+ list(open?: ReadonlySet<string>, query?: TaSavedSessionQuery): Promise<TaSavedSessionInfo[]>;
64
64
  /** Where pi keeps the sessions it creates (SessionManager.create without a directory). */
65
65
  protected sessionsDir(): Promise<string>;
66
66
  protected files(root: string): Promise<string[]>;
67
- protected summary(file: string): Promise<SessionSummary | undefined>;
67
+ /**
68
+ * What the file holds; undefined, without reading it, when it was last written before `since`: its last
69
+ * message came before then too, and a list of a window leaves it out (an archive of thousands is not read).
70
+ */
71
+ protected summary(file: string, since?: number): Promise<SessionSummary | undefined>;
68
72
  }
69
73
  export {};
70
74
  //# sourceMappingURL=session-catalog.d.ts.map
@@ -149,15 +149,16 @@ let DefaultTaSessionCatalog = class DefaultTaSessionCatalog {
149
149
  /** By file: its size and time when read, and what it held. */
150
150
  this.cache = new Map();
151
151
  }
152
- async list(open = new Set()) {
152
+ async list(open = new Set(), query = {}) {
153
153
  const files = await this.files(await this.sessionsDir());
154
154
  // An open session's file grows with every message: it is not read again for a list that leaves it out.
155
155
  const closed = files.filter(file => !open.has(file));
156
+ const { since, before } = query;
156
157
  const sessions = [];
157
158
  for (let i = 0; i < closed.length; i += BATCH) {
158
159
  await Promise.all(closed.slice(i, i + BATCH).map(async (file) => {
159
- const summary = await this.summary(file);
160
- if (summary) {
160
+ const summary = await this.summary(file, since);
161
+ if (summary && (since === undefined || summary.updatedAt >= since) && (before === undefined || summary.updatedAt < before)) {
161
162
  const { piCwd, ...info } = summary;
162
163
  sessions.push({ ...info, sessionFile: file, cwd: piCwd && this.directories.fromPi(piCwd) });
163
164
  }
@@ -188,7 +189,11 @@ let DefaultTaSessionCatalog = class DefaultTaSessionCatalog {
188
189
  }));
189
190
  return files.flat();
190
191
  }
191
- async summary(file) {
192
+ /**
193
+ * What the file holds; undefined, without reading it, when it was last written before `since`: its last
194
+ * message came before then too, and a list of a window leaves it out (an archive of thousands is not read).
195
+ */
196
+ async summary(file, since) {
192
197
  const stats = await (0, promises_1.stat)(file).catch(() => undefined);
193
198
  if (!(stats === null || stats === void 0 ? void 0 : stats.isFile())) {
194
199
  return undefined;
@@ -198,6 +203,9 @@ let DefaultTaSessionCatalog = class DefaultTaSessionCatalog {
198
203
  if ((cached === null || cached === void 0 ? void 0 : cached.version) === version) {
199
204
  return cached.summary;
200
205
  }
206
+ if (since !== undefined && stats.mtimeMs < since) {
207
+ return undefined;
208
+ }
201
209
  const text = await (0, promises_1.readFile)(file, 'utf8').catch(() => undefined);
202
210
  const summary = text === undefined ? undefined : SessionCatalogUtil.summarize(text, stats.mtimeMs);
203
211
  this.cache.set(file, { version, summary });
@@ -14,7 +14,8 @@ export declare namespace SessionInfoUtil {
14
14
  /**
15
15
  * The text of the last message of the user or the agent that has some, on one line and cut to a preview's
16
16
  * length, as a messaging app shows the last thing said under its name: without its context, the marks of
17
- * markdown at the start of its lines, and the thinking and tool calls of the agent.
17
+ * markdown at the start of its lines, and the thinking and tool calls of the agent; a skill the user ran is
18
+ * `/skill:name` and what follows, as the title says it, not the skill's file.
18
19
  */
19
20
  function lastMessage(messages: readonly MessageLike[]): string | undefined;
20
21
  /** The time of the last message that has one, else `fallback`. */
@@ -17,9 +17,7 @@ var SessionInfoUtil;
17
17
  if (message.role !== 'user') {
18
18
  continue;
19
19
  }
20
- const said = ta_protocol_1.TaImageNote.strip(ta_protocol_1.TaMessageContext.strip(text(message.content)));
21
- const skill = ta_protocol_1.TaSkillUse.parse(said);
22
- const line = (skill ? ta_protocol_1.TaSkillUse.command(skill) : said)
20
+ const line = userWords(text(message.content))
23
21
  .split('\n')
24
22
  .map(part => part.trim())
25
23
  .find(Boolean);
@@ -33,7 +31,8 @@ var SessionInfoUtil;
33
31
  /**
34
32
  * The text of the last message of the user or the agent that has some, on one line and cut to a preview's
35
33
  * length, as a messaging app shows the last thing said under its name: without its context, the marks of
36
- * markdown at the start of its lines, and the thinking and tool calls of the agent.
34
+ * markdown at the start of its lines, and the thinking and tool calls of the agent; a skill the user ran is
35
+ * `/skill:name` and what follows, as the title says it, not the skill's file.
37
36
  */
38
37
  function lastMessage(messages) {
39
38
  for (let i = messages.length - 1; i >= 0; i--) {
@@ -41,10 +40,10 @@ var SessionInfoUtil;
41
40
  if (message.role !== 'user' && message.role !== 'assistant') {
42
41
  continue;
43
42
  }
44
- const said = message.role === 'user' ? ta_protocol_1.TaImageNote.strip(ta_protocol_1.TaMessageContext.strip(text(message.content))) : ta_protocol_1.TaAgentSummary.strip(text(message.content));
43
+ const said = message.role === 'user' ? userWords(text(message.content)) : ta_protocol_1.TaAgentSummary.strip(text(message.content));
45
44
  // A list asks for it every few seconds: only the start of a long reply is read, enough for a preview.
46
- const line = said
47
- .slice(0, PREVIEW_READ)
45
+ const read = said.slice(0, PREVIEW_READ);
46
+ const line = (withoutFences(read) || read)
48
47
  .split('\n')
49
48
  .map(part => part
50
49
  .replace(/^\s*(?:#{1,6}\s+|>\s*|[-*+]\s+|\d+\.\s+)/, '')
@@ -60,6 +59,34 @@ var SessionInfoUtil;
60
59
  return undefined;
61
60
  }
62
61
  SessionInfoUtil.lastMessage = lastMessage;
62
+ /**
63
+ * The text without its fenced blocks, as a messenger says no more than [code] of them: code, and the cards a
64
+ * reply draws (a card's language, as `ta-glance`), are not what was said.
65
+ */
66
+ function withoutFences(text) {
67
+ var _a;
68
+ const kept = [];
69
+ let fence;
70
+ for (const line of text.split('\n')) {
71
+ const mark = (_a = /^\s*(`{3,}|~{3,})/.exec(line)) === null || _a === void 0 ? void 0 : _a[1];
72
+ if (!fence && mark) {
73
+ fence = mark;
74
+ }
75
+ else if (fence && mark && mark[0] === fence[0] && mark.length >= fence.length && !line.trim().slice(mark.length)) {
76
+ fence = undefined;
77
+ }
78
+ else if (!fence) {
79
+ kept.push(line);
80
+ }
81
+ }
82
+ return kept.join('\n').trim();
83
+ }
84
+ /** What the user typed of a message: without its context and pi's notes of images, a skill as `/skill:name` and what follows. */
85
+ function userWords(content) {
86
+ const said = ta_protocol_1.TaImageNote.strip(ta_protocol_1.TaMessageContext.strip(content));
87
+ const skill = ta_protocol_1.TaSkillUse.parse(said);
88
+ return skill ? ta_protocol_1.TaSkillUse.command(skill) : said;
89
+ }
63
90
  /** The time of the last message that has one, else `fallback`. */
64
91
  function updatedAt(messages, fallback) {
65
92
  for (let i = messages.length - 1; i >= 0; i--) {
@@ -0,0 +1,29 @@
1
+ import type { RpcConnection } from '@celljs/rpc/lib/node';
2
+ import { type TaSessionInfo } from '@celljs/ta-protocol';
3
+ /** At most one list per connection in this time, the latest; the first change leaves at once. */
4
+ export declare const SESSION_LIST_MS = 250;
5
+ interface Watcher {
6
+ timer?: ReturnType<typeof setTimeout>;
7
+ lastAt: number;
8
+ /** The list it was sent last, as JSON: the same again is not sent. */
9
+ sent?: string;
10
+ }
11
+ /**
12
+ * The open sessions told to the connections that watch them (TaServer.watchSessions): the whole list each time
13
+ * what a list shows of it changes, so that every page shows the same at once, rather than what it read a few
14
+ * seconds before. A session streams hundreds of events a second, of which few change the list: those come
15
+ * here (`changed`), and a moment of them leaves as one list, only when it differs from the one sent.
16
+ */
17
+ export declare class SessionListFeed {
18
+ protected readonly list: () => TaSessionInfo[];
19
+ protected readonly intervalMs: number;
20
+ protected readonly watchers: Map<RpcConnection, Watcher>;
21
+ constructor(list: () => TaSessionInfo[], intervalMs?: number);
22
+ /** The list now; the connection is told of each change from now on, until it closes. */
23
+ watch(connection: RpcConnection): TaSessionInfo[];
24
+ /** What a list shows changed: a session opened or closed, or one of them changed. */
25
+ changed(): void;
26
+ protected schedule(connection: RpcConnection, watcher: Watcher): void;
27
+ }
28
+ export {};
29
+ //# sourceMappingURL=session-list-feed.d.ts.map
@@ -0,0 +1,66 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.SessionListFeed = exports.SESSION_LIST_MS = void 0;
4
+ const ta_protocol_1 = require("@celljs/ta-protocol");
5
+ /** At most one list per connection in this time, the latest; the first change leaves at once. */
6
+ exports.SESSION_LIST_MS = 250;
7
+ /**
8
+ * The open sessions told to the connections that watch them (TaServer.watchSessions): the whole list each time
9
+ * what a list shows of it changes, so that every page shows the same at once, rather than what it read a few
10
+ * seconds before. A session streams hundreds of events a second, of which few change the list: those come
11
+ * here (`changed`), and a moment of them leaves as one list, only when it differs from the one sent.
12
+ */
13
+ class SessionListFeed {
14
+ constructor(list, intervalMs = exports.SESSION_LIST_MS) {
15
+ this.list = list;
16
+ this.intervalMs = intervalMs;
17
+ this.watchers = new Map();
18
+ }
19
+ /** The list now; the connection is told of each change from now on, until it closes. */
20
+ watch(connection) {
21
+ const list = this.list();
22
+ let watcher = this.watchers.get(connection);
23
+ if (!watcher) {
24
+ const created = { lastAt: Number.NEGATIVE_INFINITY };
25
+ this.watchers.set(connection, created);
26
+ connection.onClose(() => {
27
+ clearTimeout(created.timer);
28
+ this.watchers.delete(connection);
29
+ });
30
+ watcher = created;
31
+ }
32
+ watcher.sent = JSON.stringify(list);
33
+ return list;
34
+ }
35
+ /** What a list shows changed: a session opened or closed, or one of them changed. */
36
+ changed() {
37
+ for (const [connection, watcher] of this.watchers) {
38
+ this.schedule(connection, watcher);
39
+ }
40
+ }
41
+ schedule(connection, watcher) {
42
+ if (watcher.timer !== undefined) {
43
+ return;
44
+ }
45
+ const wait = Math.max(0, watcher.lastAt + this.intervalMs - performance.now());
46
+ watcher.timer = setTimeout(() => {
47
+ watcher.timer = undefined;
48
+ watcher.lastAt = performance.now();
49
+ if (connection.closed) {
50
+ return;
51
+ }
52
+ const list = this.list();
53
+ const json = JSON.stringify(list);
54
+ if (json === watcher.sent) {
55
+ return;
56
+ }
57
+ watcher.sent = json;
58
+ connection
59
+ .client(ta_protocol_1.TaClient)
60
+ .onSessions(list)
61
+ .catch(() => undefined);
62
+ }, wait);
63
+ }
64
+ }
65
+ exports.SessionListFeed = SessionListFeed;
66
+ //# sourceMappingURL=session-list-feed.js.map
@@ -1,6 +1,8 @@
1
1
  import type { IncomingMessage } from 'node:http';
2
2
  import type { AccessStore } from './access-store';
3
3
  import { type SignInAccount, type SignInProvider } from './sign-in-provider';
4
+ /** Sign-ins under way at most: anyone may start one without a token, and each is kept until it ends or expires. */
5
+ export declare const MAX_PENDING_SIGN_INS = 1000;
4
6
  interface Pending {
5
7
  provider: string;
6
8
  verifier: string;
@@ -1,12 +1,14 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.SignInFlow = exports.SignInUtil = void 0;
3
+ exports.SignInFlow = exports.SignInUtil = exports.MAX_PENDING_SIGN_INS = void 0;
4
4
  const node_crypto_1 = require("node:crypto");
5
5
  const ta_protocol_1 = require("@celljs/ta-protocol");
6
6
  const sign_in_provider_1 = require("./sign-in-provider");
7
7
  /** How long the browser has with the provider, and a link of {@link SignInFlow.bindUrl}. */
8
8
  const PENDING_TTL_MS = 10 * 60 * 1000;
9
9
  const BIND_TTL_MS = 5 * 60 * 1000;
10
+ /** Sign-ins under way at most: anyone may start one without a token, and each is kept until it ends or expires. */
11
+ exports.MAX_PENDING_SIGN_INS = 1000;
10
12
  var SignInUtil;
11
13
  (function (SignInUtil) {
12
14
  /**
@@ -67,6 +69,13 @@ class SignInFlow {
67
69
  if (bind) {
68
70
  this.binds.delete(bind);
69
71
  }
72
+ // The oldest goes first: a flood of starts takes no more memory, and costs only sign-ins as old.
73
+ for (const oldest of this.pending.keys()) {
74
+ if (this.pending.size < exports.MAX_PENDING_SIGN_INS) {
75
+ break;
76
+ }
77
+ this.pending.delete(oldest);
78
+ }
70
79
  const state = (0, node_crypto_1.randomBytes)(18).toString('base64url');
71
80
  const { verifier, challenge } = SignInUtil.pkce();
72
81
  const redirectUri = SignInUtil.redirectUri(origin, provider.id);
@@ -135,8 +135,9 @@ class OidcSignIn {
135
135
  throw new SignInError(`${this.name}: ${(_b = (_a = token.error_description) !== null && _a !== void 0 ? _a : token.error) !== null && _b !== void 0 ? _b : 'no access token'}`);
136
136
  }
137
137
  const user = await SignInHttp.json(userinfo_endpoint, { headers: { Authorization: `Bearer ${token.access_token}`, Accept: 'application/json' } });
138
- // Some providers say "false" as a string.
139
- const email = user.email && user.email_verified !== false && user.email_verified !== 'false' ? user.email : undefined;
138
+ // Only an address the provider says it verified (some say "true" as a string): one it does not vouch for
139
+ // (no email_verified, as Microsoft Entra) may be any address the user typed, and would match TA_ALLOWED_USERS.
140
+ const email = user.email && (user.email_verified === true || user.email_verified === 'true') ? user.email : undefined;
140
141
  if (!email && (this.options.requireEmail || !user.sub)) {
141
142
  throw new SignInError(`${this.name}: the account has no verified email address`);
142
143
  }
@@ -0,0 +1,44 @@
1
+ import type { TaSlashCommand } from '@celljs/ta-protocol';
2
+ type Descriptions = Readonly<Record<string, string>>;
3
+ type SourceInfo = TaSlashCommand['sourceInfo'];
4
+ /** What the `/` menu lists, as pi has them: commands of extensions by the names they are run by, prompt templates, skills. */
5
+ export interface SlashCommandSources {
6
+ commands: readonly {
7
+ invocationName: string;
8
+ description?: string;
9
+ sourceInfo: SourceInfo;
10
+ }[];
11
+ prompts: readonly {
12
+ name: string;
13
+ description?: string;
14
+ sourceInfo: SourceInfo;
15
+ }[];
16
+ skills: readonly {
17
+ name: string;
18
+ description?: string;
19
+ sourceInfo: SourceInfo;
20
+ }[];
21
+ }
22
+ /**
23
+ * The descriptions in other languages of the commands of the `/` menu: `pi.descriptions` of the package.json
24
+ * of the package each command or skill comes from, by its name there (`loop`, `skill:ta-game`), each a
25
+ * string by language (`{ "zh-CN": "…" }`). The package is the nearest directory up from its file with a package.json.
26
+ */
27
+ export declare namespace SlashCommandUtil {
28
+ /** The commands of the `/` menu, in pi's order (its `get_commands`), with their descriptions in other languages. */
29
+ function list({ commands, prompts, skills }: SlashCommandSources): TaSlashCommand[];
30
+ /**
31
+ * The names the commands of extensions are run by, as pi's extension runner gives them: a name two
32
+ * extensions register is `name:1`, `name:2`, in the order the extensions loaded.
33
+ */
34
+ function invocationNames<C extends {
35
+ name: string;
36
+ }>(commands: readonly C[]): (C & {
37
+ invocationName: string;
38
+ })[];
39
+ function withDescriptions(commands: readonly TaSlashCommand[]): TaSlashCommand[];
40
+ /** `pi.descriptions` of the package `directory` is in, with only what is text. */
41
+ function descriptionsOf(directory: string): Record<string, Descriptions> | undefined;
42
+ }
43
+ export {};
44
+ //# sourceMappingURL=slash-command-util.d.ts.map
@@ -0,0 +1,108 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.SlashCommandUtil = void 0;
4
+ const node_fs_1 = require("node:fs");
5
+ const node_path_1 = require("node:path");
6
+ /**
7
+ * The descriptions in other languages of the commands of the `/` menu: `pi.descriptions` of the package.json
8
+ * of the package each command or skill comes from, by its name there (`loop`, `skill:ta-game`), each a
9
+ * string by language (`{ "zh-CN": "…" }`). The package is the nearest directory up from its file with a package.json.
10
+ */
11
+ var SlashCommandUtil;
12
+ (function (SlashCommandUtil) {
13
+ /** The commands of the `/` menu, in pi's order (its `get_commands`), with their descriptions in other languages. */
14
+ function list({ commands, prompts, skills }) {
15
+ return withDescriptions([
16
+ ...commands.map(c => ({ name: c.invocationName, description: c.description, source: 'extension', sourceInfo: c.sourceInfo })),
17
+ ...prompts.map(p => ({ name: p.name, description: p.description, source: 'prompt', sourceInfo: p.sourceInfo })),
18
+ ...skills.map(s => ({ name: `skill:${s.name}`, description: s.description, source: 'skill', sourceInfo: s.sourceInfo })),
19
+ ]);
20
+ }
21
+ SlashCommandUtil.list = list;
22
+ /**
23
+ * The names the commands of extensions are run by, as pi's extension runner gives them: a name two
24
+ * extensions register is `name:1`, `name:2`, in the order the extensions loaded.
25
+ */
26
+ function invocationNames(commands) {
27
+ var _a;
28
+ const counts = new Map();
29
+ for (const command of commands) {
30
+ counts.set(command.name, ((_a = counts.get(command.name)) !== null && _a !== void 0 ? _a : 0) + 1);
31
+ }
32
+ const seen = new Map();
33
+ const taken = new Set();
34
+ return commands.map(command => {
35
+ var _a, _b;
36
+ const occurrence = ((_a = seen.get(command.name)) !== null && _a !== void 0 ? _a : 0) + 1;
37
+ seen.set(command.name, occurrence);
38
+ let invocationName = ((_b = counts.get(command.name)) !== null && _b !== void 0 ? _b : 0) > 1 ? `${command.name}:${occurrence}` : command.name;
39
+ for (let suffix = occurrence; taken.has(invocationName);) {
40
+ suffix++;
41
+ invocationName = `${command.name}:${suffix}`;
42
+ }
43
+ taken.add(invocationName);
44
+ return { ...command, invocationName };
45
+ });
46
+ }
47
+ SlashCommandUtil.invocationNames = invocationNames;
48
+ function withDescriptions(commands) {
49
+ const packages = new Map();
50
+ return commands.map(command => {
51
+ var _a;
52
+ const { path } = command.sourceInfo;
53
+ if (!(0, node_path_1.isAbsolute)(path)) {
54
+ return command;
55
+ }
56
+ const directory = (0, node_path_1.dirname)(path);
57
+ if (!packages.has(directory)) {
58
+ packages.set(directory, descriptionsOf(directory));
59
+ }
60
+ const descriptions = (_a = packages.get(directory)) === null || _a === void 0 ? void 0 : _a[command.name];
61
+ return descriptions ? { ...command, descriptions } : command;
62
+ });
63
+ }
64
+ SlashCommandUtil.withDescriptions = withDescriptions;
65
+ /** `pi.descriptions` of the package `directory` is in, with only what is text. */
66
+ function descriptionsOf(directory) {
67
+ var _a, _b;
68
+ const root = packageRoot(directory);
69
+ if (!root) {
70
+ return undefined;
71
+ }
72
+ let declared;
73
+ try {
74
+ declared = (_b = (_a = JSON.parse((0, node_fs_1.readFileSync)((0, node_path_1.join)(root, 'package.json'), 'utf8'))) === null || _a === void 0 ? void 0 : _a.pi) === null || _b === void 0 ? void 0 : _b.descriptions;
75
+ }
76
+ catch (_c) {
77
+ return undefined;
78
+ }
79
+ if (!isRecord(declared)) {
80
+ return undefined;
81
+ }
82
+ const byName = {};
83
+ for (const [name, texts] of Object.entries(declared)) {
84
+ const languages = isRecord(texts)
85
+ ? Object.entries(texts).filter((entry) => typeof entry[1] === 'string' && entry[1].trim() !== '')
86
+ : [];
87
+ if (languages.length > 0) {
88
+ byName[name] = Object.fromEntries(languages);
89
+ }
90
+ }
91
+ return byName;
92
+ }
93
+ SlashCommandUtil.descriptionsOf = descriptionsOf;
94
+ function packageRoot(directory) {
95
+ for (let current = directory;; current = (0, node_path_1.dirname)(current)) {
96
+ if ((0, node_fs_1.existsSync)((0, node_path_1.join)(current, 'package.json'))) {
97
+ return current;
98
+ }
99
+ if ((0, node_path_1.dirname)(current) === current) {
100
+ return undefined;
101
+ }
102
+ }
103
+ }
104
+ function isRecord(value) {
105
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
106
+ }
107
+ })(SlashCommandUtil || (exports.SlashCommandUtil = SlashCommandUtil = {}));
108
+ //# sourceMappingURL=slash-command-util.js.map
@@ -1,4 +1,4 @@
1
- import type { TaConversation, TaEvent, TaMessage } from '@celljs/ta-protocol';
1
+ import { type TaConversation, type TaEvent, type TaMessage } from '@celljs/ta-protocol';
2
2
  type AgentSessionEvent = import('@earendil-works/pi-coding-agent', { with: { 'resolution-mode': 'import' } }).AgentSessionEvent;
3
3
  export declare namespace TaEventUtil {
4
4
  /**
@@ -15,8 +15,15 @@ export declare namespace TaEventUtil {
15
15
  function leanMessage(message: TaMessage): TaMessage;
16
16
  /** The result of a tool, or a message of one, without the bytes of its images. */
17
17
  function leanResult<T>(result: T): T;
18
- /** A conversation as clients get it: its messages and the results of its calls lean. */
18
+ /**
19
+ * A conversation as clients get it: its messages and the results of its calls lean, and the images of the
20
+ * messages of the user without their bytes but with their size (`TaShownImage`): they come with
21
+ * `getMessageImage` once shown, and a conversation with pictures opens as fast as one without. Events keep
22
+ * them: a message just sent shows on every device at once.
23
+ */
19
24
  function leanConversation(conversation: TaConversation): TaConversation;
25
+ /** A message as a page of the conversation gives it: `leanMessage`, and the images of the user's without their bytes. */
26
+ function leanShown(message: TaMessage): TaMessage;
20
27
  }
21
28
  export {};
22
29
  //# sourceMappingURL=ta-event-util.d.ts.map