@borgee/agents-host 0.2.2 → 0.2.28

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 (84) hide show
  1. package/README.md +184 -21
  2. package/dist/agents-host-supervisor.d.ts +7 -5
  3. package/dist/agents-host-supervisor.js +24 -4
  4. package/dist/agents-host.d.ts +114 -15
  5. package/dist/agents-host.js +2712 -141
  6. package/dist/chat/chat-control-plane.d.ts +13 -2
  7. package/dist/chat/sdk-chat-control-plane.d.ts +14 -3
  8. package/dist/chat/sdk-chat-control-plane.js +54 -2
  9. package/dist/cli-args.d.ts +46 -5
  10. package/dist/cli-args.js +313 -32
  11. package/dist/cli.d.ts +9 -0
  12. package/dist/cli.js +112 -5
  13. package/dist/compatibility-gates.d.ts +39 -0
  14. package/dist/compatibility-gates.js +131 -0
  15. package/dist/config.d.ts +1 -0
  16. package/dist/config.js +23 -5
  17. package/dist/connections-state-store.d.ts +81 -0
  18. package/dist/connections-state-store.js +228 -0
  19. package/dist/context/attention.d.ts +12 -0
  20. package/dist/context/attention.js +137 -0
  21. package/dist/context/collaboration-capabilities-diagnostics.d.ts +3 -0
  22. package/dist/context/collaboration-capabilities-diagnostics.js +18 -0
  23. package/dist/context/collaboration-outcome.d.ts +2 -0
  24. package/dist/context/collaboration-outcome.js +26 -0
  25. package/dist/context/injection.d.ts +134 -0
  26. package/dist/context/injection.js +355 -0
  27. package/dist/context/prompt.d.ts +4 -1
  28. package/dist/context/prompt.js +231 -1
  29. package/dist/context/task-thread-collaboration.d.ts +6 -0
  30. package/dist/context/task-thread-collaboration.js +31 -0
  31. package/dist/context/turn-preparation.d.ts +9 -0
  32. package/dist/context/turn-preparation.js +135 -0
  33. package/dist/debug.d.ts +44 -0
  34. package/dist/debug.js +135 -0
  35. package/dist/gateway/localhost-gateway.d.ts +52 -0
  36. package/dist/gateway/localhost-gateway.js +857 -0
  37. package/dist/index.js +7 -5
  38. package/dist/local-config.d.ts +4 -1
  39. package/dist/local-config.js +24 -7
  40. package/dist/managed-daemon-log.d.ts +34 -0
  41. package/dist/managed-daemon-log.js +261 -0
  42. package/dist/managed-daemon.d.ts +220 -0
  43. package/dist/managed-daemon.js +1601 -0
  44. package/dist/policy/authorization-audit.d.ts +63 -0
  45. package/dist/policy/authorization-audit.js +94 -0
  46. package/dist/policy/copilot-permission.d.ts +15 -0
  47. package/dist/policy/copilot-permission.js +193 -0
  48. package/dist/policy/gateway-authorization.d.ts +42 -0
  49. package/dist/policy/gateway-authorization.js +162 -0
  50. package/dist/providers/awaiting-user.d.ts +12 -0
  51. package/dist/providers/awaiting-user.js +192 -0
  52. package/dist/providers/claude/adapter.d.ts +3 -1
  53. package/dist/providers/claude/adapter.js +8 -12
  54. package/dist/providers/claude/cli-client.d.ts +12 -5
  55. package/dist/providers/claude/cli-client.js +184 -37
  56. package/dist/providers/claude/session-store.d.ts +1 -0
  57. package/dist/providers/codex/adapter.d.ts +11 -0
  58. package/dist/providers/codex/adapter.js +19 -0
  59. package/dist/providers/codex/cli-client.d.ts +103 -0
  60. package/dist/providers/codex/cli-client.js +1133 -0
  61. package/dist/providers/codex/project-doc.d.ts +3 -0
  62. package/dist/providers/codex/project-doc.js +90 -0
  63. package/dist/providers/codex/session-store.d.ts +38 -0
  64. package/dist/providers/codex/session-store.js +150 -0
  65. package/dist/providers/copilot/adapter.d.ts +3 -1
  66. package/dist/providers/copilot/adapter.js +8 -12
  67. package/dist/providers/copilot/cli-client.d.ts +20 -2
  68. package/dist/providers/copilot/cli-client.js +251 -71
  69. package/dist/providers/copilot/session-store.d.ts +1 -0
  70. package/dist/providers/create-provider.d.ts +11 -2
  71. package/dist/providers/create-provider.js +131 -12
  72. package/dist/run.d.ts +1 -0
  73. package/dist/run.js +5 -2
  74. package/dist/state-paths.d.ts +14 -1
  75. package/dist/state-paths.js +87 -3
  76. package/dist/task-thread-resolution.d.ts +10 -0
  77. package/dist/task-thread-resolution.js +48 -0
  78. package/dist/types.d.ts +267 -1
  79. package/dist/visible-mentions.d.ts +3 -0
  80. package/dist/visible-mentions.js +15 -0
  81. package/package.json +19 -17
  82. package/skills/borgee-agent/SKILL.md +33 -0
  83. package/skills/borgee-agent/borgee-agent.mjs +473 -0
  84. package/skills/borgee-agent/borgee-agent.py +409 -0
