@celljs/ta-host 4.11.0 → 4.13.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 (129) hide show
  1. package/README.en.md +3 -2
  2. package/README.md +3 -2
  3. package/esm/node/extension-data-notifier.d.ts +3 -0
  4. package/esm/node/extension-data-notifier.js +8 -2
  5. package/esm/node/extension-providers.js +1 -1
  6. package/esm/node/host-protocol.d.ts +20 -1
  7. package/esm/node/host-protocol.js +1 -0
  8. package/esm/node/index.d.ts +3 -0
  9. package/esm/node/index.js +3 -0
  10. package/esm/node/keep-awake.d.ts +44 -0
  11. package/esm/node/keep-awake.js +112 -0
  12. package/esm/node/package-host-extension.js +2 -0
  13. package/esm/node/package-hosts.d.ts +23 -1
  14. package/esm/node/package-hosts.js +61 -3
  15. package/esm/node/relay-bridge.d.ts +37 -3
  16. package/esm/node/relay-bridge.js +271 -10
  17. package/esm/node/rooms-bridge.d.ts +13 -2
  18. package/esm/node/rooms-bridge.js +34 -4
  19. package/esm/node/session-catalog.d.ts +1 -1
  20. package/esm/node/session-catalog.js +5 -0
  21. package/esm/node/session-list-feed.d.ts +11 -1
  22. package/esm/node/session-list-feed.js +17 -3
  23. package/esm/node/session-resume.d.ts +52 -0
  24. package/esm/node/session-resume.js +174 -0
  25. package/esm/node/settings-store.d.ts +3 -0
  26. package/esm/node/settings-store.js +22 -0
  27. package/esm/node/ta-errors.d.ts +1 -0
  28. package/esm/node/ta-errors.js +4 -0
  29. package/esm/node/ta-server-impl.d.ts +10 -0
  30. package/esm/node/ta-server-impl.js +57 -9
  31. package/esm/node/ta-session-factory.js +5 -2
  32. package/esm/node/ta-session-registry.d.ts +12 -1
  33. package/esm/node/ta-session-registry.js +30 -1
  34. package/esm/node/ta-session.d.ts +3 -0
  35. package/esm/node/ta-session.js +16 -0
  36. package/esm/node/team/authority.d.ts +19 -0
  37. package/esm/node/team/authority.js +79 -0
  38. package/esm/node/team/call-util.d.ts +23 -0
  39. package/esm/node/team/call-util.js +88 -0
  40. package/esm/node/team/connections.d.ts +15 -0
  41. package/esm/node/team/connections.js +81 -0
  42. package/esm/node/team/host-team.d.ts +13 -0
  43. package/esm/node/team/host-team.js +69 -0
  44. package/esm/node/team/index.d.ts +13 -0
  45. package/esm/node/team/index.js +14 -0
  46. package/esm/node/team/member-devices.d.ts +11 -0
  47. package/esm/node/team/member-devices.js +56 -0
  48. package/esm/node/team/package-permissions.d.ts +23 -0
  49. package/esm/node/team/package-permissions.js +75 -0
  50. package/esm/node/team/principals.d.ts +22 -0
  51. package/esm/node/team/principals.js +72 -0
  52. package/esm/node/team/run-actors.d.ts +21 -0
  53. package/esm/node/team/run-actors.js +100 -0
  54. package/esm/node/team/shared-data.d.ts +18 -0
  55. package/esm/node/team/shared-data.js +55 -0
  56. package/esm/node/team/team-calls.d.ts +33 -0
  57. package/esm/node/team/team-calls.js +266 -0
  58. package/esm/node/team/team-gate.d.ts +31 -0
  59. package/esm/node/team/team-gate.js +177 -0
  60. package/esm/node/team/team-protocol.d.ts +89 -0
  61. package/esm/node/team/team-protocol.js +27 -0
  62. package/esm/node/team/visibility.d.ts +13 -0
  63. package/esm/node/team/visibility.js +50 -0
  64. package/esm/node/terminal-service.d.ts +5 -0
  65. package/esm/node/terminal-service.js +11 -2
  66. package/lib/node/extension-data-notifier.d.ts +3 -0
  67. package/lib/node/extension-data-notifier.js +8 -2
  68. package/lib/node/extension-providers.js +1 -1
  69. package/lib/node/host-protocol.d.ts +20 -1
  70. package/lib/node/host-protocol.js +2 -1
  71. package/lib/node/index.d.ts +3 -0
  72. package/lib/node/index.js +3 -0
  73. package/lib/node/keep-awake.d.ts +45 -0
  74. package/lib/node/keep-awake.js +115 -0
  75. package/lib/node/package-host-extension.js +2 -0
  76. package/lib/node/package-hosts.d.ts +23 -1
  77. package/lib/node/package-hosts.js +60 -2
  78. package/lib/node/relay-bridge.d.ts +37 -3
  79. package/lib/node/relay-bridge.js +269 -8
  80. package/lib/node/rooms-bridge.d.ts +13 -2
  81. package/lib/node/rooms-bridge.js +34 -4
  82. package/lib/node/session-catalog.d.ts +1 -1
  83. package/lib/node/session-catalog.js +5 -0
  84. package/lib/node/session-list-feed.d.ts +11 -1
  85. package/lib/node/session-list-feed.js +17 -3
  86. package/lib/node/session-resume.d.ts +53 -0
  87. package/lib/node/session-resume.js +177 -0
  88. package/lib/node/settings-store.d.ts +3 -0
  89. package/lib/node/settings-store.js +22 -0
  90. package/lib/node/ta-errors.d.ts +1 -0
  91. package/lib/node/ta-errors.js +4 -0
  92. package/lib/node/ta-server-impl.d.ts +10 -0
  93. package/lib/node/ta-server-impl.js +57 -9
  94. package/lib/node/ta-session-factory.js +4 -1
  95. package/lib/node/ta-session-registry.d.ts +12 -1
  96. package/lib/node/ta-session-registry.js +30 -1
  97. package/lib/node/ta-session.d.ts +3 -0
  98. package/lib/node/ta-session.js +16 -0
  99. package/lib/node/team/authority.d.ts +20 -0
  100. package/lib/node/team/authority.js +82 -0
  101. package/lib/node/team/call-util.d.ts +24 -0
  102. package/lib/node/team/call-util.js +91 -0
  103. package/lib/node/team/connections.d.ts +16 -0
  104. package/lib/node/team/connections.js +84 -0
  105. package/lib/node/team/host-team.d.ts +14 -0
  106. package/lib/node/team/host-team.js +72 -0
  107. package/lib/node/team/index.d.ts +14 -0
  108. package/lib/node/team/index.js +30 -0
  109. package/lib/node/team/member-devices.d.ts +12 -0
  110. package/lib/node/team/member-devices.js +59 -0
  111. package/lib/node/team/package-permissions.d.ts +24 -0
  112. package/lib/node/team/package-permissions.js +78 -0
  113. package/lib/node/team/principals.d.ts +23 -0
  114. package/lib/node/team/principals.js +75 -0
  115. package/lib/node/team/run-actors.d.ts +22 -0
  116. package/lib/node/team/run-actors.js +103 -0
  117. package/lib/node/team/shared-data.d.ts +19 -0
  118. package/lib/node/team/shared-data.js +58 -0
  119. package/lib/node/team/team-calls.d.ts +34 -0
  120. package/lib/node/team/team-calls.js +270 -0
  121. package/lib/node/team/team-gate.d.ts +32 -0
  122. package/lib/node/team/team-gate.js +180 -0
  123. package/lib/node/team/team-protocol.d.ts +90 -0
  124. package/lib/node/team/team-protocol.js +30 -0
  125. package/lib/node/team/visibility.d.ts +14 -0
  126. package/lib/node/team/visibility.js +53 -0
  127. package/lib/node/terminal-service.d.ts +5 -0
  128. package/lib/node/terminal-service.js +11 -2
  129. package/package.json +14 -10
