@celljs/ta-host 0.0.0-stage → 4.5.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 (155) hide show
  1. package/README.md +33 -2
  2. package/cell.schema.json +33 -0
  3. package/cell.yml +14 -0
  4. package/esm/node/client-channel.d.ts +31 -0
  5. package/esm/node/client-channel.js +84 -0
  6. package/esm/node/client-channel.js.map +1 -0
  7. package/esm/node/event-log.d.ts +28 -0
  8. package/esm/node/event-log.js +48 -0
  9. package/esm/node/event-log.js.map +1 -0
  10. package/esm/node/host-protocol.d.ts +27 -0
  11. package/esm/node/host-protocol.js +4 -0
  12. package/esm/node/host-protocol.js.map +1 -0
  13. package/esm/node/index.d.ts +13 -0
  14. package/esm/node/index.js +14 -0
  15. package/esm/node/index.js.map +1 -0
  16. package/esm/node/local-exec-environment-factory.d.ts +4 -0
  17. package/esm/node/local-exec-environment-factory.js +18 -0
  18. package/esm/node/local-exec-environment-factory.js.map +1 -0
  19. package/esm/node/module.d.ts +3 -0
  20. package/esm/node/module.js +4 -0
  21. package/esm/node/module.js.map +1 -0
  22. package/esm/node/receipt-book.d.ts +12 -0
  23. package/esm/node/receipt-book.js +38 -0
  24. package/esm/node/receipt-book.js.map +1 -0
  25. package/esm/node/remote-ui-context.d.ts +63 -0
  26. package/esm/node/remote-ui-context.js +130 -0
  27. package/esm/node/remote-ui-context.js.map +1 -0
  28. package/esm/node/ta-access.d.ts +30 -0
  29. package/esm/node/ta-access.js +107 -0
  30. package/esm/node/ta-access.js.map +1 -0
  31. package/esm/node/ta-errors.d.ts +11 -0
  32. package/esm/node/ta-errors.js +44 -0
  33. package/esm/node/ta-errors.js.map +1 -0
  34. package/esm/node/ta-event-util.d.ts +11 -0
  35. package/esm/node/ta-event-util.js +20 -0
  36. package/esm/node/ta-event-util.js.map +1 -0
  37. package/esm/node/ta-server-impl.d.ts +50 -0
  38. package/esm/node/ta-server-impl.js +226 -0
  39. package/esm/node/ta-server-impl.js.map +1 -0
  40. package/esm/node/ta-session-factory.d.ts +32 -0
  41. package/esm/node/ta-session-factory.js +151 -0
  42. package/esm/node/ta-session-factory.js.map +1 -0
  43. package/esm/node/ta-session-registry.d.ts +20 -0
  44. package/esm/node/ta-session-registry.js +85 -0
  45. package/esm/node/ta-session-registry.js.map +1 -0
  46. package/esm/node/ta-session.d.ts +53 -0
  47. package/esm/node/ta-session.js +157 -0
  48. package/esm/node/ta-session.js.map +1 -0
  49. package/esm/package.json +3 -0
  50. package/lib/node/client-channel.d.ts +32 -0
  51. package/lib/node/client-channel.d.ts.map +1 -0
  52. package/lib/node/client-channel.js +88 -0
  53. package/lib/node/client-channel.js.map +1 -0
  54. package/lib/node/client-channel.spec.d.ts +2 -0
  55. package/lib/node/client-channel.spec.d.ts.map +1 -0
  56. package/lib/node/client-channel.spec.js +106 -0
  57. package/lib/node/client-channel.spec.js.map +1 -0
  58. package/lib/node/event-log.d.ts +29 -0
  59. package/lib/node/event-log.d.ts.map +1 -0
  60. package/lib/node/event-log.js +52 -0
  61. package/lib/node/event-log.js.map +1 -0
  62. package/lib/node/event-log.spec.d.ts +2 -0
  63. package/lib/node/event-log.spec.d.ts.map +1 -0
  64. package/lib/node/event-log.spec.js +48 -0
  65. package/lib/node/event-log.spec.js.map +1 -0
  66. package/lib/node/host-protocol.d.ts +28 -0
  67. package/lib/node/host-protocol.d.ts.map +1 -0
  68. package/lib/node/host-protocol.js +7 -0
  69. package/lib/node/host-protocol.js.map +1 -0
  70. package/lib/node/index.d.ts +14 -0
  71. package/lib/node/index.d.ts.map +1 -0
  72. package/lib/node/index.js +30 -0
  73. package/lib/node/index.js.map +1 -0
  74. package/lib/node/local-exec-environment-factory.d.ts +5 -0
  75. package/lib/node/local-exec-environment-factory.d.ts.map +1 -0
  76. package/lib/node/local-exec-environment-factory.js +21 -0
  77. package/lib/node/local-exec-environment-factory.js.map +1 -0
  78. package/lib/node/module.d.ts +4 -0
  79. package/lib/node/module.d.ts.map +1 -0
  80. package/lib/node/module.js +6 -0
  81. package/lib/node/module.js.map +1 -0
  82. package/lib/node/receipt-book.d.ts +13 -0
  83. package/lib/node/receipt-book.d.ts.map +1 -0
  84. package/lib/node/receipt-book.js +42 -0
  85. package/lib/node/receipt-book.js.map +1 -0
  86. package/lib/node/receipt-book.spec.d.ts +2 -0
  87. package/lib/node/receipt-book.spec.d.ts.map +1 -0
  88. package/lib/node/receipt-book.spec.js +39 -0
  89. package/lib/node/receipt-book.spec.js.map +1 -0
  90. package/lib/node/remote-ui-context.d.ts +64 -0
  91. package/lib/node/remote-ui-context.d.ts.map +1 -0
  92. package/lib/node/remote-ui-context.js +134 -0
  93. package/lib/node/remote-ui-context.js.map +1 -0
  94. package/lib/node/remote-ui-context.spec.d.ts +2 -0
  95. package/lib/node/remote-ui-context.spec.d.ts.map +1 -0
  96. package/lib/node/remote-ui-context.spec.js +62 -0
  97. package/lib/node/remote-ui-context.spec.js.map +1 -0
  98. package/lib/node/ta-access.d.ts +31 -0
  99. package/lib/node/ta-access.d.ts.map +1 -0
  100. package/lib/node/ta-access.js +110 -0
  101. package/lib/node/ta-access.js.map +1 -0
  102. package/lib/node/ta-access.spec.d.ts +2 -0
  103. package/lib/node/ta-access.spec.d.ts.map +1 -0
  104. package/lib/node/ta-access.spec.js +25 -0
  105. package/lib/node/ta-access.spec.js.map +1 -0
  106. package/lib/node/ta-errors.d.ts +12 -0
  107. package/lib/node/ta-errors.d.ts.map +1 -0
  108. package/lib/node/ta-errors.js +47 -0
  109. package/lib/node/ta-errors.js.map +1 -0
  110. package/lib/node/ta-event-util.d.ts +12 -0
  111. package/lib/node/ta-event-util.d.ts.map +1 -0
  112. package/lib/node/ta-event-util.js +23 -0
  113. package/lib/node/ta-event-util.js.map +1 -0
  114. package/lib/node/ta-event-util.spec.d.ts +2 -0
  115. package/lib/node/ta-event-util.spec.d.ts.map +1 -0
  116. package/lib/node/ta-event-util.spec.js +28 -0
  117. package/lib/node/ta-event-util.spec.js.map +1 -0
  118. package/lib/node/ta-server-impl.d.ts +51 -0
  119. package/lib/node/ta-server-impl.d.ts.map +1 -0
  120. package/lib/node/ta-server-impl.js +229 -0
  121. package/lib/node/ta-server-impl.js.map +1 -0
  122. package/lib/node/ta-session-factory.d.ts +33 -0
  123. package/lib/node/ta-session-factory.d.ts.map +1 -0
  124. package/lib/node/ta-session-factory.js +154 -0
  125. package/lib/node/ta-session-factory.js.map +1 -0
  126. package/lib/node/ta-session-registry.d.ts +21 -0
  127. package/lib/node/ta-session-registry.d.ts.map +1 -0
  128. package/lib/node/ta-session-registry.js +86 -0
  129. package/lib/node/ta-session-registry.js.map +1 -0
  130. package/lib/node/ta-session.d.ts +54 -0
  131. package/lib/node/ta-session.d.ts.map +1 -0
  132. package/lib/node/ta-session.js +161 -0
  133. package/lib/node/ta-session.js.map +1 -0
  134. package/package.json +80 -4
  135. package/src/node/client-channel.spec.ts +117 -0
  136. package/src/node/client-channel.ts +94 -0
  137. package/src/node/event-log.spec.ts +52 -0
  138. package/src/node/event-log.ts +59 -0
  139. package/src/node/host-protocol.ts +32 -0
  140. package/src/node/index.ts +13 -0
  141. package/src/node/local-exec-environment-factory.ts +9 -0
  142. package/src/node/module.ts +4 -0
  143. package/src/node/receipt-book.spec.ts +41 -0
  144. package/src/node/receipt-book.ts +40 -0
  145. package/src/node/remote-ui-context.spec.ts +68 -0
  146. package/src/node/remote-ui-context.ts +168 -0
  147. package/src/node/ta-access.spec.ts +27 -0
  148. package/src/node/ta-access.ts +98 -0
  149. package/src/node/ta-errors.ts +55 -0
  150. package/src/node/ta-event-util.spec.ts +29 -0
  151. package/src/node/ta-event-util.ts +23 -0
  152. package/src/node/ta-server-impl.ts +264 -0
  153. package/src/node/ta-session-factory.ts +156 -0
  154. package/src/node/ta-session-registry.ts +75 -0
  155. package/src/node/ta-session.ts +193 -0