@@ -0,0 +1,355 @@
1
+ import { promises as fs } from 'node:fs';
2
+ import { fileURLToPath } from 'node:url';
3
+ import { dirname, join, resolve } from 'node:path';
4
+ const CHANNEL_CONTEXT_ROOT_DIRNAME = 'channel-context';
5
+ const CHANNEL_CONTEXT_PAYLOAD_FILENAME = 'context.json';
6
+ const CHANNEL_CONTEXT_GATEWAY_AUTH_FILENAME = '.localhost-gateway-auth.json';
7
+ const TASK_WORKSPACE_ROOT_DIRNAME = '.borgee-task-workspaces';
8
+ export class ChannelContextPreparationError extends Error {
9
+ partialContext;
10
+ constructor(message, partialContext, options) {
11
+ super(message, options);
12
+ this.partialContext = partialContext;
13
+ this.name = 'ChannelContextPreparationError';
14
+ }
15
+ }
16
+ const DEFAULT_FILE_SYSTEM = {
17
+ async mkdir(path, options) {
18
+ await fs.mkdir(path, options);
19
+ },
20
+ async readdir(path) {
21
+ return await fs.readdir(path);
22
+ },
23
+ async readFile(path, options) {
24
+ return await fs.readFile(path, options);
25
+ },
26
+ async writeFile(path, data, options) {
27
+ await fs.writeFile(path, data, options);
28
+ },
29
+ async unlink(path) {
30
+ await fs.unlink(path);
31
+ },
32
+ async access(path) {
33
+ await fs.access(path);
34
+ },
35
+ };
36
+ const BORGEE_AGENT_SKILL_DIRNAME = 'borgee-agent';
37
+ const TASK_ASSIGNMENT_PREAMBLE_PATTERN = /^This is a task assignment \(task_id: (.+)\)\. The work belongs to this thread\b/u;
38
+ function toSkillRuntimePayload(skillRuntime) {
39
+ if (!skillRuntime) {
40
+ return undefined;
41
+ }
42
+ return {
43
+ skillDirectoryPath: skillRuntime.skillDirectoryPath,
44
+ nodeCliPath: skillRuntime.nodeCliPath,
45
+ pythonCliPath: skillRuntime.pythonCliPath,
46
+ };
47
+ }
48
+ function buildLocalhostGatewayAuthPayload(channelId, localhostGateway) {
49
+ if (!localhostGateway) {
50
+ return undefined;
51
+ }
52
+ return {
53
+ schemaVersion: 1,
54
+ channelId,
55
+ localhostGateway: {
56
+ token: localhostGateway.token,
57
+ },
58
+ };
59
+ }
60
+ function buildChannelContextPayload(channelId, collaborationOutcome, attentionSnapshot, taskThreadCollaborationContract, collaborationCapabilities, missedCollaborationDiagnostic, skillRuntime, localhostGateway, options) {
61
+ return {
62
+ schemaVersion: 1,
63
+ channelId,
64
+ ...(collaborationOutcome ? { collaborationOutcome } : {}),
65
+ ...(attentionSnapshot ? { attentionSnapshot } : {}),
66
+ ...(taskThreadCollaborationContract ? { taskThreadCollaborationContract } : {}),
67
+ ...(collaborationCapabilities ? { collaborationCapabilities } : {}),
68
+ ...(missedCollaborationDiagnostic ? { missedCollaborationDiagnostic } : {}),
69
+ ...(skillRuntime ? { skillRuntime: toSkillRuntimePayload(skillRuntime) } : {}),
70
+ ...(localhostGateway ? { localhostGateway } : {}),
71
+ ...(options?.taskAssignmentContext ? { taskAssignmentContext: options.taskAssignmentContext } : {}),
72
+ ...(options?.taskWorkspace ? { taskWorkspace: options.taskWorkspace } : {}),
73
+ };
74
+ }
75
+ function isRecord(value) {
76
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
77
+ }
78
+ function canRoundTripThroughUriComponentEncoding(value) {
79
+ try {
80
+ return decodeURIComponent(encodeURIComponent(value)) === value;
81
+ }
82
+ catch (error) {
83
+ if (error instanceof URIError) {
84
+ return false;
85
+ }
86
+ throw error;
87
+ }
88
+ }
89
+ function isUsableTaskId(value) {
90
+ return value.length > 0
91
+ && !/[\u0000-\u001f\u007f\s]/u.test(value)
92
+ && canRoundTripThroughUriComponentEncoding(value);
93
+ }
94
+ function sanitizeTaskAssignmentContext(value) {
95
+ if (!isRecord(value) || value.active !== true) {
96
+ return undefined;
97
+ }
98
+ const currentTaskId = typeof value.currentTaskId === 'string'
99
+ ? value.currentTaskId.trim()
100
+ : '';
101
+ return currentTaskId && isUsableTaskId(currentTaskId)
102
+ ? { active: true, currentTaskId }
103
+ : { active: true };
104
+ }
105
+ export function extractTaskIdFromTaskAssignmentContent(incomingContent) {
106
+ if (typeof incomingContent !== 'string') {
107
+ return undefined;
108
+ }
109
+ const currentTaskId = incomingContent.match(TASK_ASSIGNMENT_PREAMBLE_PATTERN)?.[1]?.trim();
110
+ return currentTaskId && isUsableTaskId(currentTaskId)
111
+ ? currentTaskId
112
+ : undefined;
113
+ }
114
+ function buildTaskAssignmentContextForTurn(options, existingContext) {
115
+ if (options?.incomingMessageType === 'task_assignment') {
116
+ const currentTaskId = extractTaskIdFromTaskAssignmentContent(options.incomingContent);
117
+ return currentTaskId ? { active: true, currentTaskId } : { active: true };
118
+ }
119
+ return existingContext;
120
+ }
121
+ async function readExistingTaskAssignmentContext(payloadPath, fileSystem) {
122
+ try {
123
+ const raw = await fileSystem.readFile(payloadPath, { encoding: 'utf8' });
124
+ const payload = JSON.parse(raw);
125
+ return sanitizeTaskAssignmentContext(payload.taskAssignmentContext);
126
+ }
127
+ catch {
128
+ return undefined;
129
+ }
130
+ }
131
+ export function encodeChannelPathSegment(channelId) {
132
+ const encoded = Buffer.from(channelId, 'utf8').toString('hex');
133
+ return encoded.length > 0 ? encoded : 'empty';
134
+ }
135
+ export function resolveChannelContextDirectory(stateRootDir, channelId) {
136
+ return resolve(stateRootDir, CHANNEL_CONTEXT_ROOT_DIRNAME, encodeChannelPathSegment(channelId));
137
+ }
138
+ export function resolveChannelContextPayloadPath(stateRootDir, channelId) {
139
+ return join(resolveChannelContextDirectory(stateRootDir, channelId), CHANNEL_CONTEXT_PAYLOAD_FILENAME);
140
+ }
141
+ export function resolveTaskWorkspaceRootDirectory(startupWorkspaceRootDir) {
142
+ return join(resolve(startupWorkspaceRootDir), TASK_WORKSPACE_ROOT_DIRNAME);
143
+ }
144
+ export function resolveTaskWorkspaceDirectory(startupWorkspaceRootDir, channelId, taskId) {
145
+ return join(resolveTaskWorkspaceRootDirectory(startupWorkspaceRootDir), encodeChannelPathSegment(channelId), encodeChannelPathSegment(taskId));
146
+ }
147
+ export function resolveChannelContextGatewayAuthPath(stateRootDir, channelId, turnExecutionId) {
148
+ const filename = turnExecutionId
149
+ ? `.localhost-gateway-auth.${Buffer.from(turnExecutionId, 'utf8').toString('hex')}.json`
150
+ : CHANNEL_CONTEXT_GATEWAY_AUTH_FILENAME;
151
+ return join(resolveChannelContextDirectory(stateRootDir, channelId), filename);
152
+ }
153
+ export function resolveGatewayAuthPathFromPayloadPath(payloadPath) {
154
+ return join(dirname(payloadPath), CHANNEL_CONTEXT_GATEWAY_AUTH_FILENAME);
155
+ }
156
+ const LEGACY_TURN_SCOPED_GATEWAY_AUTH_BASENAME_PREFIX = '.localhost-gateway-auth.';
157
+ async function pruneLegacyGatewayAuthSidecars(fileSystem, directoryPath) {
158
+ let entries;
159
+ try {
160
+ entries = await fileSystem.readdir(directoryPath);
161
+ }
162
+ catch (error) {
163
+ const code = typeof error === 'object' && error && 'code' in error ? error.code : undefined;
164
+ if (code === 'ENOENT') {
165
+ return;
166
+ }
167
+ throw error;
168
+ }
169
+ await Promise.all(entries
170
+ .filter((entry) => entry.startsWith(LEGACY_TURN_SCOPED_GATEWAY_AUTH_BASENAME_PREFIX)
171
+ && entry.endsWith('.json'))
172
+ .map(async (entry) => {
173
+ await fileSystem.unlink(join(directoryPath, entry)).catch((error) => {
174
+ if (error.code !== 'ENOENT') {
175
+ throw error;
176
+ }
177
+ });
178
+ }));
179
+ }
180
+ async function resolvePackageRootFromModuleUrl(moduleUrl, fileSystem = DEFAULT_FILE_SYSTEM) {
181
+ let currentPath = dirname(fileURLToPath(moduleUrl));
182
+ for (;;) {
183
+ try {
184
+ await fileSystem.access(join(currentPath, 'package.json'));
185
+ return currentPath;
186
+ }
187
+ catch { }
188
+ const parentPath = resolve(currentPath, '..');
189
+ if (parentPath === currentPath) {
190
+ throw new Error(`Unable to resolve agents-host package root from ${moduleUrl}`);
191
+ }
192
+ currentPath = parentPath;
193
+ }
194
+ }
195
+ export async function resolveBorgeeAgentSkillRuntimeAssets(moduleUrl, fileSystem = DEFAULT_FILE_SYSTEM) {
196
+ const packageRootPath = await resolvePackageRootFromModuleUrl(moduleUrl, fileSystem);
197
+ const skillDirectoryPath = join(packageRootPath, 'skills', BORGEE_AGENT_SKILL_DIRNAME);
198
+ const skillMarkdownPath = join(skillDirectoryPath, 'SKILL.md');
199
+ const nodeCliPath = join(skillDirectoryPath, 'borgee-agent.mjs');
200
+ const pythonCliPath = join(skillDirectoryPath, 'borgee-agent.py');
201
+ await Promise.all([
202
+ fileSystem.access(skillDirectoryPath),
203
+ fileSystem.access(skillMarkdownPath),
204
+ fileSystem.access(nodeCliPath),
205
+ fileSystem.access(pythonCliPath),
206
+ ]);
207
+ return {
208
+ skillDirectoryPath,
209
+ skillMarkdownPath,
210
+ nodeCliPath,
211
+ pythonCliPath,
212
+ };
213
+ }
214
+ class PackageSkillAssetResolver {
215
+ moduleUrl;
216
+ fileSystem;
217
+ resolutionPromise = null;
218
+ constructor(moduleUrl, fileSystem = DEFAULT_FILE_SYSTEM) {
219
+ this.moduleUrl = moduleUrl;
220
+ this.fileSystem = fileSystem;
221
+ }
222
+ resolve() {
223
+ this.resolutionPromise ??= resolveBorgeeAgentSkillRuntimeAssets(this.moduleUrl, this.fileSystem);
224
+ return this.resolutionPromise;
225
+ }
226
+ }
227
+ export class FileChannelContextStore {
228
+ stateRootDir;
229
+ fileSystem;
230
+ skillRuntimeEnabled;
231
+ skillAssetResolver;
232
+ localhostGateway;
233
+ startupWorkspaceRootDir;
234
+ constructor(stateRootDir, options = {}) {
235
+ this.stateRootDir = stateRootDir;
236
+ this.fileSystem = options.fileSystem ?? DEFAULT_FILE_SYSTEM;
237
+ this.skillRuntimeEnabled = options.skillRuntimeEnabled ?? false;
238
+ this.skillAssetResolver = options.skillAssetResolver ?? new PackageSkillAssetResolver(import.meta.url, this.fileSystem);
239
+ this.localhostGateway = options.localhostGateway;
240
+ this.startupWorkspaceRootDir = resolve(options.taskWorkspaceRootDir ?? process.cwd());
241
+ }
242
+ async prepare(inputOrChannelId, options) {
243
+ const input = typeof inputOrChannelId === 'string'
244
+ ? { channelId: inputOrChannelId, ...options }
245
+ : inputOrChannelId;
246
+ const turnMode = input.collaboration?.turnMode ?? 'ordinary';
247
+ const collaborationCommandsEnabled = input.collaboration?.enabled === true && input.collaboration.sendRoutesAllowed === true;
248
+ const collaborationRoutesAllowedForTurnMode = turnMode === 'ordinary';
249
+ const auxiliaryCollaborationEnabled = collaborationCommandsEnabled && collaborationRoutesAllowedForTurnMode;
250
+ const directoryPath = resolveChannelContextDirectory(this.stateRootDir, input.channelId);
251
+ const payloadPath = resolveChannelContextPayloadPath(this.stateRootDir, input.channelId);
252
+ const gatewayAuthPath = resolveGatewayAuthPathFromPayloadPath(payloadPath);
253
+ const existingTaskAssignmentContext = await readExistingTaskAssignmentContext(payloadPath, this.fileSystem);
254
+ const skillRuntime = this.skillRuntimeEnabled
255
+ ? await this.resolveSkillRuntimeBestEffort()
256
+ : undefined;
257
+ const issuedLocalhostGateway = skillRuntime
258
+ ? this.localhostGateway?.resolveBootstrap(input.channelId, {
259
+ collaboration: auxiliaryCollaborationEnabled && input.collaboration?.turnExecutionId
260
+ ? {
261
+ enabled: true,
262
+ turnExecutionId: input.collaboration.turnExecutionId,
263
+ }
264
+ : undefined,
265
+ })
266
+ : undefined;
267
+ const localhostGateway = issuedLocalhostGateway
268
+ ? {
269
+ baseUrl: issuedLocalhostGateway.baseUrl,
270
+ ...(auxiliaryCollaborationEnabled
271
+ ? {
272
+ collaboration: {
273
+ enabled: true,
274
+ },
275
+ }
276
+ : {}),
277
+ }
278
+ : undefined;
279
+ const taskAssignmentContext = buildTaskAssignmentContextForTurn({
280
+ incomingMessageType: input.incomingMessageType,
281
+ incomingContent: input.incomingContent,
282
+ }, existingTaskAssignmentContext);
283
+ const taskWorkspace = taskAssignmentContext?.currentTaskId
284
+ ? {
285
+ currentTaskId: taskAssignmentContext.currentTaskId,
286
+ rootPath: resolveTaskWorkspaceDirectory(this.startupWorkspaceRootDir, input.channelId, taskAssignmentContext.currentTaskId),
287
+ }
288
+ : undefined;
289
+ const payload = buildChannelContextPayload(input.channelId, input.collaborationOutcome, input.attentionSnapshot, input.taskThreadCollaborationContract, input.collaborationCapabilities, input.missedCollaborationDiagnostic, skillRuntime, localhostGateway, taskAssignmentContext || taskWorkspace
290
+ ? {
291
+ ...(taskAssignmentContext ? { taskAssignmentContext } : {}),
292
+ ...(taskWorkspace ? { taskWorkspace } : {}),
293
+ }
294
+ : undefined);
295
+ const gatewayAuthPayload = buildLocalhostGatewayAuthPayload(input.channelId, issuedLocalhostGateway);
296
+ let taskWorkspaceMaterialized = false;
297
+ let payloadWritten = false;
298
+ let gatewayAuthWritten = false;
299
+ const preparedContext = {
300
+ directoryPath,
301
+ payload,
302
+ payloadPath,
303
+ gatewayAuthPath: gatewayAuthPayload ? gatewayAuthPath : undefined,
304
+ skillRuntime,
305
+ localhostGateway,
306
+ taskWorkspace,
307
+ };
308
+ try {
309
+ await this.fileSystem.mkdir(directoryPath, { recursive: true, mode: 0o700 });
310
+ if (taskWorkspace) {
311
+ await this.fileSystem.mkdir(taskWorkspace.rootPath, { recursive: true, mode: 0o700 });
312
+ taskWorkspaceMaterialized = true;
313
+ }
314
+ await pruneLegacyGatewayAuthSidecars(this.fileSystem, directoryPath);
315
+ await this.fileSystem.writeFile(payloadPath, `${JSON.stringify(payload, null, 2)}\n`, { encoding: 'utf8', mode: 0o600 });
316
+ payloadWritten = true;
317
+ if (gatewayAuthPayload) {
318
+ await this.fileSystem.writeFile(gatewayAuthPath, `${JSON.stringify(gatewayAuthPayload, null, 2)}\n`, { encoding: 'utf8', mode: 0o600 });
319
+ gatewayAuthWritten = true;
320
+ }
321
+ else {
322
+ await this.fileSystem.unlink(gatewayAuthPath).catch((error) => {
323
+ if (error.code !== 'ENOENT') {
324
+ throw error;
325
+ }
326
+ });
327
+ this.localhostGateway?.clearChannel(input.channelId);
328
+ }
329
+ if (issuedLocalhostGateway) {
330
+ this.localhostGateway?.publishPayload(input.channelId, payloadPath, payload);
331
+ }
332
+ return preparedContext;
333
+ }
334
+ catch (error) {
335
+ const partialContext = {
336
+ directoryPath,
337
+ payload,
338
+ payloadPath: payloadWritten ? payloadPath : undefined,
339
+ gatewayAuthPath: gatewayAuthWritten ? gatewayAuthPath : undefined,
340
+ skillRuntime: payloadWritten ? skillRuntime : undefined,
341
+ localhostGateway: payloadWritten ? localhostGateway : undefined,
342
+ taskWorkspace: taskWorkspaceMaterialized ? taskWorkspace : undefined,
343
+ };
344
+ throw new ChannelContextPreparationError('failed to persist channel context payload', partialContext, { cause: error });
345
+ }
346
+ }
347
+ async resolveSkillRuntimeBestEffort() {
348
+ try {
349
+ return await this.skillAssetResolver.resolve();
350
+ }
351
+ catch {
352
+ return undefined;
353
+ }
354
+ }
355
+ }
@@ -1,4 +1,4 @@
1
- import type { ProviderKind } from '../types.js';
1
+ import type { PreparedPromptContext, ProviderKind } from '../types.js';
2
2
  /**
3
3
  * Builds the per-turn prompt. Conversation memory is intentionally NOT
4
4
  * assembled here: each provider's CLI client resumes a native per-channel
@@ -12,4 +12,7 @@ export declare function buildPrompt(params: {
12
12
  channelId: string;
13
13
  incomingAuthorId: string;
14
14
  incomingContent: string;
15
+ incomingEventKind?: string;
16
+ incomingMessageType?: string;
17
+ promptContext?: PreparedPromptContext;
15
18
  }): string;
@@ -1,5 +1,210 @@
1
+ import { AWAITING_USER_CONTROL_PREFIX } from '../providers/awaiting-user.js';
2
+ import { buildAttentionSummaryLines } from './attention.js';
3
+ import { buildCollaborationCapabilityDeclarationSummaryLines, buildMissedCollaborationDiagnosticSummaryLines, } from './collaboration-capabilities-diagnostics.js';
4
+ import { buildCollaborationOutcomeSummaryLines } from './collaboration-outcome.js';
5
+ import { buildTaskThreadCollaborationSummaryLines } from './task-thread-collaboration.js';
1
6
  function providerLabel(provider) {
2
- return provider === 'copilot' ? 'GitHub Copilot' : 'Claude';
7
+ if (provider === 'copilot') {
8
+ return 'GitHub Copilot';
9
+ }
10
+ if (provider === 'codex') {
11
+ return 'Codex';
12
+ }
13
+ return 'Claude';
14
+ }
15
+ function buildSkillRuntimePromptLines(context) {
16
+ if (!context?.skillRuntime) {
17
+ return [];
18
+ }
19
+ return [
20
+ '',
21
+ 'Read-only local skill runtime bootstrap is available for this turn.',
22
+ `Channel context payload: ${context.channelContextPayloadPath}`,
23
+ `Skill guide: ${context.skillRuntime.skillMarkdownPath}`,
24
+ `Node CLI: node ${context.skillRuntime.nodeCliPath} --context ${context.channelContextPayloadPath} --print-bootstrap`,
25
+ `Python CLI: python3 ${context.skillRuntime.pythonCliPath} --context ${context.channelContextPayloadPath} --print-bootstrap`,
26
+ 'These CLIs are local-only, may only access the loopback gateway described below, must not mutate files or the local environment, and may only send auxiliary collaboration messages when that gateway surface is explicitly advertised below.',
27
+ ];
28
+ }
29
+ function buildLocalhostGatewayPromptLines(context) {
30
+ if (!context?.localhostGateway) {
31
+ return [];
32
+ }
33
+ if (!context.gatewayAuthPath) {
34
+ return [];
35
+ }
36
+ const lines = [
37
+ '',
38
+ 'A loopback-only localhost gateway is available for this turn.',
39
+ 'Use the packaged local CLI with the existing --context payload to access the documented gateway surface.',
40
+ `Gateway auth sidecar for this turn: ${context.gatewayAuthPath}`,
41
+ ];
42
+ const isTaskAssignmentThread = context.taskAssignmentContext?.active === true;
43
+ if (!context.skillRuntime) {
44
+ return lines;
45
+ }
46
+ lines.push('The read-only gateway commands listed in this prompt are already authorized for this turn and may be executed directly.', 'Do not ask the user for permission before using the read-only gateway commands listed below.', 'If the user asks about channel history, visible participants, or your current agent identity, run the relevant read command first and answer from its result instead of speculating about authorization.', `Node gateway checks: node ${context.skillRuntime.nodeCliPath} --context ${context.channelContextPayloadPath} --auth-path ${context.gatewayAuthPath} --health`, `Node channel bootstrap: node ${context.skillRuntime.nodeCliPath} --context ${context.channelContextPayloadPath} --auth-path ${context.gatewayAuthPath} --read-bootstrap`, `Node agent identity: node ${context.skillRuntime.nodeCliPath} --context ${context.channelContextPayloadPath} --auth-path ${context.gatewayAuthPath} --get-me`, `Node channel history: node ${context.skillRuntime.nodeCliPath} --context ${context.channelContextPayloadPath} --auth-path ${context.gatewayAuthPath} --read-history --limit 20`, `Python gateway checks: python3 ${context.skillRuntime.pythonCliPath} --context ${context.channelContextPayloadPath} --auth-path ${context.gatewayAuthPath} --health`, `Python channel bootstrap: python3 ${context.skillRuntime.pythonCliPath} --context ${context.channelContextPayloadPath} --auth-path ${context.gatewayAuthPath} --read-bootstrap`, `Python agent identity: python3 ${context.skillRuntime.pythonCliPath} --context ${context.channelContextPayloadPath} --auth-path ${context.gatewayAuthPath} --get-me`, `Python channel history: python3 ${context.skillRuntime.pythonCliPath} --context ${context.channelContextPayloadPath} --auth-path ${context.gatewayAuthPath} --read-history --limit 20`);
47
+ if (isTaskAssignmentThread) {
48
+ lines.push('Task-collection commands remain disabled inside this task thread; use the parent channel for create/list task operations.', `Node get current thread task: node ${context.skillRuntime.nodeCliPath} --context ${context.channelContextPayloadPath} --auth-path ${context.gatewayAuthPath} --get-task`, `Node update current thread task: node ${context.skillRuntime.nodeCliPath} --context ${context.channelContextPayloadPath} --auth-path ${context.gatewayAuthPath} --update-task [--status "<status>"] [--assignee-id "<assignee-id>"] [--title "<title>"]`, `Python get current thread task: python3 ${context.skillRuntime.pythonCliPath} --context ${context.channelContextPayloadPath} --auth-path ${context.gatewayAuthPath} --get-task`, `Python update current thread task: python3 ${context.skillRuntime.pythonCliPath} --context ${context.channelContextPayloadPath} --auth-path ${context.gatewayAuthPath} --update-task [--status "<status>"] [--assignee-id "<assignee-id>"] [--title "<title>"]`);
49
+ }
50
+ else {
51
+ lines.push(`Node create task: node ${context.skillRuntime.nodeCliPath} --context ${context.channelContextPayloadPath} --auth-path ${context.gatewayAuthPath} --create-task --title "<title>" [--description "<description>"] [--assignee-id "<assignee-id>"]`, `Node list tasks: node ${context.skillRuntime.nodeCliPath} --context ${context.channelContextPayloadPath} --auth-path ${context.gatewayAuthPath} --list-tasks`, `Node get task: node ${context.skillRuntime.nodeCliPath} --context ${context.channelContextPayloadPath} --auth-path ${context.gatewayAuthPath} --get-task --task-id "<task-id>"`, `Node update task: node ${context.skillRuntime.nodeCliPath} --context ${context.channelContextPayloadPath} --auth-path ${context.gatewayAuthPath} --update-task --task-id "<task-id>" [--status "<status>"] [--assignee-id "<assignee-id>"] [--title "<title>"]`, `Python create task: python3 ${context.skillRuntime.pythonCliPath} --context ${context.channelContextPayloadPath} --auth-path ${context.gatewayAuthPath} --create-task --title "<title>" [--description "<description>"] [--assignee-id "<assignee-id>"]`, `Python list tasks: python3 ${context.skillRuntime.pythonCliPath} --context ${context.channelContextPayloadPath} --auth-path ${context.gatewayAuthPath} --list-tasks`, `Python get task: python3 ${context.skillRuntime.pythonCliPath} --context ${context.channelContextPayloadPath} --auth-path ${context.gatewayAuthPath} --get-task --task-id "<task-id>"`, `Python update task: python3 ${context.skillRuntime.pythonCliPath} --context ${context.channelContextPayloadPath} --auth-path ${context.gatewayAuthPath} --update-task --task-id "<task-id>" [--status "<status>"] [--assignee-id "<assignee-id>"] [--title "<title>"]`);
52
+ }
53
+ if (context.localhostGateway.collaboration?.enabled &&
54
+ (context.collaborationTurnMode ?? 'ordinary') === 'ordinary') {
55
+ const turnExecutionArgument = context.collaborationTurnExecutionId
56
+ ? ` --turn-execution-id ${context.collaborationTurnExecutionId}`
57
+ : '';
58
+ lines.push('Auxiliary collaboration commands are available for this turn. Use them only for short targeted escalation, mention, or reply notices, never for the main final answer body.', 'When you need the host-private in-flight draft for this live collaboration turn, use the dedicated read-draft command rather than inspecting public channel messages.', 'When --list-users is listed below, it is a read-only command for this turn and may be executed directly without asking for permission.', 'When the user explicitly asks you to mention, ping, notify, or send a short note to another visible participant, use the dedicated send-mention command directly and include a visible <@targetId> token in the body.', 'If the user asks you to @ another agent now, send the short auxiliary mention first, then confirm what you sent.', 'If the user says "the other agent" and only one other visible agent is present, resolve that target from --list-users and then use --send-mention with that participant id.', 'If collaboration with another visible agent would help, use these auxiliary commands to send a short targeted mention or reply-thread note yourself rather than asking AgentsHost to orchestrate a special protocol.', `Node private draft snapshot: node ${context.skillRuntime.nodeCliPath} --context ${context.channelContextPayloadPath} --auth-path ${context.gatewayAuthPath}${turnExecutionArgument} --read-draft`, `Node user directory: node ${context.skillRuntime.nodeCliPath} --context ${context.channelContextPayloadPath} --auth-path ${context.gatewayAuthPath} --list-users`, `Node auxiliary mention: node ${context.skillRuntime.nodeCliPath} --context ${context.channelContextPayloadPath} --auth-path ${context.gatewayAuthPath}${turnExecutionArgument} --send-mention user-id --body "Need review from <@user-id>"`, `Node reply thread notice: node ${context.skillRuntime.nodeCliPath} --context ${context.channelContextPayloadPath} --auth-path ${context.gatewayAuthPath}${turnExecutionArgument} --send-message --body "Following up here" --reply-to message-id`, `Python private draft snapshot: python3 ${context.skillRuntime.pythonCliPath} --context ${context.channelContextPayloadPath} --auth-path ${context.gatewayAuthPath}${turnExecutionArgument} --read-draft`, `Python user directory: python3 ${context.skillRuntime.pythonCliPath} --context ${context.channelContextPayloadPath} --auth-path ${context.gatewayAuthPath} --list-users`, `Python auxiliary mention: python3 ${context.skillRuntime.pythonCliPath} --context ${context.channelContextPayloadPath} --auth-path ${context.gatewayAuthPath}${turnExecutionArgument} --send-mention user-id --body "Need review from <@user-id>"`, `Python reply thread notice: python3 ${context.skillRuntime.pythonCliPath} --context ${context.channelContextPayloadPath} --auth-path ${context.gatewayAuthPath}${turnExecutionArgument} --send-message --body "Following up here" --reply-to message-id`);
59
+ }
60
+ return lines;
61
+ }
62
+ function buildTaskAssignmentPromptLines(params) {
63
+ const isTaskAssignmentTurn = params.incomingMessageType?.trim() === 'task_assignment';
64
+ const taskAssignmentContext = params.promptContext?.taskAssignmentContext;
65
+ if (!isTaskAssignmentTurn && taskAssignmentContext?.active !== true) {
66
+ return [];
67
+ }
68
+ const lines = isTaskAssignmentTurn
69
+ ? [
70
+ 'This message is a task assignment.',
71
+ 'The assigned work belongs to this thread. Do the work here.',
72
+ ]
73
+ : [
74
+ 'This thread is continuing an existing task assignment.',
75
+ 'Keep the main work in this thread.',
76
+ ];
77
+ if (taskAssignmentContext?.currentTaskId) {
78
+ lines.push(`Current assigned task id: ${taskAssignmentContext.currentTaskId}.`);
79
+ lines.push('Inside this task thread, the packaged Node and Python CLIs may omit --task-id for --get-task and --update-task because the current task id is already persisted in the injected thread context.');
80
+ if (params.promptContext?.taskWorkspace) {
81
+ lines.push(`Task-scoped writable workspace root: ${params.promptContext.taskWorkspace.rootPath}.`);
82
+ lines.push('This writable workspace is local to agents-host for the current task thread. It does not imply that the target repository has already been checked out there.');
83
+ }
84
+ }
85
+ else if (taskAssignmentContext?.active === true) {
86
+ lines.push('No current task id is persisted in the injected thread context for this task thread.');
87
+ lines.push('Inside this task thread, shorthand --get-task/--update-task calls without --task-id use an agents-host local fallback that scans visible parent-channel tasks for this thread; pass --task-id explicitly if that fallback cannot resolve a unique task.');
88
+ }
89
+ lines.push('Set the task status to in_progress when you start.', 'When you finish, set the task status to in_review and return your normal final response in this thread.', 'Do not use an auxiliary message command for the main completion report; reserve it for intentional targeted escalation or cross-channel notification.', 'Do not use create/list task operations inside this task thread; those remain parent-channel operations.', 'Do not move the main work back to the parent channel.');
90
+ return lines;
91
+ }
92
+ function buildInboundMetadataLines(params) {
93
+ return [
94
+ `Incoming transport event kind: ${params.incomingEventKind?.trim() || 'message'}`,
95
+ `Incoming semantic message type: ${params.incomingMessageType?.trim() || 'default'}`,
96
+ ...(() => {
97
+ const lines = buildTaskThreadCollaborationSummaryLines(params.promptContext?.taskThreadCollaborationContract);
98
+ return lines.length > 0 ? ['', ...lines] : [];
99
+ })(),
100
+ ...buildTaskAssignmentPromptLines(params),
101
+ ];
102
+ }
103
+ function describeIdentity(identity) {
104
+ if (!identity) {
105
+ return null;
106
+ }
107
+ const name = identity.displayName?.trim();
108
+ const label = name && name.length > 0 ? `${name} (${identity.id})` : identity.id;
109
+ return `${label}, kind=${identity.kind}`;
110
+ }
111
+ function buildTurnControlPromptLines(context) {
112
+ const taskThreadAttentionAvailable = context?.taskAssignmentContext?.active === true
113
+ && typeof context.taskAssignmentContext.currentTaskId === 'string'
114
+ && context.taskAssignmentContext.currentTaskId.trim().length > 0;
115
+ const attentionLines = context?.attentionSnapshot
116
+ ? [
117
+ 'Attention controls are projection-only host hints. They do not bypass server-side mention policy or widen message delivery.',
118
+ `To follow ordinary delivered human messages in this channel, add "attentionUpdate":"follow-channel".`,
119
+ `To stop follow-based human wake for this channel, add "attentionUpdate":"unfollow-channel".`,
120
+ `To mute ordinary delivered human wake while keeping explicit mentions and task assignments untouched, add "attentionUpdate":"mute-channel".`,
121
+ `To set a durable channel-level attention hint, add "attentionUpdate":"claim-channel".`,
122
+ ...(taskThreadAttentionAvailable
123
+ ? [
124
+ `To set a durable task-thread attention hint, add "attentionUpdate":"claim-task-thread" only when this turn has active injected task-thread context with a usable currentTaskId.`,
125
+ `To clear a local claim without changing deliveryMode, add "attentionUpdate":"unclaim-channel" or "attentionUpdate":"unclaim-task-thread".`,
126
+ ]
127
+ : [
128
+ `To clear a local channel claim without changing deliveryMode, add "attentionUpdate":"unclaim-channel".`,
129
+ ]),
130
+ ]
131
+ : [];
132
+ const attentionOnlyLine = context?.attentionSnapshot
133
+ ? [
134
+ `For an attention-only reply, keep a non-empty visible body and append: ${AWAITING_USER_CONTROL_PREFIX}{"kind":"attention-only","attentionUpdate":"follow-channel"}`,
135
+ ]
136
+ : [];
137
+ if (!context) {
138
+ return [
139
+ `Only when you need host-local turn control, append exactly one final non-empty line starting with ${AWAITING_USER_CONTROL_PREFIX}.`,
140
+ `For ordinary blocked-on-human turns, use: ${AWAITING_USER_CONTROL_PREFIX}{"kind":"awaiting-user","question":"<short question>","reason":"<short reason>"}`,
141
+ ...attentionLines,
142
+ ...attentionOnlyLine,
143
+ 'Do not emit multiple control lines, and do not use a control footer for ordinary answers.',
144
+ ];
145
+ }
146
+ if (context.collaborationTurnMode === 'protocol-managed' && context.protocol) {
147
+ const selfIdentity = describeIdentity(context.grounding?.self);
148
+ const incomingIdentity = describeIdentity(context.grounding?.incomingAuthor);
149
+ const peerIdentity = describeIdentity(context.grounding?.peer);
150
+ return [
151
+ `Protocol-managed collaboration is already active for this turn. Your host-managed role is ${context.protocol.role}, and your target peer is ${context.protocol.targetPeerId}.`,
152
+ ...(selfIdentity ? [`Your self identity for this turn: ${selfIdentity}.`] : []),
153
+ ...(peerIdentity ? [`Your peer for this turn: ${peerIdentity}.`] : []),
154
+ ...(incomingIdentity ? [`The incoming author for this turn is ${incomingIdentity}.`] : []),
155
+ 'The host will deliver the visible protocol reply body for you; you only decide the body plus exactly one control footer.',
156
+ 'Do not use auxiliary collaboration send commands during this turn, even if other turns can use them.',
157
+ 'Do not attempt a localhost gateway message post during this turn.',
158
+ `When handing off to the named peer, use: ${AWAITING_USER_CONTROL_PREFIX}{"kind":"continue-to-peer"}`,
159
+ `When finishing locally, use: ${AWAITING_USER_CONTROL_PREFIX}{"kind":"conclude-locally"}`,
160
+ `If you are blocked on the human instead, use: ${AWAITING_USER_CONTROL_PREFIX}{"kind":"awaiting-user","question":"<short question>","reason":"<short reason>"}`,
161
+ ...(context.attentionSnapshot
162
+ ? ['You may add one attentionUpdate field to continue-to-peer, conclude-locally, or awaiting-user when you also need an attention change for this channel.']
163
+ : []),
164
+ ...attentionLines,
165
+ 'Do not emit multiple control lines, and do not use start-protocol while host-managed collaboration is already active.',
166
+ ];
167
+ }
168
+ if (context.collaborationTurnMode === 'silent-kickoff' && context.kickoff) {
169
+ const kickoff = context.kickoff;
170
+ const otherParticipantId = kickoff.participantIds.find((participantId) => participantId !== kickoff.issuerId);
171
+ const selfIdentity = describeIdentity(context.grounding?.self);
172
+ const incomingIdentity = describeIdentity(context.grounding?.incomingAuthor);
173
+ const peerIdentity = describeIdentity(context.grounding?.peer);
174
+ const participantSummary = context.grounding?.participants
175
+ ?.map((participant) => describeIdentity(participant))
176
+ .filter((participant) => participant != null)
177
+ .join('; ');
178
+ return [
179
+ `Silent protocol kickoff evaluation is active for anchor ${kickoff.anchorMessageId}. The issuer is ${kickoff.issuerId}${otherParticipantId ? ` and the other participant is ${otherParticipantId}` : ''}.`,
180
+ ...(context.grounding?.hostRecognizedKickoffCandidate
181
+ ? [
182
+ 'The host has already recognized this message as a structurally valid kickoff candidate and is asking you to decide whether host-managed collaboration should start.',
183
+ ]
184
+ : []),
185
+ ...(selfIdentity ? [`Your self identity for this decision: ${selfIdentity}.`] : []),
186
+ ...(peerIdentity ? [`Your peer candidate for this decision: ${peerIdentity}.`] : []),
187
+ ...(incomingIdentity
188
+ ? [`The incoming author for this decision is ${incomingIdentity}.`]
189
+ : []),
190
+ ...(participantSummary ? [`Visible kickoff participants: ${participantSummary}.`] : []),
191
+ 'This evaluation is read-only and silent: do not use auxiliary collaboration send commands, and do not draft a user-visible reply body for this turn.',
192
+ `If the anchor message is genuinely requesting host-managed collaboration between the named agents, use: ${AWAITING_USER_CONTROL_PREFIX}{"kind":"start-protocol","rounds":<positive integer>}`,
193
+ 'Do not combine start-protocol with any attentionUpdate field.',
194
+ 'If collaboration should not start, omit the control footer entirely.',
195
+ 'Do not emit multiple control lines.',
196
+ ];
197
+ }
198
+ return [
199
+ `Only when you need host-local turn control, append exactly one final non-empty line starting with ${AWAITING_USER_CONTROL_PREFIX}.`,
200
+ `For ordinary blocked-on-human turns, use: ${AWAITING_USER_CONTROL_PREFIX}{"kind":"awaiting-user","question":"<short question>","reason":"<short reason>"}`,
201
+ ...(context?.attentionSnapshot
202
+ ? ['You may add one attentionUpdate field to awaiting-user when you also need an attention change for this channel.']
203
+ : []),
204
+ ...attentionLines,
205
+ ...attentionOnlyLine,
206
+ 'Do not emit multiple control lines, and do not use a control footer for ordinary answers.',
207
+ ];
3
208
  }
4
209
  /**
5
210
  * Builds the per-turn prompt. Conversation memory is intentionally NOT
@@ -15,8 +220,33 @@ export function buildPrompt(params) {
15
220
  'You are replying inside a shared collaboration channel.',
16
221
  'Be concise, helpful, and honest about uncertainty.',
17
222
  'Do not claim to have performed actions you did not actually perform.',
223
+ 'Keep the visible reply text concise.',
224
+ ...buildTurnControlPromptLines(params.promptContext),
18
225
  `If the user asks who you are, what powers you, or which backend/provider you use, mention that you are currently running on ${providerLabel(params.provider)}.`,
19
226
  `Channel: ${params.channelId}`,
227
+ ...buildInboundMetadataLines({
228
+ incomingEventKind: params.incomingEventKind,
229
+ incomingMessageType: params.incomingMessageType,
230
+ promptContext: params.promptContext,
231
+ }),
232
+ ...(() => {
233
+ const lines = buildCollaborationOutcomeSummaryLines(params.promptContext?.collaborationOutcome);
234
+ return lines.length > 0 ? ['', ...lines] : [];
235
+ })(),
236
+ ...(() => {
237
+ const lines = buildAttentionSummaryLines(params.promptContext?.attentionSnapshot);
238
+ return lines.length > 0 ? ['', ...lines] : [];
239
+ })(),
240
+ ...(() => {
241
+ const lines = buildCollaborationCapabilityDeclarationSummaryLines(params.promptContext?.collaborationCapabilities);
242
+ return lines.length > 0 ? ['', ...lines] : [];
243
+ })(),
244
+ ...(() => {
245
+ const lines = buildMissedCollaborationDiagnosticSummaryLines(params.promptContext?.missedCollaborationDiagnostic);
246
+ return lines.length > 0 ? ['', ...lines] : [];
247
+ })(),
248
+ ...buildSkillRuntimePromptLines(params.promptContext),
249
+ ...buildLocalhostGatewayPromptLines(params.promptContext),
20
250
  '',
21
251
  `New message from ${params.incomingAuthorId}:`,
22
252
  params.incomingContent,
@@ -0,0 +1,6 @@
1
+ import type { TaskThreadCollaborationContract } from '../types.js';
2
+ export declare function projectTaskThreadCollaborationContract(params: {
3
+ incomingMessageType?: string;
4
+ taskThreadContextActive: boolean;
5
+ }): TaskThreadCollaborationContract | undefined;
6
+ export declare function buildTaskThreadCollaborationSummaryLines(contract: TaskThreadCollaborationContract | undefined): string[];
@@ -0,0 +1,31 @@
1
+ export function projectTaskThreadCollaborationContract(params) {
2
+ if (!params.taskThreadContextActive) {
3
+ return undefined;
4
+ }
5
+ const turnRole = params.incomingMessageType?.trim() === 'task_assignment'
6
+ ? 'assignment'
7
+ : 'continuation';
8
+ return {
9
+ source: 'host-projected',
10
+ turnRole,
11
+ taskThreadContextActive: true,
12
+ mainResult: 'ordinary-final-reply-in-thread',
13
+ auxiliaryRoute: 'optional-auxiliary-send-or-escalation-only',
14
+ checkIn: 'status-update-intent-only',
15
+ blockedWork: 'in-thread-disclosure-only',
16
+ };
17
+ }
18
+ export function buildTaskThreadCollaborationSummaryLines(contract) {
19
+ if (!contract) {
20
+ return [];
21
+ }
22
+ return [
23
+ 'Shared task-thread collaboration contract for this turn (projection only; not runtime-authoritative truth).',
24
+ `Thread role: ${contract.turnRole}`,
25
+ `Active task-thread context: ${contract.taskThreadContextActive ? 'yes' : 'no'}`,
26
+ 'Main task result: return the ordinary final reply in this task thread.',
27
+ 'Auxiliary send or escalation: optional auxiliary route only, never the main completion path.',
28
+ 'Check-in: status-update intent only; no timer, heartbeat, send-route, scheduler, receipt, or recovery authority is implied here.',
29
+ 'Blocked work: disclose the blocker in-thread through the existing in-thread reply path, if one exists; no blocked-state authority or extra control kind is implied here.',
30
+ ];
31
+ }