@@ -8,14 +8,19 @@ export const SESSION_LIST_MS = 250;
8
8
  * here (`changed`), and a moment of them leaves as one list, only when it differs from the one sent.
9
9
  */
10
10
  export class SessionListFeed {
11
- constructor(list, intervalMs = SESSION_LIST_MS) {
11
+ constructor(list, intervalMs = SESSION_LIST_MS,
12
+ /** What a connection may see of the list: all of it, but for those let in (docs/design/ta-team.md). */
13
+ filter = (_connection, list) => list) {
12
14
  this.list = list;
13
15
  this.intervalMs = intervalMs;
16
+ this.filter = filter;
14
17
  this.watchers = new Map();
18
+ /** `Date.now()` time the last connection stopped watching; 0 for none yet. */
19
+ this.leftAt = 0;
15
20
  }
16
21
  /** The list now; the connection is told of each change from now on, until it closes. */
17
22
  watch(connection) {
18
- const list = this.list();
23
+ const list = this.filter(connection, this.list());
19
24
  let watcher = this.watchers.get(connection);
20
25
  if (!watcher) {
21
26
  const created = { lastAt: Number.NEGATIVE_INFINITY };
@@ -23,12 +28,21 @@ export class SessionListFeed {
23
28
  connection.onClose(() => {
24
29
  clearTimeout(created.timer);
25
30
  this.watchers.delete(connection);
31
+ this.leftAt = Date.now();
26
32
  });
27
33
  watcher = created;
28
34
  }
29
35
  watcher.sent = JSON.stringify(list);
30
36
  return list;
31
37
  }
38
+ /** The connections watching now. */
39
+ get watching() {
40
+ return this.watchers.size;
41
+ }
42
+ /** `Date.now()` time a connection last watched: now while one does; 0 for never. */
43
+ get watchedAt() {
44
+ return this.watchers.size > 0 ? Date.now() : this.leftAt;
45
+ }
32
46
  /** What a list shows changed: a session opened or closed, or one of them changed. */
33
47
  changed() {
34
48
  for (const [connection, watcher] of this.watchers) {
@@ -46,7 +60,7 @@ export class SessionListFeed {
46
60
  if (connection.closed) {
47
61
  return;
48
62
  }
49
- const list = this.list();
63
+ const list = this.filter(connection, this.list());
50
64
  const json = JSON.stringify(list);
51
65
  if (json === watcher.sent) {
52
66
  return;
@@ -0,0 +1,52 @@
1
+ import type { Server } from 'node:http';
2
+ import { type Application, ApplicationLifecycle } from '@celljs/core';
3
+ import { type TaEvent } from '@celljs/ta-protocol';
4
+ import { ServerAware } from '@celljs/web/lib/node';
5
+ import { TaSessionRegistry } from './host-protocol.js';
6
+ import type { TaSession } from './ta-session.js';
7
+ /** A session whose run had not ended: kept while it runs, so that a stop of ta serve, or a crash, leaves it known. */
8
+ export interface TaRunningSession {
9
+ sessionId: string;
10
+ /** `Date.now()` time its run started. */
11
+ since: number;
12
+ /** What the user had queued for it, steering then follow-ups: pi keeps its queue in memory only. */
13
+ queued?: string[];
14
+ /** How many times it was carried on since ta serve last stopped as it should, its run not ending meanwhile. */
15
+ resumes?: number;
16
+ }
17
+ /** What the model is told as the conversation carries on; the web client shows the message as a mark, not this. */
18
+ export declare const RESUME_PROMPT = "Ta restarted while you were working, and cut your turn off. Carry on from where you stopped. A command or tool that was running then may not have finished: check before you rely on what it did.";
19
+ export declare namespace TaSessionResumeUtil {
20
+ function parse(text: string): TaRunningSession[];
21
+ /** The queue pi announces (queue_update), as text in the order it would take it. */
22
+ function queued(event: TaEvent): string[];
23
+ }
24
+ /**
25
+ * Carries on the runs a restart of ta serve cut off. Every session whose run has not ended is written down
26
+ * (`ta-running.json` in the agent directory) as it starts, with what is queued for it, and struck off when the
27
+ * run ends; a stop, which closes the sessions without their events (TaSession.close), or a crash leaves the
28
+ * list as it was. At the next start each one opens again under its id and goes on, told why
29
+ * ({@link TA_RESUME_MESSAGE}), and what was queued is queued again. A session closed for good meanwhile is
30
+ * not, nor one whose run ta serve did not survive {@link MAX_RESUMES} times in a row.
31
+ */
32
+ export declare class TaSessionResume implements ServerAware, ApplicationLifecycle<Application> {
33
+ protected readonly sessions: TaSessionRegistry;
34
+ protected readonly file: string;
35
+ protected readonly running: Map<string, TaRunningSession>;
36
+ protected unsubscribe?: () => void;
37
+ onStart(): void;
38
+ /** Once it listens: what a session needs to open (the hosts of packages, the relay) has started by then. */
39
+ setServer(server: Server): Promise<void>;
40
+ /**
41
+ * The list stays: the sessions it names are those to carry on at the next start. A stop is not the runs'
42
+ * doing, unlike a crash: they start counting again.
43
+ */
44
+ onStop(): void;
45
+ protected observe(session: TaSession, event: TaEvent): void;
46
+ /** All at once: a page that reconnects meanwhile finds them at work, rather than cut off, the sooner. */
47
+ protected resume(): Promise<void>;
48
+ protected open(entry: TaRunningSession): Promise<void>;
49
+ protected carryOn(session: TaSession, queued: string[]): void;
50
+ protected read(): string;
51
+ protected save(): void;
52
+ }
@@ -0,0 +1,174 @@
1
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
2
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
3
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
4
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
5
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
6
+ };
7
+ var __metadata = (this && this.__metadata) || function (k, v) {
8
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
9
+ };
10
+ import { readFileSync, renameSync, writeFileSync } from 'node:fs';
11
+ import { join } from 'node:path';
12
+ import { ApplicationLifecycle, Autowired, Component } from '@celljs/core';
13
+ import { TaBrand } from '@celljs/ta-harness/lib/node/ta-brand';
14
+ import { TA_RESUME_MESSAGE } from '@celljs/ta-protocol';
15
+ import { ServerAware } from '@celljs/web/lib/node';
16
+ import { TaSessionRegistry } from './host-protocol.js';
17
+ /** A run that ta serve did not survive this many times in a row is let go, rather than bring it down at every start. */
18
+ const MAX_RESUMES = 2;
19
+ /** What the model is told as the conversation carries on; the web client shows the message as a mark, not this. */
20
+ export const RESUME_PROMPT = 'Ta restarted while you were working, and cut your turn off. Carry on from where you stopped. A command or tool that was running then may not have finished: check before you rely on what it did.';
21
+ export var TaSessionResumeUtil;
22
+ (function (TaSessionResumeUtil) {
23
+ function parse(text) {
24
+ try {
25
+ const data = JSON.parse(text);
26
+ return (Array.isArray(data) ? data : []).filter((entry) => typeof (entry === null || entry === void 0 ? void 0 : entry.sessionId) === 'string' && typeof entry.since === 'number');
27
+ }
28
+ catch (_a) {
29
+ return [];
30
+ }
31
+ }
32
+ TaSessionResumeUtil.parse = parse;
33
+ /** The queue pi announces (queue_update), as text in the order it would take it. */
34
+ function queued(event) {
35
+ const { steering, followUp } = event;
36
+ return [...(Array.isArray(steering) ? steering : []), ...(Array.isArray(followUp) ? followUp : [])].filter((text) => typeof text === 'string');
37
+ }
38
+ TaSessionResumeUtil.queued = queued;
39
+ })(TaSessionResumeUtil || (TaSessionResumeUtil = {}));
40
+ /**
41
+ * Carries on the runs a restart of ta serve cut off. Every session whose run has not ended is written down
42
+ * (`ta-running.json` in the agent directory) as it starts, with what is queued for it, and struck off when the
43
+ * run ends; a stop, which closes the sessions without their events (TaSession.close), or a crash leaves the
44
+ * list as it was. At the next start each one opens again under its id and goes on, told why
45
+ * ({@link TA_RESUME_MESSAGE}), and what was queued is queued again. A session closed for good meanwhile is
46
+ * not, nor one whose run ta serve did not survive {@link MAX_RESUMES} times in a row.
47
+ */
48
+ let TaSessionResume = class TaSessionResume {
49
+ constructor() {
50
+ this.file = join(TaBrand.agentDir(), 'ta-running.json');
51
+ this.running = new Map();
52
+ }
53
+ onStart() {
54
+ for (const entry of TaSessionResumeUtil.parse(this.read())) {
55
+ this.running.set(entry.sessionId, entry);
56
+ }
57
+ this.unsubscribe = this.sessions.onSessionEvent((session, event) => this.observe(session, event));
58
+ }
59
+ /** Once it listens: what a session needs to open (the hosts of packages, the relay) has started by then. */
60
+ async setServer(server) {
61
+ const resume = () => void this.resume();
62
+ if (server.listening) {
63
+ resume();
64
+ }
65
+ else {
66
+ server.once('listening', resume);
67
+ }
68
+ }
69
+ /**
70
+ * The list stays: the sessions it names are those to carry on at the next start. A stop is not the runs'
71
+ * doing, unlike a crash: they start counting again.
72
+ */
73
+ onStop() {
74
+ var _a;
75
+ (_a = this.unsubscribe) === null || _a === void 0 ? void 0 : _a.call(this);
76
+ this.unsubscribe = undefined;
77
+ if ([...this.running.values()].some(entry => entry.resumes)) {
78
+ for (const [id, entry] of this.running) {
79
+ this.running.set(id, { ...entry, resumes: undefined });
80
+ }
81
+ this.save();
82
+ }
83
+ }
84
+ observe(session, event) {
85
+ const entry = this.running.get(session.id);
86
+ if (event.type === 'agent_start' && !entry) {
87
+ this.running.set(session.id, { sessionId: session.id, since: Date.now() });
88
+ }
89
+ else if (event.type === 'agent_settled' && entry) {
90
+ this.running.delete(session.id);
91
+ }
92
+ else if (event.type === 'queue_update' && entry) {
93
+ const queued = TaSessionResumeUtil.queued(event);
94
+ this.running.set(session.id, { ...entry, queued: queued.length ? queued : undefined });
95
+ }
96
+ else {
97
+ return;
98
+ }
99
+ this.save();
100
+ }
101
+ /** All at once: a page that reconnects meanwhile finds them at work, rather than cut off, the sooner. */
102
+ async resume() {
103
+ var _a;
104
+ const entries = [...this.running.values()];
105
+ for (const entry of entries) {
106
+ const resumes = ((_a = entry.resumes) !== null && _a !== void 0 ? _a : 0) + 1;
107
+ if (resumes > MAX_RESUMES) {
108
+ this.running.delete(entry.sessionId);
109
+ console.error(`ta serve: session ${entry.sessionId} ran as ta serve went down ${MAX_RESUMES} times in a row; not carried on again`);
110
+ }
111
+ else {
112
+ // Counted before it opens: a run that brings ta serve down again is one less to try.
113
+ this.running.set(entry.sessionId, { ...entry, queued: undefined, resumes });
114
+ }
115
+ }
116
+ if (entries.length) {
117
+ this.save();
118
+ }
119
+ await Promise.all(entries.filter(entry => this.running.has(entry.sessionId)).map(entry => this.open(entry)));
120
+ }
121
+ async open(entry) {
122
+ var _a;
123
+ let session;
124
+ try {
125
+ session = await this.sessions.resolve(entry.sessionId);
126
+ }
127
+ catch (error) {
128
+ // Closed for good, or its file is gone.
129
+ this.running.delete(entry.sessionId);
130
+ this.save();
131
+ console.error(`ta serve: session ${entry.sessionId} could not be carried on: ${error instanceof Error ? error.message : String(error)}`);
132
+ return;
133
+ }
134
+ if (!session.pi.isStreaming) {
135
+ this.carryOn(session, (_a = entry.queued) !== null && _a !== void 0 ? _a : []);
136
+ }
137
+ }
138
+ carryOn(session, queued) {
139
+ const { pi } = session;
140
+ const failed = (error) => console.error(`ta serve: session ${session.id} could not be carried on:`, error);
141
+ // It starts the run before it returns (pi's _startRun), so what follows queues behind it.
142
+ pi.sendCustomMessage({ customType: TA_RESUME_MESSAGE, content: RESUME_PROMPT, display: true }, { triggerTurn: true }).catch(failed);
143
+ for (const text of queued) {
144
+ pi.followUp(text, undefined, { source: 'rpc' }).catch(failed);
145
+ }
146
+ console.log(`ta serve: carried on session ${session.id}${queued.length ? `, with ${queued.length} queued` : ''}`);
147
+ }
148
+ read() {
149
+ try {
150
+ return readFileSync(this.file, 'utf8');
151
+ }
152
+ catch (_a) {
153
+ return '[]';
154
+ }
155
+ }
156
+ save() {
157
+ try {
158
+ writeFileSync(`${this.file}.tmp`, `${JSON.stringify([...this.running.values()])}\n`, { mode: 0o600 });
159
+ renameSync(`${this.file}.tmp`, this.file);
160
+ }
161
+ catch (error) {
162
+ console.error('ta serve: the list of running sessions could not be saved:', error);
163
+ }
164
+ }
165
+ };
166
+ __decorate([
167
+ Autowired(TaSessionRegistry),
168
+ __metadata("design:type", Object)
169
+ ], TaSessionResume.prototype, "sessions", void 0);
170
+ TaSessionResume = __decorate([
171
+ Component([ServerAware, ApplicationLifecycle])
172
+ ], TaSessionResume);
173
+ export { TaSessionResume };
174
+ //# sourceMappingURL=session-resume.js.map
@@ -8,6 +8,8 @@ export declare const TaSettingsStore: unique symbol;
8
8
  export interface TaSettingsStore {
9
9
  get(cwd: string): Promise<TaSettingsSnapshot>;
10
10
  update(scope: TaSettingsScope, changes: Record<string, unknown>, cwd: string): Promise<TaSettingsSnapshot>;
11
+ /** The file of the user rewritten whole by `update`, under pi's lock; the open sessions read it again. */
12
+ rewriteUser(update: (data: Record<string, unknown>) => Record<string, unknown>): Promise<void>;
11
13
  }
12
14
  type Json = Record<string, unknown>;
13
15
  export declare namespace TaSettingsUtil {
@@ -42,6 +44,7 @@ export declare class TaSettingsStoreImpl implements TaSettingsStore {
42
44
  protected writing: Promise<unknown>;
43
45
  get(cwd: string): Promise<TaSettingsSnapshot>;
44
46
  update(scope: TaSettingsScope, changes: Record<string, unknown>, cwd: string): Promise<TaSettingsSnapshot>;
47
+ rewriteUser(update: (data: Record<string, unknown>) => Record<string, unknown>): Promise<void>;
45
48
  protected write(scope: TaSettingsScope, changes: Record<string, unknown>, cwd: string): Promise<TaSettingsSnapshot>;
46
49
  /**
47
50
  * `trusted`: pi's decision for the project, or false when it has resources pi asks about first;
@@ -222,6 +222,28 @@ let TaSettingsStoreImpl = class TaSettingsStoreImpl {
222
222
  this.writing = next.catch(() => undefined);
223
223
  return next;
224
224
  }
225
+ rewriteUser(update) {
226
+ const next = this.writing.then(async () => {
227
+ var _a;
228
+ var _b;
229
+ const userFile = join((_b = (_a = this.codingAgentOptions) === null || _a === void 0 ? void 0 : _a.agentDir) !== null && _b !== void 0 ? _b : (await PiSdkUtil.load()).getAgentDir(), 'settings.json');
230
+ let changed = false;
231
+ await SettingsLockUtil.run(userFile, async () => {
232
+ const before = await this.read(userFile);
233
+ const data = update(structuredClone(before));
234
+ if (JSON.stringify(data) !== JSON.stringify(before)) {
235
+ changed = true;
236
+ await writeFile(`${userFile}.tmp`, `${JSON.stringify(data, null, 2)}\n`);
237
+ await rename(`${userFile}.tmp`, userFile);
238
+ }
239
+ });
240
+ if (changed) {
241
+ await this.reloadSessions('user', '');
242
+ }
243
+ });
244
+ this.writing = next.catch(() => undefined);
245
+ return next;
246
+ }
225
247
  async write(scope, changes, cwd) {
226
248
  if (!changes || typeof changes !== 'object' || Array.isArray(changes)) {
227
249
  throw TaErrors.invalidArgument('The changes are an object of settings.', 'Pass { key: value }, with null to remove a key.');
@@ -5,6 +5,7 @@ export declare namespace TaErrors {
5
5
  function tooManySessions(max: number): Error;
6
6
  function messageConflict(clientMessageId: string): Error;
7
7
  function modelNotFound(model: string): Error;
8
+ function limit(running: number): Error;
8
9
  function invalidArgument(message: string, hint: string): Error;
9
10
  /** Runs a call of a service of ta serve, so that what it throws reaches the client with its message (commandFailed). */
10
11
  function guard<T>(command: () => T | Promise<T>): Promise<T>;
@@ -40,6 +40,10 @@ export var TaErrors;
40
40
  return TaError(TaErrorCode.MODEL_NOT_FOUND, `The model ${model} is not known or has no credentials.`, 'Use <provider>/<model id>; getAvailableModels lists the ones that work.');
41
41
  }
42
42
  TaErrors.modelNotFound = modelNotFound;
43
+ function limit(running) {
44
+ return TaError(TaErrorCode.LIMIT, `${running} runs of people let in are going, as many as the owner of this Ta lets at once.`, 'Try again once one ended; the owner sets the limit in Members.');
45
+ }
46
+ TaErrors.limit = limit;
43
47
  function invalidArgument(message, hint) {
44
48
  return TaError(TaErrorCode.INVALID_ARGUMENT, message, hint);
45
49
  }
@@ -2,6 +2,7 @@ import { ExecEnvironmentFactory } from '@celljs/ta-exec';
2
2
  import { type ImageContent, type RpcExtensionUIResponse, type TaAttachOptions, type TaAttachResult, type TaClientToolResult, type TaCommandResult, type TaForkFileResult, type TaMessagePage, type TaNavigateResult, type TaOpenedSession, type TaOpenSessionOptions, type TaPromptInput, type TaPromptReceipt, type TaSavedSessionInfo, type TaSavedSessionQuery, TaServer, type TaServerInfo, type TaSessionInfo, type TaSlashCommand, type ThinkingLevel } from '@celljs/ta-protocol';
3
3
  import { TaSessionCatalog, TaSessionFactory, TaSessionRegistry } from './host-protocol.js';
4
4
  import type { TaSession } from './ta-session.js';
5
+ import { TaAuthority, TaPrincipals, TaRunActors, TaVisibility } from './team/team-protocol.js';
5
6
  import { TaWorkingDirectory } from './working-directory.js';
6
7
  /**
7
8
  * The sessions of ta serve. Each command of pi's RPC mode does here what it does in pi's `rpc-mode`, which
@@ -14,6 +15,10 @@ export declare class TaServerImpl implements TaServer {
14
15
  protected readonly workingDirectory: TaWorkingDirectory;
15
16
  protected readonly catalog: TaSessionCatalog;
16
17
  protected readonly factory: TaSessionFactory;
18
+ protected readonly runs: TaRunActors;
19
+ protected readonly principals: TaPrincipals;
20
+ protected readonly authority: TaAuthority;
21
+ protected readonly visibility: TaVisibility;
17
22
  getServerInfo(): Promise<TaServerInfo>;
18
23
  setWorkingDirectory(cwd: string): Promise<TaServerInfo>;
19
24
  openSession({ attach, ...options }: TaOpenSessionOptions): Promise<TaOpenedSession>;
@@ -28,9 +33,12 @@ export declare class TaServerImpl implements TaServer {
28
33
  respondUi(sessionId: string, response: RpcExtensionUIResponse): Promise<boolean>;
29
34
  claimClientTool(sessionId: string, id: string): Promise<boolean>;
30
35
  respondClientTool(sessionId: string, result: TaClientToolResult): Promise<boolean>;
36
+ /** Who the page is, when it is of one let in. */
37
+ protected member(): import("@celljs/ta-protocol").TaMemberInfo | undefined;
31
38
  prompt(sessionId: string, input: TaPromptInput): Promise<TaPromptReceipt>;
32
39
  steer(sessionId: string, input: TaPromptInput): Promise<TaPromptReceipt>;
33
40
  followUp(sessionId: string, input: TaPromptInput): Promise<TaPromptReceipt>;
41
+ /** Logs how long the run took to end here: with the times the box keeps (stop.times of @celljs/ta-web), where a slow stop went. */
34
42
  abort(sessionId: string): Promise<void>;
35
43
  clearQueue(sessionId: string): Promise<TaCommandResult<'clear_queue'>>;
36
44
  removeQueued(sessionId: string, kind: 'steering' | 'followUp', index: number): Promise<boolean>;
@@ -70,6 +78,8 @@ export declare class TaServerImpl implements TaServer {
70
78
  commands: TaSlashCommand[];
71
79
  }>;
72
80
  reload(sessionId: string): Promise<void>;
81
+ /** A call that may move the session to a new conversation: the one who made the call is its author. */
82
+ protected authored<T>(sessionId: string, command: (session: TaSession) => T | Promise<T>): Promise<T>;
73
83
  protected on<T>(sessionId: string, command: (session: TaSession) => T | Promise<T>): Promise<T>;
74
84
  protected guard<T>(command: () => Promise<T>): Promise<T>;
75
85
  }
@@ -20,6 +20,7 @@ import { TaSessionCatalog, TaSessionFactory, TaSessionRegistry } from './host-pr
20
20
  import { SessionInfoUtil } from './session-info-util.js';
21
21
  import { SlashCommandUtil } from './slash-command-util.js';
22
22
  import { TaErrors } from './ta-errors.js';
23
+ import { TaAuthority, TaPrincipals, TaRunActors, TaVisibility } from './team/team-protocol.js';
23
24
  import { TaWorkingDirectory } from './working-directory.js';
24
25
  /**
25
26
  * The sessions of ta serve. Each command of pi's RPC mode does here what it does in pi's `rpc-mode`, which
@@ -34,6 +35,7 @@ let TaServerImpl = class TaServerImpl {
34
35
  user: userInfo().username,
35
36
  host: hostname().replace(/\.local$/, ''),
36
37
  home: homedir(),
38
+ ...(this.member() ? { member: this.member() } : {}),
37
39
  }));
38
40
  }
39
41
  async setWorkingDirectory(cwd) {
@@ -51,6 +53,9 @@ let TaServerImpl = class TaServerImpl {
51
53
  async openSession({ attach, ...options }) {
52
54
  return this.guard(async () => {
53
55
  const session = await this.sessions.open(options);
56
+ if (!options.sessionFile) {
57
+ this.runs.created(session.pi.sessionFile, session.cwd);
58
+ }
54
59
  if (!attach) {
55
60
  return session.info();
56
61
  }
@@ -62,7 +67,7 @@ let TaServerImpl = class TaServerImpl {
62
67
  return this.guard(() => this.sessions.close(sessionId));
63
68
  }
64
69
  async listSessions() {
65
- return this.sessions.list().map(session => session.info());
70
+ return this.visibility.sessions(RpcContext.connection(), this.sessions.list().map(session => session.info()));
66
71
  }
67
72
  async watchSessions() {
68
73
  return this.sessions.watch(RpcContext.requireConnection());
@@ -70,7 +75,7 @@ let TaServerImpl = class TaServerImpl {
70
75
  listSavedSessions(query) {
71
76
  return this.guard(async () => {
72
77
  const open = new Set(this.sessions.list().flatMap(session => { var _a; return (_a = session.pi.sessionFile) !== null && _a !== void 0 ? _a : []; }));
73
- return this.catalog.list(open, query !== null && query !== void 0 ? query : undefined);
78
+ return this.visibility.sessions(RpcContext.connection(), await this.catalog.list(open, query !== null && query !== void 0 ? query : undefined));
74
79
  });
75
80
  }
76
81
  attach(sessionId, afterSeq, options) {
@@ -100,17 +105,29 @@ let TaServerImpl = class TaServerImpl {
100
105
  respondClientTool(sessionId, result) {
101
106
  return this.on(sessionId, session => session.respondClientTool(this.sessions.channel(RpcContext.requireConnection()), result));
102
107
  }
108
+ /** Who the page is, when it is of one let in. */
109
+ member() {
110
+ return this.authority.describe(this.principals.current());
111
+ }
103
112
  prompt(sessionId, input) {
104
- return this.on(sessionId, session => session.prompt(input));
113
+ return this.on(sessionId, session => {
114
+ this.runs.prompted(sessionId);
115
+ return session.prompt(input);
116
+ });
105
117
  }
106
118
  steer(sessionId, input) {
119
+ this.runs.prompted(sessionId);
107
120
  return this.on(sessionId, session => session.steer(input));
108
121
  }
109
122
  followUp(sessionId, input) {
123
+ this.runs.prompted(sessionId);
110
124
  return this.on(sessionId, session => session.followUp(input));
111
125
  }
112
- abort(sessionId) {
113
- return this.on(sessionId, ({ pi }) => pi.abort());
126
+ /** Logs how long the run took to end here: with the times the box keeps (stop.times of @celljs/ta-web), where a slow stop went. */
127
+ async abort(sessionId) {
128
+ const start = Date.now();
129
+ await this.on(sessionId, ({ pi }) => pi.abort());
130
+ console.log(`[${new Date().toISOString()}] ta serve: stopped ${sessionId.slice(0, 8)} in ${Date.now() - start} ms`);
114
131
  }
115
132
  clearQueue(sessionId) {
116
133
  return this.on(sessionId, ({ pi }) => pi.clearQueue());
@@ -119,7 +136,7 @@ let TaServerImpl = class TaServerImpl {
119
136
  return this.on(sessionId, session => session.removeQueued(kind, index));
120
137
  }
121
138
  newSession(sessionId, parentSession) {
122
- return this.on(sessionId, ({ runtime }) => runtime.newSession(parentSession ? { parentSession } : undefined));
139
+ return this.authored(sessionId, ({ runtime }) => runtime.newSession(parentSession ? { parentSession } : undefined));
123
140
  }
124
141
  getState(sessionId) {
125
142
  return this.on(sessionId, ({ pi }) => ({
@@ -211,7 +228,7 @@ let TaServerImpl = class TaServerImpl {
211
228
  return this.on(sessionId, ({ runtime }) => runtime.switchSession(sessionPath));
212
229
  }
213
230
  fork(sessionId, entryId, position) {
214
- return this.on(sessionId, async ({ runtime }) => {
231
+ return this.authored(sessionId, async ({ runtime }) => {
215
232
  var _a;
216
233
  const result = await runtime.fork(entryId, { position });
217
234
  return { text: (_a = result.selectedText) !== null && _a !== void 0 ? _a : '', cancelled: result.cancelled };
@@ -219,6 +236,8 @@ let TaServerImpl = class TaServerImpl {
219
236
  }
220
237
  forkToFile(sessionId, entryId, position = 'before') {
221
238
  return this.on(sessionId, async ({ pi }) => {
239
+ var _a;
240
+ var _b;
222
241
  const manager = pi.sessionManager;
223
242
  const entry = manager.getEntry(entryId);
224
243
  const user = (entry === null || entry === void 0 ? void 0 : entry.type) === 'message' && entry.message.role === 'user' ? entry.message : undefined;
@@ -234,11 +253,13 @@ let TaServerImpl = class TaServerImpl {
234
253
  // A copy of the session, so that the session itself does not move.
235
254
  const sdk = await PiSdkUtil.load();
236
255
  const forked = sdk.SessionManager.open(file, manager.getSessionDir()).createBranchedSession(leafId);
237
- return { sessionFile: forked && existsSync(forked) ? forked : undefined, text };
256
+ const sessionFile = forked && existsSync(forked) ? forked : undefined;
257
+ this.runs.created(sessionFile, (_b = (_a = this.sessions.locate(sessionId)) === null || _a === void 0 ? void 0 : _a.cwd) !== null && _b !== void 0 ? _b : '');
258
+ return { sessionFile, text };
238
259
  });
239
260
  }
240
261
  clone(sessionId) {
241
- return this.on(sessionId, async ({ pi, runtime }) => {
262
+ return this.authored(sessionId, async ({ pi, runtime }) => {
242
263
  const leafId = pi.sessionManager.getLeafId();
243
264
  if (!leafId) {
244
265
  throw TaErrors.invalidArgument('This session has nothing to clone yet.', 'Send a message first.');
@@ -299,6 +320,17 @@ let TaServerImpl = class TaServerImpl {
299
320
  return session.reload();
300
321
  });
301
322
  }
323
+ /** A call that may move the session to a new conversation: the one who made the call is its author. */
324
+ authored(sessionId, command) {
325
+ return this.on(sessionId, async (session) => {
326
+ const before = session.pi.sessionFile;
327
+ const result = await command(session);
328
+ if (session.pi.sessionFile !== before) {
329
+ this.runs.created(session.pi.sessionFile, session.cwd);
330
+ }
331
+ return result;
332
+ });
333
+ }
302
334
  on(sessionId, command) {
303
335
  return this.guard(async () => command(await this.sessions.resolve(sessionId)));
304
336
  }
@@ -326,6 +358,22 @@ __decorate([
326
358
  Autowired(TaSessionFactory),
327
359
  __metadata("design:type", Object)
328
360
  ], TaServerImpl.prototype, "factory", void 0);
361
+ __decorate([
362
+ Autowired(TaRunActors),
363
+ __metadata("design:type", Object)
364
+ ], TaServerImpl.prototype, "runs", void 0);
365
+ __decorate([
366
+ Autowired(TaPrincipals),
367
+ __metadata("design:type", Object)
368
+ ], TaServerImpl.prototype, "principals", void 0);
369
+ __decorate([
370
+ Autowired(TaAuthority),
371
+ __metadata("design:type", Object)
372
+ ], TaServerImpl.prototype, "authority", void 0);
373
+ __decorate([
374
+ Autowired(TaVisibility),
375
+ __metadata("design:type", Object)
376
+ ], TaServerImpl.prototype, "visibility", void 0);
329
377
  TaServerImpl = __decorate([
330
378
  Rpc(TaServer)
331
379
  ], TaServerImpl);
@@ -8,7 +8,7 @@ var __metadata = (this && this.__metadata) || function (k, v) {
8
8
  if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
9
9
  };
10
10
  import { statSync } from 'node:fs';
11
- import { resolve, sep } from 'node:path';
11
+ import { join, resolve, sep } from 'node:path';
12
12
  import { AgentExtension, AgentTool, AgentToolUtil, CODING_AGENT_OPTIONS, ModelRuntimeProvider, PiSdkUtil, } from '@celljs/ai-coding-agent';
13
13
  import { Autowired, Component, Optional, Value } from '@celljs/core';
14
14
  import { ExecEnvironmentFactory } from '@celljs/ta-exec';
@@ -143,7 +143,10 @@ let DefaultTaSessionFactory = class DefaultTaSessionFactory {
143
143
  settingsManager,
144
144
  modelRuntime,
145
145
  resourceLoaderOptions: {
146
- ...TaPackages.loaderOptions(agentDir),
146
+ ...TaPackages.loaderOptions(agentDir, {
147
+ loadSkills: sdk.loadSkillsFromDir,
148
+ projectDir: settingsManager.isProjectTrusted() ? join(cwd, sdk.CONFIG_DIR_NAME) : undefined,
149
+ }),
147
150
  ...(commandsOnly ? {} : await this.contextFiles(environment, agentDir)),
148
151
  extensionFactories: this.extensionFactories(sdk, environment, cwd, lock),
149
152
  appendSystemPrompt: appendSystemPrompt ? [appendSystemPrompt] : undefined,
@@ -1,10 +1,11 @@
1
1
  import type { RpcConnection } from '@celljs/rpc/lib/node';
2
- import type { TaOpenSessionOptions, TaSessionInfo } from '@celljs/ta-protocol';
2
+ import type { TaEvent, TaOpenSessionOptions, TaSessionInfo } from '@celljs/ta-protocol';
3
3
  import { ClientChannel } from './client-channel.js';
4
4
  import { type TaHostOptions, TaSessionFactory, TaSessionRegistry } from './host-protocol.js';
5
5
  import { TaSessionHandles } from './session-handles.js';
6
6
  import { SessionListFeed } from './session-list-feed.js';
7
7
  import type { TaSession } from './ta-session.js';
8
+ import { TaVisibility } from './team/team-protocol.js';
8
9
  /**
9
10
  * The open sessions. A session's id outlives its memory: closed while idle or by a restart, it opens again
10
11
  * from its file under the same id at the next call (TaSessionHandles), so clients never see it go.
@@ -15,18 +16,28 @@ export declare class DefaultTaSessionRegistry implements TaSessionRegistry {
15
16
  protected readonly handles: TaSessionHandles;
16
17
  protected readonly sessions: Map<string, TaSession>;
17
18
  protected readonly channels: WeakMap<RpcConnection, ClientChannel>;
19
+ protected readonly eventListeners: Set<(session: TaSession, event: TaEvent) => void>;
18
20
  /** Sessions being created count against the limit too. */
19
21
  protected opening: number;
20
22
  /** The closes under way, by session file: out of the list already, their files locked until they end. */
21
23
  protected readonly closing: Map<string, Promise<void>>;
22
24
  /** Sessions opening again under their ids: the calls that come meanwhile wait for the same. */
23
25
  protected readonly waking: Map<string, Promise<TaSession>>;
26
+ /** What each connection may see of the list (docs/design/ta-team.md): all of it for the owner's. */
27
+ protected readonly visibility: TaVisibility;
24
28
  protected readonly feed: SessionListFeed;
29
+ locate(sessionId: string): {
30
+ sessionFile?: string;
31
+ cwd: string;
32
+ } | undefined;
25
33
  open(options: TaOpenSessionOptions): Promise<TaSession>;
26
34
  require(sessionId: string): TaSession;
27
35
  resolve(sessionId: string): Promise<TaSession>;
28
36
  list(): TaSession[];
29
37
  watch(connection: RpcConnection): TaSessionInfo[];
38
+ get watching(): number;
39
+ get watchedAt(): number;
40
+ onSessionEvent(listener: (session: TaSession, event: TaEvent) => void): () => void;
30
41
  close(sessionId: string, idle?: boolean): Promise<void>;
31
42
  closeAll(): Promise<void>;
32
43
  /** The one channel of a connection; it leaves every session when the connection ends. */