@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
@@ -11,14 +11,19 @@ exports.SESSION_LIST_MS = 250;
11
11
  * here (`changed`), and a moment of them leaves as one list, only when it differs from the one sent.
12
12
  */
13
13
  class SessionListFeed {
14
- constructor(list, intervalMs = exports.SESSION_LIST_MS) {
14
+ constructor(list, intervalMs = exports.SESSION_LIST_MS,
15
+ /** What a connection may see of the list: all of it, but for those let in (docs/design/ta-team.md). */
16
+ filter = (_connection, list) => list) {
15
17
  this.list = list;
16
18
  this.intervalMs = intervalMs;
19
+ this.filter = filter;
17
20
  this.watchers = new Map();
21
+ /** `Date.now()` time the last connection stopped watching; 0 for none yet. */
22
+ this.leftAt = 0;
18
23
  }
19
24
  /** The list now; the connection is told of each change from now on, until it closes. */
20
25
  watch(connection) {
21
- const list = this.list();
26
+ const list = this.filter(connection, this.list());
22
27
  let watcher = this.watchers.get(connection);
23
28
  if (!watcher) {
24
29
  const created = { lastAt: Number.NEGATIVE_INFINITY };
@@ -26,12 +31,21 @@ class SessionListFeed {
26
31
  connection.onClose(() => {
27
32
  clearTimeout(created.timer);
28
33
  this.watchers.delete(connection);
34
+ this.leftAt = Date.now();
29
35
  });
30
36
  watcher = created;
31
37
  }
32
38
  watcher.sent = JSON.stringify(list);
33
39
  return list;
34
40
  }
41
+ /** The connections watching now. */
42
+ get watching() {
43
+ return this.watchers.size;
44
+ }
45
+ /** `Date.now()` time a connection last watched: now while one does; 0 for never. */
46
+ get watchedAt() {
47
+ return this.watchers.size > 0 ? Date.now() : this.leftAt;
48
+ }
35
49
  /** What a list shows changed: a session opened or closed, or one of them changed. */
36
50
  changed() {
37
51
  for (const [connection, watcher] of this.watchers) {
@@ -49,7 +63,7 @@ class SessionListFeed {
49
63
  if (connection.closed) {
50
64
  return;
51
65
  }
52
- const list = this.list();
66
+ const list = this.filter(connection, this.list());
53
67
  const json = JSON.stringify(list);
54
68
  if (json === watcher.sent) {
55
69
  return;
@@ -0,0 +1,53 @@
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';
6
+ import type { TaSession } from './ta-session';
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
+ }
53
+ //# sourceMappingURL=session-resume.d.ts.map
@@ -0,0 +1,177 @@
1
+ "use strict";
2
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
3
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
4
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
5
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
6
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
7
+ };
8
+ var __metadata = (this && this.__metadata) || function (k, v) {
9
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
10
+ };
11
+ Object.defineProperty(exports, "__esModule", { value: true });
12
+ exports.TaSessionResume = exports.TaSessionResumeUtil = exports.RESUME_PROMPT = void 0;
13
+ const node_fs_1 = require("node:fs");
14
+ const node_path_1 = require("node:path");
15
+ const core_1 = require("@celljs/core");
16
+ const ta_brand_1 = require("@celljs/ta-harness/lib/node/ta-brand");
17
+ const ta_protocol_1 = require("@celljs/ta-protocol");
18
+ const node_1 = require("@celljs/web/lib/node");
19
+ const host_protocol_1 = require("./host-protocol");
20
+ /** 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. */
21
+ const MAX_RESUMES = 2;
22
+ /** What the model is told as the conversation carries on; the web client shows the message as a mark, not this. */
23
+ exports.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.';
24
+ var TaSessionResumeUtil;
25
+ (function (TaSessionResumeUtil) {
26
+ function parse(text) {
27
+ try {
28
+ const data = JSON.parse(text);
29
+ return (Array.isArray(data) ? data : []).filter((entry) => typeof (entry === null || entry === void 0 ? void 0 : entry.sessionId) === 'string' && typeof entry.since === 'number');
30
+ }
31
+ catch (_a) {
32
+ return [];
33
+ }
34
+ }
35
+ TaSessionResumeUtil.parse = parse;
36
+ /** The queue pi announces (queue_update), as text in the order it would take it. */
37
+ function queued(event) {
38
+ const { steering, followUp } = event;
39
+ return [...(Array.isArray(steering) ? steering : []), ...(Array.isArray(followUp) ? followUp : [])].filter((text) => typeof text === 'string');
40
+ }
41
+ TaSessionResumeUtil.queued = queued;
42
+ })(TaSessionResumeUtil || (exports.TaSessionResumeUtil = TaSessionResumeUtil = {}));
43
+ /**
44
+ * Carries on the runs a restart of ta serve cut off. Every session whose run has not ended is written down
45
+ * (`ta-running.json` in the agent directory) as it starts, with what is queued for it, and struck off when the
46
+ * run ends; a stop, which closes the sessions without their events (TaSession.close), or a crash leaves the
47
+ * list as it was. At the next start each one opens again under its id and goes on, told why
48
+ * ({@link TA_RESUME_MESSAGE}), and what was queued is queued again. A session closed for good meanwhile is
49
+ * not, nor one whose run ta serve did not survive {@link MAX_RESUMES} times in a row.
50
+ */
51
+ let TaSessionResume = class TaSessionResume {
52
+ constructor() {
53
+ this.file = (0, node_path_1.join)(ta_brand_1.TaBrand.agentDir(), 'ta-running.json');
54
+ this.running = new Map();
55
+ }
56
+ onStart() {
57
+ for (const entry of TaSessionResumeUtil.parse(this.read())) {
58
+ this.running.set(entry.sessionId, entry);
59
+ }
60
+ this.unsubscribe = this.sessions.onSessionEvent((session, event) => this.observe(session, event));
61
+ }
62
+ /** Once it listens: what a session needs to open (the hosts of packages, the relay) has started by then. */
63
+ async setServer(server) {
64
+ const resume = () => void this.resume();
65
+ if (server.listening) {
66
+ resume();
67
+ }
68
+ else {
69
+ server.once('listening', resume);
70
+ }
71
+ }
72
+ /**
73
+ * The list stays: the sessions it names are those to carry on at the next start. A stop is not the runs'
74
+ * doing, unlike a crash: they start counting again.
75
+ */
76
+ onStop() {
77
+ var _a;
78
+ (_a = this.unsubscribe) === null || _a === void 0 ? void 0 : _a.call(this);
79
+ this.unsubscribe = undefined;
80
+ if ([...this.running.values()].some(entry => entry.resumes)) {
81
+ for (const [id, entry] of this.running) {
82
+ this.running.set(id, { ...entry, resumes: undefined });
83
+ }
84
+ this.save();
85
+ }
86
+ }
87
+ observe(session, event) {
88
+ const entry = this.running.get(session.id);
89
+ if (event.type === 'agent_start' && !entry) {
90
+ this.running.set(session.id, { sessionId: session.id, since: Date.now() });
91
+ }
92
+ else if (event.type === 'agent_settled' && entry) {
93
+ this.running.delete(session.id);
94
+ }
95
+ else if (event.type === 'queue_update' && entry) {
96
+ const queued = TaSessionResumeUtil.queued(event);
97
+ this.running.set(session.id, { ...entry, queued: queued.length ? queued : undefined });
98
+ }
99
+ else {
100
+ return;
101
+ }
102
+ this.save();
103
+ }
104
+ /** All at once: a page that reconnects meanwhile finds them at work, rather than cut off, the sooner. */
105
+ async resume() {
106
+ var _a;
107
+ const entries = [...this.running.values()];
108
+ for (const entry of entries) {
109
+ const resumes = ((_a = entry.resumes) !== null && _a !== void 0 ? _a : 0) + 1;
110
+ if (resumes > MAX_RESUMES) {
111
+ this.running.delete(entry.sessionId);
112
+ console.error(`ta serve: session ${entry.sessionId} ran as ta serve went down ${MAX_RESUMES} times in a row; not carried on again`);
113
+ }
114
+ else {
115
+ // Counted before it opens: a run that brings ta serve down again is one less to try.
116
+ this.running.set(entry.sessionId, { ...entry, queued: undefined, resumes });
117
+ }
118
+ }
119
+ if (entries.length) {
120
+ this.save();
121
+ }
122
+ await Promise.all(entries.filter(entry => this.running.has(entry.sessionId)).map(entry => this.open(entry)));
123
+ }
124
+ async open(entry) {
125
+ var _a;
126
+ let session;
127
+ try {
128
+ session = await this.sessions.resolve(entry.sessionId);
129
+ }
130
+ catch (error) {
131
+ // Closed for good, or its file is gone.
132
+ this.running.delete(entry.sessionId);
133
+ this.save();
134
+ console.error(`ta serve: session ${entry.sessionId} could not be carried on: ${error instanceof Error ? error.message : String(error)}`);
135
+ return;
136
+ }
137
+ if (!session.pi.isStreaming) {
138
+ this.carryOn(session, (_a = entry.queued) !== null && _a !== void 0 ? _a : []);
139
+ }
140
+ }
141
+ carryOn(session, queued) {
142
+ const { pi } = session;
143
+ const failed = (error) => console.error(`ta serve: session ${session.id} could not be carried on:`, error);
144
+ // It starts the run before it returns (pi's _startRun), so what follows queues behind it.
145
+ pi.sendCustomMessage({ customType: ta_protocol_1.TA_RESUME_MESSAGE, content: exports.RESUME_PROMPT, display: true }, { triggerTurn: true }).catch(failed);
146
+ for (const text of queued) {
147
+ pi.followUp(text, undefined, { source: 'rpc' }).catch(failed);
148
+ }
149
+ console.log(`ta serve: carried on session ${session.id}${queued.length ? `, with ${queued.length} queued` : ''}`);
150
+ }
151
+ read() {
152
+ try {
153
+ return (0, node_fs_1.readFileSync)(this.file, 'utf8');
154
+ }
155
+ catch (_a) {
156
+ return '[]';
157
+ }
158
+ }
159
+ save() {
160
+ try {
161
+ (0, node_fs_1.writeFileSync)(`${this.file}.tmp`, `${JSON.stringify([...this.running.values()])}\n`, { mode: 0o600 });
162
+ (0, node_fs_1.renameSync)(`${this.file}.tmp`, this.file);
163
+ }
164
+ catch (error) {
165
+ console.error('ta serve: the list of running sessions could not be saved:', error);
166
+ }
167
+ }
168
+ };
169
+ exports.TaSessionResume = TaSessionResume;
170
+ __decorate([
171
+ (0, core_1.Autowired)(host_protocol_1.TaSessionRegistry),
172
+ __metadata("design:type", Object)
173
+ ], TaSessionResume.prototype, "sessions", void 0);
174
+ exports.TaSessionResume = TaSessionResume = __decorate([
175
+ (0, core_1.Component)([node_1.ServerAware, core_1.ApplicationLifecycle])
176
+ ], TaSessionResume);
177
+ //# 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;
@@ -225,6 +225,28 @@ let TaSettingsStoreImpl = class TaSettingsStoreImpl {
225
225
  this.writing = next.catch(() => undefined);
226
226
  return next;
227
227
  }
228
+ rewriteUser(update) {
229
+ const next = this.writing.then(async () => {
230
+ var _a;
231
+ var _b;
232
+ const userFile = (0, node_path_1.join)((_b = (_a = this.codingAgentOptions) === null || _a === void 0 ? void 0 : _a.agentDir) !== null && _b !== void 0 ? _b : (await ai_coding_agent_1.PiSdkUtil.load()).getAgentDir(), 'settings.json');
233
+ let changed = false;
234
+ await SettingsLockUtil.run(userFile, async () => {
235
+ const before = await this.read(userFile);
236
+ const data = update(structuredClone(before));
237
+ if (JSON.stringify(data) !== JSON.stringify(before)) {
238
+ changed = true;
239
+ await (0, promises_1.writeFile)(`${userFile}.tmp`, `${JSON.stringify(data, null, 2)}\n`);
240
+ await (0, promises_1.rename)(`${userFile}.tmp`, userFile);
241
+ }
242
+ });
243
+ if (changed) {
244
+ await this.reloadSessions('user', '');
245
+ }
246
+ });
247
+ this.writing = next.catch(() => undefined);
248
+ return next;
249
+ }
228
250
  async write(scope, changes, cwd) {
229
251
  if (!changes || typeof changes !== 'object' || Array.isArray(changes)) {
230
252
  throw ta_errors_1.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>;
@@ -43,6 +43,10 @@ var TaErrors;
43
43
  return TaError(ta_protocol_1.TaErrorCode.MODEL_NOT_FOUND, `The model ${model} is not known or has no credentials.`, 'Use <provider>/<model id>; getAvailableModels lists the ones that work.');
44
44
  }
45
45
  TaErrors.modelNotFound = modelNotFound;
46
+ function limit(running) {
47
+ return TaError(ta_protocol_1.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.');
48
+ }
49
+ TaErrors.limit = limit;
46
50
  function invalidArgument(message, hint) {
47
51
  return TaError(ta_protocol_1.TaErrorCode.INVALID_ARGUMENT, message, hint);
48
52
  }
@@ -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';
4
4
  import type { TaSession } from './ta-session';
5
+ import { TaAuthority, TaPrincipals, TaRunActors, TaVisibility } from './team/team-protocol';
5
6
  import { TaWorkingDirectory } from './working-directory';
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
  }
@@ -23,6 +23,7 @@ const host_protocol_1 = require("./host-protocol");
23
23
  const session_info_util_1 = require("./session-info-util");
24
24
  const slash_command_util_1 = require("./slash-command-util");
25
25
  const ta_errors_1 = require("./ta-errors");
26
+ const team_protocol_1 = require("./team/team-protocol");
26
27
  const working_directory_1 = require("./working-directory");
27
28
  /**
28
29
  * The sessions of ta serve. Each command of pi's RPC mode does here what it does in pi's `rpc-mode`, which
@@ -37,6 +38,7 @@ let TaServerImpl = class TaServerImpl {
37
38
  user: (0, node_os_1.userInfo)().username,
38
39
  host: (0, node_os_1.hostname)().replace(/\.local$/, ''),
39
40
  home: (0, node_os_1.homedir)(),
41
+ ...(this.member() ? { member: this.member() } : {}),
40
42
  }));
41
43
  }
42
44
  async setWorkingDirectory(cwd) {
@@ -54,6 +56,9 @@ let TaServerImpl = class TaServerImpl {
54
56
  async openSession({ attach, ...options }) {
55
57
  return this.guard(async () => {
56
58
  const session = await this.sessions.open(options);
59
+ if (!options.sessionFile) {
60
+ this.runs.created(session.pi.sessionFile, session.cwd);
61
+ }
57
62
  if (!attach) {
58
63
  return session.info();
59
64
  }
@@ -65,7 +70,7 @@ let TaServerImpl = class TaServerImpl {
65
70
  return this.guard(() => this.sessions.close(sessionId));
66
71
  }
67
72
  async listSessions() {
68
- return this.sessions.list().map(session => session.info());
73
+ return this.visibility.sessions(node_1.RpcContext.connection(), this.sessions.list().map(session => session.info()));
69
74
  }
70
75
  async watchSessions() {
71
76
  return this.sessions.watch(node_1.RpcContext.requireConnection());
@@ -73,7 +78,7 @@ let TaServerImpl = class TaServerImpl {
73
78
  listSavedSessions(query) {
74
79
  return this.guard(async () => {
75
80
  const open = new Set(this.sessions.list().flatMap(session => { var _a; return (_a = session.pi.sessionFile) !== null && _a !== void 0 ? _a : []; }));
76
- return this.catalog.list(open, query !== null && query !== void 0 ? query : undefined);
81
+ return this.visibility.sessions(node_1.RpcContext.connection(), await this.catalog.list(open, query !== null && query !== void 0 ? query : undefined));
77
82
  });
78
83
  }
79
84
  attach(sessionId, afterSeq, options) {
@@ -103,17 +108,29 @@ let TaServerImpl = class TaServerImpl {
103
108
  respondClientTool(sessionId, result) {
104
109
  return this.on(sessionId, session => session.respondClientTool(this.sessions.channel(node_1.RpcContext.requireConnection()), result));
105
110
  }
111
+ /** Who the page is, when it is of one let in. */
112
+ member() {
113
+ return this.authority.describe(this.principals.current());
114
+ }
106
115
  prompt(sessionId, input) {
107
- return this.on(sessionId, session => session.prompt(input));
116
+ return this.on(sessionId, session => {
117
+ this.runs.prompted(sessionId);
118
+ return session.prompt(input);
119
+ });
108
120
  }
109
121
  steer(sessionId, input) {
122
+ this.runs.prompted(sessionId);
110
123
  return this.on(sessionId, session => session.steer(input));
111
124
  }
112
125
  followUp(sessionId, input) {
126
+ this.runs.prompted(sessionId);
113
127
  return this.on(sessionId, session => session.followUp(input));
114
128
  }
115
- abort(sessionId) {
116
- return this.on(sessionId, ({ pi }) => pi.abort());
129
+ /** 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. */
130
+ async abort(sessionId) {
131
+ const start = Date.now();
132
+ await this.on(sessionId, ({ pi }) => pi.abort());
133
+ console.log(`[${new Date().toISOString()}] ta serve: stopped ${sessionId.slice(0, 8)} in ${Date.now() - start} ms`);
117
134
  }
118
135
  clearQueue(sessionId) {
119
136
  return this.on(sessionId, ({ pi }) => pi.clearQueue());
@@ -122,7 +139,7 @@ let TaServerImpl = class TaServerImpl {
122
139
  return this.on(sessionId, session => session.removeQueued(kind, index));
123
140
  }
124
141
  newSession(sessionId, parentSession) {
125
- return this.on(sessionId, ({ runtime }) => runtime.newSession(parentSession ? { parentSession } : undefined));
142
+ return this.authored(sessionId, ({ runtime }) => runtime.newSession(parentSession ? { parentSession } : undefined));
126
143
  }
127
144
  getState(sessionId) {
128
145
  return this.on(sessionId, ({ pi }) => ({
@@ -214,7 +231,7 @@ let TaServerImpl = class TaServerImpl {
214
231
  return this.on(sessionId, ({ runtime }) => runtime.switchSession(sessionPath));
215
232
  }
216
233
  fork(sessionId, entryId, position) {
217
- return this.on(sessionId, async ({ runtime }) => {
234
+ return this.authored(sessionId, async ({ runtime }) => {
218
235
  var _a;
219
236
  const result = await runtime.fork(entryId, { position });
220
237
  return { text: (_a = result.selectedText) !== null && _a !== void 0 ? _a : '', cancelled: result.cancelled };
@@ -222,6 +239,8 @@ let TaServerImpl = class TaServerImpl {
222
239
  }
223
240
  forkToFile(sessionId, entryId, position = 'before') {
224
241
  return this.on(sessionId, async ({ pi }) => {
242
+ var _a;
243
+ var _b;
225
244
  const manager = pi.sessionManager;
226
245
  const entry = manager.getEntry(entryId);
227
246
  const user = (entry === null || entry === void 0 ? void 0 : entry.type) === 'message' && entry.message.role === 'user' ? entry.message : undefined;
@@ -237,11 +256,13 @@ let TaServerImpl = class TaServerImpl {
237
256
  // A copy of the session, so that the session itself does not move.
238
257
  const sdk = await ai_coding_agent_1.PiSdkUtil.load();
239
258
  const forked = sdk.SessionManager.open(file, manager.getSessionDir()).createBranchedSession(leafId);
240
- return { sessionFile: forked && (0, node_fs_1.existsSync)(forked) ? forked : undefined, text };
259
+ const sessionFile = forked && (0, node_fs_1.existsSync)(forked) ? forked : undefined;
260
+ this.runs.created(sessionFile, (_b = (_a = this.sessions.locate(sessionId)) === null || _a === void 0 ? void 0 : _a.cwd) !== null && _b !== void 0 ? _b : '');
261
+ return { sessionFile, text };
241
262
  });
242
263
  }
243
264
  clone(sessionId) {
244
- return this.on(sessionId, async ({ pi, runtime }) => {
265
+ return this.authored(sessionId, async ({ pi, runtime }) => {
245
266
  const leafId = pi.sessionManager.getLeafId();
246
267
  if (!leafId) {
247
268
  throw ta_errors_1.TaErrors.invalidArgument('This session has nothing to clone yet.', 'Send a message first.');
@@ -302,6 +323,17 @@ let TaServerImpl = class TaServerImpl {
302
323
  return session.reload();
303
324
  });
304
325
  }
326
+ /** A call that may move the session to a new conversation: the one who made the call is its author. */
327
+ authored(sessionId, command) {
328
+ return this.on(sessionId, async (session) => {
329
+ const before = session.pi.sessionFile;
330
+ const result = await command(session);
331
+ if (session.pi.sessionFile !== before) {
332
+ this.runs.created(session.pi.sessionFile, session.cwd);
333
+ }
334
+ return result;
335
+ });
336
+ }
305
337
  on(sessionId, command) {
306
338
  return this.guard(async () => command(await this.sessions.resolve(sessionId)));
307
339
  }
@@ -330,6 +362,22 @@ __decorate([
330
362
  (0, core_1.Autowired)(host_protocol_1.TaSessionFactory),
331
363
  __metadata("design:type", Object)
332
364
  ], TaServerImpl.prototype, "factory", void 0);
365
+ __decorate([
366
+ (0, core_1.Autowired)(team_protocol_1.TaRunActors),
367
+ __metadata("design:type", Object)
368
+ ], TaServerImpl.prototype, "runs", void 0);
369
+ __decorate([
370
+ (0, core_1.Autowired)(team_protocol_1.TaPrincipals),
371
+ __metadata("design:type", Object)
372
+ ], TaServerImpl.prototype, "principals", void 0);
373
+ __decorate([
374
+ (0, core_1.Autowired)(team_protocol_1.TaAuthority),
375
+ __metadata("design:type", Object)
376
+ ], TaServerImpl.prototype, "authority", void 0);
377
+ __decorate([
378
+ (0, core_1.Autowired)(team_protocol_1.TaVisibility),
379
+ __metadata("design:type", Object)
380
+ ], TaServerImpl.prototype, "visibility", void 0);
333
381
  exports.TaServerImpl = TaServerImpl = __decorate([
334
382
  (0, rpc_1.Rpc)(ta_protocol_1.TaServer)
335
383
  ], TaServerImpl);
@@ -146,7 +146,10 @@ let DefaultTaSessionFactory = class DefaultTaSessionFactory {
146
146
  settingsManager,
147
147
  modelRuntime,
148
148
  resourceLoaderOptions: {
149
- ...ta_harness_1.TaPackages.loaderOptions(agentDir),
149
+ ...ta_harness_1.TaPackages.loaderOptions(agentDir, {
150
+ loadSkills: sdk.loadSkillsFromDir,
151
+ projectDir: settingsManager.isProjectTrusted() ? (0, node_path_1.join)(cwd, sdk.CONFIG_DIR_NAME) : undefined,
152
+ }),
150
153
  ...(commandsOnly ? {} : await this.contextFiles(environment, agentDir)),
151
154
  extensionFactories: this.extensionFactories(sdk, environment, cwd, lock),
152
155
  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';
4
4
  import { type TaHostOptions, TaSessionFactory, TaSessionRegistry } from './host-protocol';
5
5
  import { TaSessionHandles } from './session-handles';
6
6
  import { SessionListFeed } from './session-list-feed';
7
7
  import type { TaSession } from './ta-session';
8
+ import { TaVisibility } from './team/team-protocol';
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. */