@celljs/ta-host 4.9.1 → 4.11.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 (117) hide show
  1. package/README.en.md +5 -5
  2. package/README.md +5 -5
  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/event-log.d.ts +2 -1
  6. package/esm/node/event-log.js +3 -2
  7. package/esm/node/exec-environment-factory.d.ts +7 -0
  8. package/esm/node/exec-environment-factory.js +30 -7
  9. package/esm/node/host-protocol.d.ts +24 -10
  10. package/esm/node/index.d.ts +2 -0
  11. package/esm/node/index.js +2 -0
  12. package/esm/node/package-hosts.d.ts +6 -0
  13. package/esm/node/package-hosts.js +36 -1
  14. package/esm/node/package-server-impl.d.ts +0 -1
  15. package/esm/node/package-server-impl.js +0 -3
  16. package/esm/node/relay-bridge.d.ts +12 -2
  17. package/esm/node/relay-bridge.js +93 -3
  18. package/esm/node/remote/remote-hosts.d.ts +1 -3
  19. package/esm/node/remote/remote-hosts.js +0 -15
  20. package/esm/node/remote/remote-protocol.d.ts +0 -2
  21. package/esm/node/remote/remote-server-impl.js +1 -1
  22. package/esm/node/remote-ui-context.d.ts +1 -1
  23. package/esm/node/remote-ui-context.js +3 -1
  24. package/esm/node/rooms-bridge.d.ts +60 -0
  25. package/esm/node/rooms-bridge.js +155 -0
  26. package/esm/node/session-catalog.d.ts +7 -3
  27. package/esm/node/session-catalog.js +15 -4
  28. package/esm/node/session-handles.d.ts +32 -0
  29. package/esm/node/session-handles.js +86 -0
  30. package/esm/node/session-info-util.d.ts +7 -0
  31. package/esm/node/session-info-util.js +63 -4
  32. package/esm/node/session-list-feed.d.ts +28 -0
  33. package/esm/node/session-list-feed.js +62 -0
  34. package/esm/node/sign-in/sign-in-flow.d.ts +2 -0
  35. package/esm/node/sign-in/sign-in-flow.js +9 -0
  36. package/esm/node/sign-in/sign-in-provider.js +3 -2
  37. package/esm/node/slash-command-util.d.ts +43 -0
  38. package/esm/node/slash-command-util.js +105 -0
  39. package/esm/node/ta-access.d.ts +11 -0
  40. package/esm/node/ta-access.js +29 -3
  41. package/esm/node/ta-errors.js +17 -2
  42. package/esm/node/ta-event-util.d.ts +19 -2
  43. package/esm/node/ta-event-util.js +97 -3
  44. package/esm/node/ta-server-impl.d.ts +13 -7
  45. package/esm/node/ta-server-impl.js +43 -24
  46. package/esm/node/ta-session-factory.d.ts +26 -2
  47. package/esm/node/ta-session-factory.js +64 -16
  48. package/esm/node/ta-session-registry.d.ts +16 -2
  49. package/esm/node/ta-session-registry.js +79 -20
  50. package/esm/node/ta-session.d.ts +16 -6
  51. package/esm/node/ta-session.js +59 -14
  52. package/esm/node/web-extension-catalog.d.ts +5 -1
  53. package/esm/node/web-extension-catalog.js +15 -19
  54. package/esm/node/web-extension-util.js +7 -3
  55. package/esm/node/workspace-files.d.ts +19 -5
  56. package/esm/node/workspace-files.js +26 -15
  57. package/esm/node/workspace-protocol.d.ts +1 -1
  58. package/esm/node/workspace-util.d.ts +2 -0
  59. package/esm/node/workspace-util.js +8 -3
  60. package/lib/node/client-tool-broker.d.ts +6 -2
  61. package/lib/node/client-tool-broker.js +11 -4
  62. package/lib/node/event-log.d.ts +2 -1
  63. package/lib/node/event-log.js +3 -2
  64. package/lib/node/exec-environment-factory.d.ts +7 -0
  65. package/lib/node/exec-environment-factory.js +30 -7
  66. package/lib/node/host-protocol.d.ts +24 -10
  67. package/lib/node/index.d.ts +2 -0
  68. package/lib/node/index.js +2 -0
  69. package/lib/node/package-hosts.d.ts +6 -0
  70. package/lib/node/package-hosts.js +35 -0
  71. package/lib/node/package-server-impl.d.ts +0 -1
  72. package/lib/node/package-server-impl.js +0 -3
  73. package/lib/node/relay-bridge.d.ts +12 -2
  74. package/lib/node/relay-bridge.js +91 -1
  75. package/lib/node/remote/remote-hosts.d.ts +1 -3
  76. package/lib/node/remote/remote-hosts.js +0 -15
  77. package/lib/node/remote/remote-protocol.d.ts +0 -2
  78. package/lib/node/remote/remote-server-impl.js +1 -1
  79. package/lib/node/remote-ui-context.d.ts +1 -1
  80. package/lib/node/remote-ui-context.js +3 -1
  81. package/lib/node/rooms-bridge.d.ts +61 -0
  82. package/lib/node/rooms-bridge.js +158 -0
  83. package/lib/node/session-catalog.d.ts +7 -3
  84. package/lib/node/session-catalog.js +15 -4
  85. package/lib/node/session-handles.d.ts +33 -0
  86. package/lib/node/session-handles.js +89 -0
  87. package/lib/node/session-info-util.d.ts +7 -0
  88. package/lib/node/session-info-util.js +62 -3
  89. package/lib/node/session-list-feed.d.ts +29 -0
  90. package/lib/node/session-list-feed.js +66 -0
  91. package/lib/node/sign-in/sign-in-flow.d.ts +2 -0
  92. package/lib/node/sign-in/sign-in-flow.js +10 -1
  93. package/lib/node/sign-in/sign-in-provider.js +3 -2
  94. package/lib/node/slash-command-util.d.ts +44 -0
  95. package/lib/node/slash-command-util.js +108 -0
  96. package/lib/node/ta-access.d.ts +11 -0
  97. package/lib/node/ta-access.js +29 -3
  98. package/lib/node/ta-errors.js +17 -2
  99. package/lib/node/ta-event-util.d.ts +19 -2
  100. package/lib/node/ta-event-util.js +97 -3
  101. package/lib/node/ta-server-impl.d.ts +13 -7
  102. package/lib/node/ta-server-impl.js +41 -22
  103. package/lib/node/ta-session-factory.d.ts +26 -2
  104. package/lib/node/ta-session-factory.js +65 -17
  105. package/lib/node/ta-session-registry.d.ts +16 -2
  106. package/lib/node/ta-session-registry.js +79 -20
  107. package/lib/node/ta-session.d.ts +16 -6
  108. package/lib/node/ta-session.js +59 -14
  109. package/lib/node/web-extension-catalog.d.ts +5 -1
  110. package/lib/node/web-extension-catalog.js +15 -19
  111. package/lib/node/web-extension-util.js +7 -3
  112. package/lib/node/workspace-files.d.ts +19 -5
  113. package/lib/node/workspace-files.js +26 -15
  114. package/lib/node/workspace-protocol.d.ts +1 -1
  115. package/lib/node/workspace-util.d.ts +2 -0
  116. package/lib/node/workspace-util.js +8 -3
  117. package/package.json +12 -12