@@ -0,0 +1,156 @@
1
+ import {
2
+ AgentExtension,
3
+ AgentTool,
4
+ AgentToolUtil,
5
+ CODING_AGENT_OPTIONS,
6
+ type CodingAgentOptions,
7
+ ModelRuntimeProvider,
8
+ type PiSdk,
9
+ PiSdkUtil,
10
+ } from '@celljs/ai-coding-agent';
11
+ import { Autowired, Component, Optional, Value } from '@celljs/core';
12
+ import { type ExecEnvironment, ExecEnvironmentFactory } from '@celljs/ta-exec';
13
+ import {
14
+ BrandExtension,
15
+ ExecExtension,
16
+ ExecMcpTransport,
17
+ type InlineExtension,
18
+ type McpServerEntry,
19
+ SessionLock,
20
+ SessionLockExtension,
21
+ TaExtensionUtil,
22
+ } from '@celljs/ta-harness';
23
+ import type { TaOpenSessionOptions } from '@celljs/ta-protocol';
24
+ import { TA_HOST_OPTIONS, type TaHostOptions, TaSessionFactory } from './host-protocol';
25
+ import { TaErrors } from './ta-errors';
26
+ import { TaSession } from './ta-session';
27
+
28
+ type ModelRuntime = import('@earendil-works/pi-coding-agent', { with: { 'resolution-mode': 'import' }}).ModelRuntime;
29
+ type SessionManager = import('@earendil-works/pi-coding-agent', { with: { 'resolution-mode': 'import' }}).SessionManager;
30
+ type Model = NonNullable<import('@earendil-works/pi-coding-agent', { with: { 'resolution-mode': 'import' }}).AgentSession['model']>;
31
+
32
+ /** Sets up pi for each session the way its command does, with one model runtime for all of them. */
33
+ @Component(TaSessionFactory)
34
+ export class DefaultTaSessionFactory implements TaSessionFactory {
35
+ @Value(TA_HOST_OPTIONS)
36
+ protected readonly options: TaHostOptions;
37
+
38
+ @Value(CODING_AGENT_OPTIONS)
39
+ protected readonly codingAgentOptions?: CodingAgentOptions;
40
+
41
+ @Autowired(ModelRuntimeProvider)
42
+ protected readonly modelRuntimeProvider: ModelRuntimeProvider;
43
+
44
+ @Autowired(ExecEnvironmentFactory)
45
+ protected readonly environments: ExecEnvironmentFactory;
46
+
47
+ @Autowired(AgentExtension)
48
+ @Optional()
49
+ protected readonly extensions: AgentExtension[] = [];
50
+
51
+ @Autowired(AgentTool)
52
+ @Optional()
53
+ protected readonly tools: AgentTool[] = [];
54
+
55
+ async create(options: TaOpenSessionOptions, requestClose: (session: TaSession) => void): Promise<TaSession> {
56
+ if (options.clientTools?.length) {
57
+ throw TaErrors.invalidArgument('This version of ta serve does not run client tools yet.', 'Open the session without clientTools.');
58
+ }
59
+ const sdk = await PiSdkUtil.load();
60
+ const agentDir = this.codingAgentOptions?.agentDir ?? sdk.getAgentDir();
61
+ const modelRuntime = await this.modelRuntimeProvider.provide();
62
+ const sessionManager = this.openSessionManager(sdk, options);
63
+ const lock = new SessionLock();
64
+ const sessionFile = sessionManager.getSessionFile();
65
+ if (sessionFile && !lock.acquire(sessionFile)) {
66
+ throw TaErrors.sessionLocked(sessionFile);
67
+ }
68
+ try {
69
+ const model = options.model ? this.resolveModel(modelRuntime, options.model) : undefined;
70
+ const runtime = await sdk.createAgentSessionRuntime(
71
+ async ({ cwd, agentDir: dir, sessionManager: manager, sessionStartEvent }) => {
72
+ const settingsManager = sdk.SettingsManager.create(cwd, dir, { projectTrusted: this.isTrusted(sdk, cwd, dir) });
73
+ const services = await sdk.createAgentSessionServices({
74
+ cwd,
75
+ agentDir: dir,
76
+ settingsManager,
77
+ modelRuntime,
78
+ resourceLoaderOptions: { extensionFactories: this.extensionFactories(sdk, cwd, lock) },
79
+ });
80
+ const created = await sdk.createAgentSessionFromServices({
81
+ services,
82
+ sessionManager: manager,
83
+ sessionStartEvent,
84
+ model,
85
+ thinkingLevel: options.thinkingLevel,
86
+ customTools: (this.tools ?? []).map(AgentToolUtil.toToolDefinition),
87
+ });
88
+ return { ...created, services, diagnostics: services.diagnostics };
89
+ },
90
+ { cwd: options.cwd, agentDir, sessionManager },
91
+ );
92
+ const session = new TaSession({ runtime, lock, options: this.options, requestClose });
93
+ await session.start();
94
+ return session;
95
+ } catch (error) {
96
+ lock.releaseAll();
97
+ throw error;
98
+ }
99
+ }
100
+
101
+ protected openSessionManager(sdk: PiSdk, options: TaOpenSessionOptions): SessionManager {
102
+ if (!options.sessionFile) {
103
+ return sdk.SessionManager.create(options.cwd);
104
+ }
105
+ try {
106
+ return sdk.SessionManager.open(options.sessionFile);
107
+ } catch (error) {
108
+ throw TaErrors.invalidArgument(
109
+ `Cannot open the session ${options.sessionFile}: ${(error as Error).message}`,
110
+ 'Pass a session file that exists; listSessions shows the open ones.',
111
+ );
112
+ }
113
+ }
114
+
115
+ protected extensionFactories(sdk: PiSdk, cwd: string, lock: SessionLock): InlineExtension[] {
116
+ const environment = this.environments.create(cwd);
117
+ const builtIn = [new SessionLockExtension(lock), new BrandExtension(sdk), ...(environment.local ? [] : [new ExecExtension(environment, sdk)])];
118
+ return [
119
+ ...this.piExtensions(sdk, environment),
120
+ TaExtensionUtil.bundle(builtIn),
121
+ ...(this.extensions ?? []).map(extension => ({
122
+ name: extension.name ?? extension.constructor.name,
123
+ factory: (pi: Parameters<AgentExtension['register']>[0]) => extension.register(pi),
124
+ })),
125
+ ];
126
+ }
127
+
128
+ /**
129
+ * The built-in extensions pi's command loads (codemode, tool search, MCP), which its SDK leaves to
130
+ * the host. Flagged as pi flags them: an installed extension that registers the same tool or
131
+ * command replaces them. pi does not export its llama.cpp extension. MCP servers over stdio start
132
+ * in the execution environment, where the session's tools run.
133
+ */
134
+ protected piExtensions(sdk: PiSdk, environment: ExecEnvironment): InlineExtension[] {
135
+ const createTransport = environment.local ? undefined : (entry: McpServerEntry) => new ExecMcpTransport(environment, entry);
136
+ return [
137
+ { name: 'codemode', factory: sdk.createCodemodeExtension(), replaceable: true, builtin: true },
138
+ { name: 'tool-search', factory: sdk.createToolSearchExtension(), replaceable: true, builtin: true },
139
+ { name: 'mcp', factory: sdk.createMcpExtension({ createTransport }), replaceable: true, builtin: true },
140
+ ];
141
+ }
142
+
143
+ /** Project resources load only in a project the user has trusted, or one without any. */
144
+ protected isTrusted(sdk: PiSdk, cwd: string, agentDir: string): boolean {
145
+ return new sdk.ProjectTrustStore(agentDir).get(cwd) ?? !sdk.hasTrustRequiringProjectResources(cwd);
146
+ }
147
+
148
+ protected resolveModel(modelRuntime: ModelRuntime, ref: string): Model {
149
+ const index = ref.indexOf('/');
150
+ const model = index > 0 ? modelRuntime.getModel(ref.slice(0, index), ref.slice(index + 1)) : undefined;
151
+ if (!model) {
152
+ throw TaErrors.modelNotFound(ref);
153
+ }
154
+ return model;
155
+ }
156
+ }
@@ -0,0 +1,75 @@
1
+ import { Autowired, Component, Value } from '@celljs/core';
2
+ import type { RpcConnection } from '@celljs/rpc/lib/node';
3
+ import type { TaOpenSessionOptions } from '@celljs/ta-protocol';
4
+ import { ClientChannel } from './client-channel';
5
+ import { TA_HOST_OPTIONS, type TaHostOptions, TaSessionFactory, TaSessionRegistry } from './host-protocol';
6
+ import { TaErrors } from './ta-errors';
7
+ import type { TaSession } from './ta-session';
8
+
9
+ @Component(TaSessionRegistry)
10
+ export class DefaultTaSessionRegistry implements TaSessionRegistry {
11
+ @Value(TA_HOST_OPTIONS)
12
+ protected readonly options: TaHostOptions;
13
+
14
+ @Autowired(TaSessionFactory)
15
+ protected readonly factory: TaSessionFactory;
16
+
17
+ protected readonly sessions = new Map<string, TaSession>();
18
+ protected readonly channels = new WeakMap<RpcConnection, ClientChannel>();
19
+ /** Sessions being created count against the limit too. */
20
+ protected opening = 0;
21
+
22
+ async open(options: TaOpenSessionOptions): Promise<TaSession> {
23
+ if (this.sessions.size + this.opening >= this.options.maxSessions) {
24
+ throw TaErrors.tooManySessions(this.options.maxSessions);
25
+ }
26
+ this.opening++;
27
+ try {
28
+ const session = await this.factory.create(options, ended => void this.close(ended.id));
29
+ this.sessions.set(session.id, session);
30
+ return session;
31
+ } finally {
32
+ this.opening--;
33
+ }
34
+ }
35
+
36
+ require(sessionId: string): TaSession {
37
+ const session = this.sessions.get(sessionId);
38
+ if (!session) {
39
+ throw TaErrors.sessionNotFound(sessionId);
40
+ }
41
+ return session;
42
+ }
43
+
44
+ list(): TaSession[] {
45
+ return [...this.sessions.values()];
46
+ }
47
+
48
+ async close(sessionId: string): Promise<void> {
49
+ const session = this.sessions.get(sessionId);
50
+ if (session) {
51
+ this.sessions.delete(sessionId);
52
+ await session.close();
53
+ }
54
+ }
55
+
56
+ async closeAll(): Promise<void> {
57
+ await Promise.all([...this.sessions.keys()].map(id => this.close(id)));
58
+ }
59
+
60
+ /** The one channel of a connection; it leaves every session when the connection ends. */
61
+ channel(connection: RpcConnection): ClientChannel {
62
+ let channel = this.channels.get(connection);
63
+ if (!channel) {
64
+ const created = new ClientChannel(connection, this.options.clientBacklogBytes);
65
+ this.channels.set(connection, created);
66
+ connection.onClose(() => {
67
+ for (const session of this.list()) {
68
+ session.detach(created);
69
+ }
70
+ });
71
+ channel = created;
72
+ }
73
+ return channel;
74
+ }
75
+ }
@@ -0,0 +1,193 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import type { SessionLock } from '@celljs/ta-harness';
3
+ import type { RpcExtensionUIResponse, TaAttachResult, TaEvent, TaPromptInput, TaPromptReceipt, TaSessionInfo } from '@celljs/ta-protocol';
4
+ import type { ClientChannel } from './client-channel';
5
+ import { EventLog } from './event-log';
6
+ import type { TaHostOptions } from './host-protocol';
7
+ import { ReceiptBook } from './receipt-book';
8
+ import { RemoteUiContext } from './remote-ui-context';
9
+ import { TaEventUtil } from './ta-event-util';
10
+
11
+ type AgentSessionRuntime = import('@earendil-works/pi-coding-agent', { with: { 'resolution-mode': 'import' }}).AgentSessionRuntime;
12
+ type AgentSession = import('@earendil-works/pi-coding-agent', { with: { 'resolution-mode': 'import' }}).AgentSession;
13
+ type PromptDisposition = 'started' | 'queued' | 'handled';
14
+
15
+ export interface TaSessionContext {
16
+ runtime: AgentSessionRuntime;
17
+ lock: SessionLock;
18
+ options: TaHostOptions;
19
+ /** The session should end: it has been idle, or an extension asked. */
20
+ requestClose(session: TaSession): void;
21
+ }
22
+
23
+ /**
24
+ * One open session of `ta serve`: pi's runtime, its event log, and the clients attached to it. Its id
25
+ * stays the same while the runtime moves between conversations.
26
+ */
27
+ export class TaSession {
28
+ readonly id = randomUUID();
29
+ readonly createdAt = Date.now();
30
+ readonly ui: RemoteUiContext;
31
+ readonly runtime: AgentSessionRuntime;
32
+ protected readonly log: EventLog;
33
+ protected readonly receipts = new ReceiptBook();
34
+ protected readonly channels = new Set<ClientChannel>();
35
+ protected unsubscribe?: () => void;
36
+ protected idleTimer?: ReturnType<typeof setTimeout>;
37
+ protected started = false;
38
+
39
+ constructor(protected readonly context: TaSessionContext) {
40
+ this.runtime = context.runtime;
41
+ this.log = new EventLog(this.id, context.options.eventBufferBytes);
42
+ this.ui = new RemoteUiContext(event => this.publish(event));
43
+ }
44
+
45
+ get pi(): AgentSession {
46
+ return this.runtime.session;
47
+ }
48
+
49
+ async start(): Promise<void> {
50
+ this.runtime.setRebindSession(() => this.bind());
51
+ await this.bind();
52
+ this.started = true;
53
+ this.watchIdle();
54
+ }
55
+
56
+ info(): TaSessionInfo {
57
+ const { pi } = this;
58
+ // Without a model pi's agent holds a placeholder that no runtime knows.
59
+ const model = pi.model && pi.modelRuntime.getModel(pi.model.provider, pi.model.id);
60
+ return {
61
+ sessionId: this.id,
62
+ piSessionId: pi.sessionId,
63
+ cwd: this.runtime.cwd,
64
+ sessionFile: pi.sessionFile,
65
+ sessionName: pi.sessionName,
66
+ model: model ? `${model.provider}/${model.id}` : undefined,
67
+ isStreaming: pi.isStreaming,
68
+ messageCount: pi.messages.length,
69
+ attached: this.channels.size,
70
+ createdAt: this.createdAt,
71
+ };
72
+ }
73
+
74
+ attach(channel: ClientChannel, afterSeq?: number): TaAttachResult {
75
+ this.channels.add(channel);
76
+ this.watchIdle();
77
+ const { events, gap } = afterSeq === undefined ? { events: [], gap: false } : this.log.since(afterSeq);
78
+ return { info: this.info(), events, pendingUi: this.ui.pendingRequests, lastSeq: this.log.lastSeq, gap };
79
+ }
80
+
81
+ detach(channel: ClientChannel): void {
82
+ if (this.channels.delete(channel)) {
83
+ this.watchIdle();
84
+ }
85
+ }
86
+
87
+ respondUi(response: RpcExtensionUIResponse): boolean {
88
+ return this.ui.respond(response);
89
+ }
90
+
91
+ prompt(input: TaPromptInput): Promise<TaPromptReceipt> {
92
+ return this.accept(
93
+ input,
94
+ () =>
95
+ new Promise<PromptDisposition>((resolve, reject) => {
96
+ this.pi
97
+ .prompt(input.message, {
98
+ images: input.images,
99
+ streamingBehavior: input.streamingBehavior ?? 'followUp',
100
+ source: 'rpc',
101
+ preflightResult: resolve,
102
+ })
103
+ // After the preflight, failures of the run reach the clients as events.
104
+ .then(() => resolve('handled'), reject);
105
+ }),
106
+ );
107
+ }
108
+
109
+ steer(input: TaPromptInput): Promise<TaPromptReceipt> {
110
+ return this.accept(input, () => this.pi.steer(input.message, input.images, { source: 'rpc' }));
111
+ }
112
+
113
+ followUp(input: TaPromptInput): Promise<TaPromptReceipt> {
114
+ return this.accept(input, () => this.pi.followUp(input.message, input.images, { source: 'rpc' }));
115
+ }
116
+
117
+ async close(): Promise<void> {
118
+ clearTimeout(this.idleTimer);
119
+ this.ui.cancelAll();
120
+ this.publish({ type: 'session_closed' });
121
+ this.channels.clear();
122
+ this.unsubscribe?.();
123
+ if (this.pi.isStreaming) {
124
+ await this.pi.abort();
125
+ }
126
+ await this.runtime.dispose();
127
+ this.context.lock.releaseAll();
128
+ }
129
+
130
+ protected async accept(input: TaPromptInput, run: () => Promise<PromptDisposition>): Promise<TaPromptReceipt> {
131
+ const duplicate = this.receipts.take(input);
132
+ if (duplicate) {
133
+ return duplicate;
134
+ }
135
+ try {
136
+ const disposition = await run();
137
+ return { clientMessageId: input.clientMessageId, status: disposition === 'queued' ? 'queued' : 'accepted' };
138
+ } catch (error) {
139
+ this.receipts.forget(input.clientMessageId);
140
+ throw error;
141
+ }
142
+ }
143
+
144
+ /** Connects this object to the session the runtime has now: at the start and after each replacement. */
145
+ protected async bind(): Promise<void> {
146
+ this.unsubscribe?.();
147
+ const { pi, runtime } = this;
148
+ await pi.bindExtensions({
149
+ uiContext: this.ui,
150
+ mode: 'rpc',
151
+ commandContextActions: {
152
+ waitForIdle: () => pi.waitForIdle(),
153
+ newSession: options => runtime.newSession(options),
154
+ fork: async (entryId, options) => ({ cancelled: (await runtime.fork(entryId, options)).cancelled }),
155
+ navigateTree: async (targetId, options) => ({ cancelled: (await pi.navigateTree(targetId, options)).cancelled }),
156
+ switchSession: (sessionPath, options) => runtime.switchSession(sessionPath, options),
157
+ reload: () => pi.reload(),
158
+ },
159
+ shutdownHandler: () => this.context.requestClose(this),
160
+ onError: error => this.publish({ type: 'extension_error', extensionPath: error.extensionPath, event: error.event, error: error.error }),
161
+ });
162
+ this.unsubscribe = pi.subscribe(event => {
163
+ this.publish(TaEventUtil.toWire(event));
164
+ if (event.type === 'agent_settled') {
165
+ this.watchIdle();
166
+ }
167
+ });
168
+ if (this.started) {
169
+ this.publish({ type: 'session_replaced', info: this.info() });
170
+ }
171
+ }
172
+
173
+ protected publish(event: TaEvent): void {
174
+ const logged = this.log.append(event);
175
+ for (const channel of this.channels) {
176
+ channel.send(logged);
177
+ }
178
+ }
179
+
180
+ protected isIdle(): boolean {
181
+ return this.channels.size === 0 && !this.pi.isStreaming && this.ui.pendingRequests.length === 0;
182
+ }
183
+
184
+ /** One timer per session, armed only when nothing is attached: an idle server does no work. */
185
+ protected watchIdle(): void {
186
+ clearTimeout(this.idleTimer);
187
+ this.idleTimer = undefined;
188
+ if (this.isIdle()) {
189
+ this.idleTimer = setTimeout(() => this.isIdle() && this.context.requestClose(this), this.context.options.idleTimeoutMs);
190
+ this.idleTimer.unref();
191
+ }
192
+ }
193
+ }