@@ -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
@@ -77,6 +77,7 @@ var SessionCatalogUtil;
77
77
  let header;
78
78
  let sessionName;
79
79
  let firstMessage;
80
+ const messages = [];
80
81
  let messageCount = 0;
81
82
  let updatedAt;
82
83
  const marks = [];
@@ -102,6 +103,7 @@ var SessionCatalogUtil;
102
103
  const message = entry.message;
103
104
  messageCount++;
104
105
  firstMessage !== null && firstMessage !== void 0 ? firstMessage : (firstMessage = session_info_util_1.SessionInfoUtil.firstMessage([message]));
106
+ messages.push(message);
105
107
  if (typeof message.timestamp === 'number') {
106
108
  updatedAt = Math.max(updatedAt !== null && updatedAt !== void 0 ? updatedAt : 0, message.timestamp);
107
109
  }
@@ -117,6 +119,7 @@ var SessionCatalogUtil;
117
119
  piCwd: typeof header.cwd === 'string' ? header.cwd : '',
118
120
  sessionName,
119
121
  firstMessage,
122
+ lastMessage: session_info_util_1.SessionInfoUtil.lastMessage(messages),
120
123
  messageCount,
121
124
  createdAt,
122
125
  updatedAt: updatedAt !== null && updatedAt !== void 0 ? updatedAt : createdAt,
@@ -146,15 +149,16 @@ let DefaultTaSessionCatalog = class DefaultTaSessionCatalog {
146
149
  /** By file: its size and time when read, and what it held. */
147
150
  this.cache = new Map();
148
151
  }
149
- async list(open = new Set()) {
152
+ async list(open = new Set(), query = {}) {
150
153
  const files = await this.files(await this.sessionsDir());
151
154
  // An open session's file grows with every message: it is not read again for a list that leaves it out.
152
155
  const closed = files.filter(file => !open.has(file));
156
+ const { since, before } = query;
153
157
  const sessions = [];
154
158
  for (let i = 0; i < closed.length; i += BATCH) {
155
159
  await Promise.all(closed.slice(i, i + BATCH).map(async (file) => {
156
- const summary = await this.summary(file);
157
- if (summary) {
160
+ const summary = await this.summary(file, since);
161
+ if (summary && (since === undefined || summary.updatedAt >= since) && (before === undefined || summary.updatedAt < before)) {
158
162
  const { piCwd, ...info } = summary;
159
163
  sessions.push({ ...info, sessionFile: file, cwd: piCwd && this.directories.fromPi(piCwd) });
160
164
  }
@@ -185,7 +189,11 @@ let DefaultTaSessionCatalog = class DefaultTaSessionCatalog {
185
189
  }));
186
190
  return files.flat();
187
191
  }
188
- 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) {
189
197
  const stats = await (0, promises_1.stat)(file).catch(() => undefined);
190
198
  if (!(stats === null || stats === void 0 ? void 0 : stats.isFile())) {
191
199
  return undefined;
@@ -195,6 +203,9 @@ let DefaultTaSessionCatalog = class DefaultTaSessionCatalog {
195
203
  if ((cached === null || cached === void 0 ? void 0 : cached.version) === version) {
196
204
  return cached.summary;
197
205
  }
206
+ if (since !== undefined && stats.mtimeMs < since) {
207
+ return undefined;
208
+ }
198
209
  const text = await (0, promises_1.readFile)(file, 'utf8').catch(() => undefined);
199
210
  const summary = text === undefined ? undefined : SessionCatalogUtil.summarize(text, stats.mtimeMs);
200
211
  this.cache.set(file, { version, summary });
@@ -0,0 +1,33 @@
1
+ import type { TaClientToolDefinition } from '@celljs/ta-protocol';
2
+ export declare const TaSessionHandles: unique symbol;
3
+ /** What opens a session again under the id clients have: its file, where it works, the tools its clients run. */
4
+ export interface TaSessionHandle {
5
+ sessionFile: string;
6
+ cwd: string;
7
+ clientTools?: TaClientToolDefinition[];
8
+ }
9
+ /**
10
+ * The ids of the sessions ta serve gave, with what opens each again. A session closed while idle, or by a
11
+ * restart, keeps its id: the next call with it opens it again (TaSessionRegistry.resolve), so that a page
12
+ * that slept through it carries on rather than failing with CELL_TA_SESSION_NOT_FOUND. Only a session
13
+ * closed for good (closeSession, an extension that ends it) loses its id.
14
+ */
15
+ export interface TaSessionHandles {
16
+ get(sessionId: string): TaSessionHandle | undefined;
17
+ /** The id kept for a session file. */
18
+ idOf(sessionFile: string): string | undefined;
19
+ set(sessionId: string, handle: TaSessionHandle): void;
20
+ delete(sessionId: string): void;
21
+ }
22
+ /** In ta-sessions.json of the agent directory, the latest last; kept across restarts. */
23
+ export declare class TaSessionHandlesImpl implements TaSessionHandles {
24
+ protected readonly file: string;
25
+ protected cache?: Map<string, TaSessionHandle>;
26
+ get(sessionId: string): TaSessionHandle | undefined;
27
+ idOf(sessionFile: string): string | undefined;
28
+ set(sessionId: string, handle: TaSessionHandle): void;
29
+ delete(sessionId: string): void;
30
+ protected read(): Map<string, TaSessionHandle>;
31
+ protected write(handles: Map<string, TaSessionHandle>): void;
32
+ }
33
+ //# sourceMappingURL=session-handles.d.ts.map
@@ -0,0 +1,89 @@
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
+ Object.defineProperty(exports, "__esModule", { value: true });
9
+ exports.TaSessionHandlesImpl = exports.TaSessionHandles = void 0;
10
+ const node_fs_1 = require("node:fs");
11
+ const node_path_1 = require("node:path");
12
+ const core_1 = require("@celljs/core");
13
+ const ta_brand_1 = require("@celljs/ta-harness/lib/node/ta-brand");
14
+ exports.TaSessionHandles = Symbol('TaSessionHandles');
15
+ /** Handles kept: the latest ones, as a client that slept longer has the conversation in its list again. */
16
+ const MAX_HANDLES = 200;
17
+ /** In ta-sessions.json of the agent directory, the latest last; kept across restarts. */
18
+ let TaSessionHandlesImpl = class TaSessionHandlesImpl {
19
+ constructor() {
20
+ this.file = (0, node_path_1.join)(ta_brand_1.TaBrand.agentDir(), 'ta-sessions.json');
21
+ }
22
+ get(sessionId) {
23
+ return this.read().get(sessionId);
24
+ }
25
+ idOf(sessionFile) {
26
+ for (const [id, handle] of this.read()) {
27
+ if (handle.sessionFile === sessionFile) {
28
+ return id;
29
+ }
30
+ }
31
+ return undefined;
32
+ }
33
+ set(sessionId, handle) {
34
+ const handles = this.read();
35
+ // One id per file: the file opened under another is reached by that one.
36
+ for (const [id, other] of handles) {
37
+ if (id !== sessionId && other.sessionFile === handle.sessionFile) {
38
+ handles.delete(id);
39
+ }
40
+ }
41
+ handles.delete(sessionId);
42
+ handles.set(sessionId, handle);
43
+ for (const id of handles.keys()) {
44
+ if (handles.size <= MAX_HANDLES) {
45
+ break;
46
+ }
47
+ handles.delete(id);
48
+ }
49
+ this.write(handles);
50
+ }
51
+ delete(sessionId) {
52
+ const handles = this.read();
53
+ if (handles.delete(sessionId)) {
54
+ this.write(handles);
55
+ }
56
+ }
57
+ read() {
58
+ if (!this.cache) {
59
+ this.cache = new Map();
60
+ try {
61
+ const data = JSON.parse((0, node_fs_1.readFileSync)(this.file, 'utf8'));
62
+ for (const [id, handle] of Object.entries(data && typeof data === 'object' && !Array.isArray(data) ? data : {})) {
63
+ const { sessionFile, cwd } = (handle !== null && handle !== void 0 ? handle : {});
64
+ if (typeof sessionFile === 'string' && typeof cwd === 'string') {
65
+ this.cache.set(id, handle);
66
+ }
67
+ }
68
+ }
69
+ catch (_a) {
70
+ // None yet, or not readable: no handles.
71
+ }
72
+ }
73
+ return this.cache;
74
+ }
75
+ write(handles) {
76
+ try {
77
+ (0, node_fs_1.writeFileSync)(`${this.file}.tmp`, `${JSON.stringify(Object.fromEntries(handles))}\n`, { mode: 0o600 });
78
+ (0, node_fs_1.renameSync)(`${this.file}.tmp`, this.file);
79
+ }
80
+ catch (_a) {
81
+ // Kept in memory: only a restart forgets them.
82
+ }
83
+ }
84
+ };
85
+ exports.TaSessionHandlesImpl = TaSessionHandlesImpl;
86
+ exports.TaSessionHandlesImpl = TaSessionHandlesImpl = __decorate([
87
+ (0, core_1.Component)(exports.TaSessionHandles)
88
+ ], TaSessionHandlesImpl);
89
+ //# sourceMappingURL=session-handles.js.map
@@ -11,6 +11,13 @@ export declare namespace SessionInfoUtil {
11
11
  * a skill the user ran is `/skill:name` and what follows, not the skill's file.
12
12
  */
13
13
  function firstMessage(messages: readonly MessageLike[]): string | undefined;
14
+ /**
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
+ * 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; a skill the user ran is
18
+ * `/skill:name` and what follows, as the title says it, not the skill's file.
19
+ */
20
+ function lastMessage(messages: readonly MessageLike[]): string | undefined;
14
21
  /** The time of the last message that has one, else `fallback`. */
15
22
  function updatedAt(messages: readonly MessageLike[], fallback: number): number;
16
23
  /** The text of the content of a message. */
@@ -6,6 +6,8 @@ const ta_protocol_1 = require("@celljs/ta-protocol");
6
6
  var SessionInfoUtil;
7
7
  (function (SessionInfoUtil) {
8
8
  const LENGTH = 120;
9
+ /** Of the text of the last message, what lastMessage reads: its lines are joined, many of them empty or marks only. */
10
+ const PREVIEW_READ = 2000;
9
11
  /**
10
12
  * The first line of the first message of the user that has text, without its context, cut to a title's length;
11
13
  * a skill the user ran is `/skill:name` and what follows, not the skill's file.
@@ -15,9 +17,7 @@ var SessionInfoUtil;
15
17
  if (message.role !== 'user') {
16
18
  continue;
17
19
  }
18
- const said = ta_protocol_1.TaMessageContext.strip(text(message.content));
19
- const skill = ta_protocol_1.TaSkillUse.parse(said);
20
- const line = (skill ? ta_protocol_1.TaSkillUse.command(skill) : said)
20
+ const line = userWords(text(message.content))
21
21
  .split('\n')
22
22
  .map(part => part.trim())
23
23
  .find(Boolean);
@@ -28,6 +28,65 @@ var SessionInfoUtil;
28
28
  return undefined;
29
29
  }
30
30
  SessionInfoUtil.firstMessage = firstMessage;
31
+ /**
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
33
+ * length, as a messaging app shows the last thing said under its name: without its context, the marks of
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.
36
+ */
37
+ function lastMessage(messages) {
38
+ for (let i = messages.length - 1; i >= 0; i--) {
39
+ const message = messages[i];
40
+ if (message.role !== 'user' && message.role !== 'assistant') {
41
+ continue;
42
+ }
43
+ const said = message.role === 'user' ? userWords(text(message.content)) : ta_protocol_1.TaAgentSummary.strip(text(message.content));
44
+ // A list asks for it every few seconds: only the start of a long reply is read, enough for a preview.
45
+ const read = said.slice(0, PREVIEW_READ);
46
+ const line = (withoutFences(read) || read)
47
+ .split('\n')
48
+ .map(part => part
49
+ .replace(/^\s*(?:#{1,6}\s+|>\s*|[-*+]\s+|\d+\.\s+)/, '')
50
+ .replace(/[*_`]{1,3}/g, '')
51
+ .trim())
52
+ .filter(Boolean)
53
+ .join(' ')
54
+ .replace(/\s+/g, ' ');
55
+ if (line) {
56
+ return line.length > LENGTH ? `${line.slice(0, LENGTH - 1)}…` : line;
57
+ }
58
+ }
59
+ return undefined;
60
+ }
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
+ }
31
90
  /** The time of the last message that has one, else `fallback`. */
32
91
  function updatedAt(messages, fallback) {
33
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
  }