@borgee/agents-host 0.2.44 → 0.2.62

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 (65) hide show
  1. package/README.md +24 -27
  2. package/dist/agents-host.d.ts +27 -5
  3. package/dist/agents-host.js +266 -201
  4. package/dist/chat/chat-control-plane.d.ts +3 -0
  5. package/dist/chat/sdk-chat-control-plane.d.ts +4 -3
  6. package/dist/chat/sdk-chat-control-plane.js +3 -0
  7. package/dist/cli.js +1 -5
  8. package/dist/compatibility-gates.d.ts +4 -0
  9. package/dist/compatibility-gates.js +20 -1
  10. package/dist/config.d.ts +2 -0
  11. package/dist/config.js +21 -0
  12. package/dist/context/claude-file-brief.d.ts +2 -0
  13. package/dist/context/claude-file-brief.js +83 -0
  14. package/dist/context/compaction.d.ts +20 -0
  15. package/dist/context/compaction.js +59 -0
  16. package/dist/context/injection.d.ts +58 -7
  17. package/dist/context/injection.js +370 -36
  18. package/dist/context/main-session-delegation.d.ts +1 -1
  19. package/dist/context/projection-strategy.d.ts +24 -0
  20. package/dist/context/projection-strategy.js +90 -0
  21. package/dist/context/prompt.d.ts +16 -1
  22. package/dist/context/prompt.js +464 -26
  23. package/dist/context/resolved-workspace.d.ts +3 -0
  24. package/dist/context/resolved-workspace.js +106 -0
  25. package/dist/context/skill-manual.d.ts +1 -0
  26. package/dist/context/skill-manual.js +4 -1
  27. package/dist/context/turn-preparation.d.ts +8 -2
  28. package/dist/context/turn-preparation.js +64 -14
  29. package/dist/gateway/localhost-gateway.js +4 -5
  30. package/dist/local-config.js +11 -1
  31. package/dist/managed-daemon.js +127 -9
  32. package/dist/plugin-sdk.js +264 -364
  33. package/dist/plugin-sdk.js.map +4 -4
  34. package/dist/policy/copilot-permission.d.ts +1 -0
  35. package/dist/policy/copilot-permission.js +18 -0
  36. package/dist/policy/gateway-authorization.js +2 -2
  37. package/dist/progress-to-activity.d.ts +16 -0
  38. package/dist/progress-to-activity.js +24 -0
  39. package/dist/projection-strategy-values.d.ts +4 -0
  40. package/dist/projection-strategy-values.js +28 -0
  41. package/dist/providers/acp-progress-collector.d.ts +44 -0
  42. package/dist/providers/acp-progress-collector.js +130 -0
  43. package/dist/providers/awaiting-user.d.ts +2 -3
  44. package/dist/providers/awaiting-user.js +5 -7
  45. package/dist/providers/claude/activity-metadata.d.ts +14 -0
  46. package/dist/providers/claude/activity-metadata.js +81 -0
  47. package/dist/providers/claude/cli-client.d.ts +2 -3
  48. package/dist/providers/claude/cli-client.js +220 -120
  49. package/dist/providers/codex/cli-client.d.ts +2 -0
  50. package/dist/providers/codex/cli-client.js +28 -104
  51. package/dist/providers/codex/project-doc.js +12 -11
  52. package/dist/providers/copilot/cli-client.d.ts +1 -1
  53. package/dist/providers/copilot/cli-client.js +12 -86
  54. package/dist/providers/create-provider.d.ts +2 -0
  55. package/dist/providers/create-provider.js +22 -4
  56. package/dist/state-paths.d.ts +1 -1
  57. package/dist/state-paths.js +3 -3
  58. package/dist/task-thread-resolution.d.ts +3 -2
  59. package/dist/types.d.ts +143 -6
  60. package/package.json +2 -2
  61. package/skills/borgee-agent/SKILL.md +12 -4
  62. package/skills/borgee-agent/references/errors.md +2 -2
  63. package/skills/borgee-agent/references/task-properties.md +6 -2
  64. package/dist/durable-cursor-store.d.ts +0 -5
  65. package/dist/durable-cursor-store.js +0 -7
@@ -1,3 +1,4 @@
1
+ import type { ReportTurnActivityInput, TurnActivityReporter } from '../plugin-sdk.js';
1
2
  import type { ChannelSummary, ChannelHistoryEntry, ChannelMessageEvent, CreateTaskInput, DirectoryUser, MeResponseUser, PostMessageInput, PostedMessage, ReadChannelHistoryInput, Task, UpdateTaskInput } from '../types.js';
2
3
  export interface ChatControlPlane {
3
4
  connect(onMessage: (message: ChannelMessageEvent) => void): Promise<void>;
@@ -6,6 +7,8 @@ export interface ChatControlPlane {
6
7
  editMessage(messageId: string, content: string): Promise<void>;
7
8
  deleteMessage(messageId: string): Promise<void>;
8
9
  startTyping(channelId: string): () => void;
10
+ /** Opens one turn's report on the activity rail. Fire-and-forget: nothing recovers what it sends. */
11
+ reportTurnActivity(input: ReportTurnActivityInput): TurnActivityReporter;
9
12
  getMe(): Promise<MeResponseUser>;
10
13
  listUsers(): Promise<DirectoryUser[]>;
11
14
  listChannels(): Promise<ChannelSummary[]>;
@@ -1,9 +1,9 @@
1
- import { type BorgeePluginClient, type BorgeePluginOptions, type InboundMessageEvent } from '../plugin-sdk.js';
1
+ import { type BorgeePluginClient, type BorgeePluginOptions, type InboundMessageEvent, type ReportTurnActivityInput, type TurnActivityReporter } from '../plugin-sdk.js';
2
2
  import type { ChannelSummary, ChannelHistoryEntry, ChannelMessageEvent, CreateTaskInput, DirectoryUser, MeResponseUser, PostMessageInput, PostedMessage, ReadChannelHistoryInput, Task, UpdateTaskInput } from '../types.js';
3
3
  import type { ChatControlPlane } from './chat-control-plane.js';
4
- type PluginClientLike = Pick<BorgeePluginClient, 'agentId' | 'close' | 'connect' | 'createTask' | 'deleteMessage' | 'editMessage' | 'getMe' | 'getTask' | 'listChannels' | 'listTasks' | 'listUsers' | 'on' | 'readHistory' | 'sendMessage' | 'startTyping' | 'updateTask' | 'setTaskProperty' | 'deleteTaskProperty'>;
4
+ type PluginClientLike = Pick<BorgeePluginClient, 'agentId' | 'close' | 'connect' | 'createTask' | 'deleteMessage' | 'editMessage' | 'getMe' | 'getTask' | 'listChannels' | 'listTasks' | 'listUsers' | 'on' | 'readHistory' | 'reportTurnActivity' | 'sendMessage' | 'startTyping' | 'updateTask' | 'setTaskProperty' | 'deleteTaskProperty'>;
5
5
  type PluginClientFactory = (options: BorgeePluginOptions) => PluginClientLike;
6
- type SdkChatControlPlaneOptions = Pick<BorgeePluginOptions, 'cursorStore' | 'pluginId'>;
6
+ type SdkChatControlPlaneOptions = Pick<BorgeePluginOptions, 'pluginId'>;
7
7
  /**
8
8
  * Thin adapter over `@borgee/plugin-sdk` (the same BPP/`/ws/plugin` SDK used by
9
9
  * the OpenClaw plugin) that implements the minimal `ChatControlPlane` surface
@@ -22,6 +22,7 @@ export declare class SdkChatControlPlane implements ChatControlPlane {
22
22
  editMessage(messageId: string, content: string): Promise<void>;
23
23
  deleteMessage(messageId: string): Promise<void>;
24
24
  startTyping(channelId: string): () => void;
25
+ reportTurnActivity(input: ReportTurnActivityInput): TurnActivityReporter;
25
26
  getMe(): Promise<MeResponseUser>;
26
27
  listUsers(): Promise<DirectoryUser[]>;
27
28
  readChannelHistory(input: ReadChannelHistoryInput): Promise<ChannelHistoryEntry[]>;
@@ -65,6 +65,9 @@ export class SdkChatControlPlane {
65
65
  startTyping(channelId) {
66
66
  return this.client.startTyping(channelId);
67
67
  }
68
+ reportTurnActivity(input) {
69
+ return this.client.reportTurnActivity(input);
70
+ }
68
71
  async getMe() {
69
72
  if (this.me) {
70
73
  return this.me;
package/dist/cli.js CHANGED
@@ -1,6 +1,6 @@
1
1
  #!/usr/bin/env node
2
2
  import { realpathSync } from 'node:fs';
3
- import { dirname, resolve } from 'node:path';
3
+ import { resolve } from 'node:path';
4
4
  import { fileURLToPath } from 'node:url';
5
5
  import { assertNoUpdateArgs, CliUsageError, parseApplyManagedArgs, parseDaemonArgs, parseDescribeArgs, parseDescribeManagedArgs, parseCleanupManagedArgs, parseGenerateConfigArgs, parseLogArgs, parseManagedStartArgs, parsePrintLayoutArgs, parseStartArgs, parseValidateArgs, USAGE, } from './cli-args.js';
6
6
  import { resolveAgentsHostDebugMode } from './debug.js';
@@ -15,7 +15,6 @@ function formatErrorMessage(error) {
15
15
  }
16
16
  return String(error);
17
17
  }
18
- const TASK_WORKSPACE_ROOT_DIR_ENV = 'AGENTS_HOST_INTERNAL_TASK_WORKSPACE_ROOT_DIR';
19
18
  export async function dispatchCli(argv, deps = {}) {
20
19
  const [command, ...rest] = argv;
21
20
  const env = deps.env ?? process.env;
@@ -31,7 +30,6 @@ export async function dispatchCli(argv, deps = {}) {
31
30
  const applyManagedSpecImpl = deps.applyManagedSpec ?? applyManagedSpec;
32
31
  const startManagedDaemonImpl = deps.startManagedDaemon ??
33
32
  (async (rootPath, debug) => {
34
- env[TASK_WORKSPACE_ROOT_DIR_ENV] = rootPath;
35
33
  const daemon = new ManagedAgentsHostDaemon(rootPath, debug, {
36
34
  logPath: env.AGENTS_HOST_MANAGED_DAEMON_LOG_PATH,
37
35
  });
@@ -63,7 +61,6 @@ export async function dispatchCli(argv, deps = {}) {
63
61
  await runMainImpl({ debug });
64
62
  return;
65
63
  }
66
- env[TASK_WORKSPACE_ROOT_DIR_ENV] = dirname(resolve(parsed.configPath));
67
64
  await runMainImpl({ configPath: parsed.configPath, debug });
68
65
  return;
69
66
  }
@@ -167,7 +164,6 @@ export async function dispatchCli(argv, deps = {}) {
167
164
  }
168
165
  if (command === 'daemon') {
169
166
  const parsed = parseDaemonArgs(rest);
170
- env[TASK_WORKSPACE_ROOT_DIR_ENV] = parsed.rootPath;
171
167
  await startManagedDaemonImpl(parsed.rootPath, parsed.debug);
172
168
  return;
173
169
  }
@@ -1,3 +1,4 @@
1
+ import type { ProjectionStrategy } from './types.js';
1
2
  export declare const CLAUDE_PROVIDER_V2_COMPATIBILITY_GATE = "claude-provider-v2";
2
3
  export declare const COPILOT_PROVIDER_V2_COMPATIBILITY_GATE = "copilot-provider-v2";
3
4
  export declare const CODEX_PROVIDER_COMPATIBILITY_GATE = "codex-provider";
@@ -18,6 +19,7 @@ export declare const COMPATIBILITY_GATES_ENV = "AGENTS_HOST_INTERNAL_COMPATIBILI
18
19
  export declare const INTERNAL_DISABLED_COMPATIBILITY_GATES_ENV = "AGENTS_HOST_INTERNAL_DISABLED_COMPATIBILITY_GATES";
19
20
  export declare const INTERNAL_POLICY_MODE_ENV = "AGENTS_HOST_INTERNAL_POLICY_MODE";
20
21
  export declare const INTERNAL_PROVIDER_IMPLEMENTATIONS_ENV = "AGENTS_HOST_INTERNAL_PROVIDER_IMPLEMENTATIONS";
22
+ export declare const INTERNAL_CLAUDE_PROMPT_STRATEGY_ENV = "AGENTS_HOST_INTERNAL_CLAUDE_PROMPT_STRATEGY";
21
23
  export declare const MANAGED_RUNTIME_SETTINGS_SCHEMA_VERSION = 1;
22
24
  export type InternalPolicyMode = 'audit-only' | 'enforce';
23
25
  export type InternalProviderImplementationPath = 'v1' | 'v2';
@@ -28,8 +30,10 @@ export interface ManagedRuntimeSettingsSnapshot {
28
30
  compatibilityGates: string[];
29
31
  providerImplementationOverrides: string[];
30
32
  internalPolicyMode: InternalPolicyMode;
33
+ projectionStrategy: ProjectionStrategy;
31
34
  }
32
35
  export declare const DEFAULT_INTERNAL_COMPATIBILITY_GATES: readonly string[];
36
+ export declare function resolveInternalProjectionStrategy(env?: NodeJS.ProcessEnv): ProjectionStrategy;
33
37
  export declare function parseCompatibilityGates(rawValue: string | undefined): ReadonlySet<string>;
34
38
  export declare function resolveInternalCompatibilityGates(env?: NodeJS.ProcessEnv): ReadonlySet<string>;
35
39
  export declare function resolveDisabledDefaultCompatibilityGates(compatibilityGates: Iterable<string>): string[];
@@ -1,4 +1,5 @@
1
1
  import { createHash } from 'node:crypto';
2
+ import { DEFAULT_PROJECTION_STRATEGY, normalizeProjectionStrategy, } from './projection-strategy-values.js';
2
3
  export const CLAUDE_PROVIDER_V2_COMPATIBILITY_GATE = 'claude-provider-v2';
3
4
  export const COPILOT_PROVIDER_V2_COMPATIBILITY_GATE = 'copilot-provider-v2';
4
5
  export const CODEX_PROVIDER_COMPATIBILITY_GATE = 'codex-provider';
@@ -19,11 +20,14 @@ export const COMPATIBILITY_GATES_ENV = 'AGENTS_HOST_INTERNAL_COMPATIBILITY_GATES
19
20
  export const INTERNAL_DISABLED_COMPATIBILITY_GATES_ENV = 'AGENTS_HOST_INTERNAL_DISABLED_COMPATIBILITY_GATES';
20
21
  export const INTERNAL_POLICY_MODE_ENV = 'AGENTS_HOST_INTERNAL_POLICY_MODE';
21
22
  export const INTERNAL_PROVIDER_IMPLEMENTATIONS_ENV = 'AGENTS_HOST_INTERNAL_PROVIDER_IMPLEMENTATIONS';
23
+ export const INTERNAL_CLAUDE_PROMPT_STRATEGY_ENV = 'AGENTS_HOST_INTERNAL_CLAUDE_PROMPT_STRATEGY';
22
24
  export const MANAGED_RUNTIME_SETTINGS_SCHEMA_VERSION = 1;
23
25
  const VALID_PROVIDER_IMPLEMENTATION_ENTRIES = '"claude:v1", "claude:v2", "copilot:v1", or "copilot:v2"';
24
26
  export const DEFAULT_INTERNAL_COMPATIBILITY_GATES = Object.freeze([
27
+ ATTENTION_FOLLOW_SEMANTICS_COMPATIBILITY_GATE,
25
28
  COLLABORATION_CAPABILITIES_DIAGNOSTICS_COMPATIBILITY_GATE,
26
29
  COLLABORATION_OUTCOME_MODEL_COMPATIBILITY_GATE,
30
+ COLLABORATION_SKILL_FIRST_COMPATIBILITY_GATE,
27
31
  CONNECTIONS_STATE_LAYER_COMPATIBILITY_GATE,
28
32
  CONTEXT_INJECTION_COMPATIBILITY_GATE,
29
33
  CODEX_PROVIDER_COMPATIBILITY_GATE,
@@ -44,6 +48,17 @@ function sortUniqueStrings(values) {
44
48
  return [...new Set([...values].map((value) => value.trim()).filter((value) => value.length > 0))]
45
49
  .sort((left, right) => left.localeCompare(right));
46
50
  }
51
+ export function resolveInternalProjectionStrategy(env = process.env) {
52
+ const rawValue = env[INTERNAL_CLAUDE_PROMPT_STRATEGY_ENV]?.trim();
53
+ if (!rawValue || rawValue.length === 0) {
54
+ return DEFAULT_PROJECTION_STRATEGY;
55
+ }
56
+ const strategy = normalizeProjectionStrategy(rawValue);
57
+ if (strategy) {
58
+ return strategy;
59
+ }
60
+ throw new Error(`Invalid ${INTERNAL_CLAUDE_PROMPT_STRATEGY_ENV}: expected "session-brief", "turn-full", "message-only", or "turn-thin"`);
61
+ }
47
62
  function isInternalProviderImplementationPath(value) {
48
63
  return value === 'v1' || value === 'v2';
49
64
  }
@@ -160,10 +175,14 @@ export function resolveManagedRuntimeSettingsSnapshot(env = process.env) {
160
175
  compatibilityGates,
161
176
  providerImplementationOverrides: resolveManagedRuntimeProviderImplementationOverrides(env, compatibilityGates),
162
177
  internalPolicyMode: resolveInternalPolicyMode(compatibilityGates.includes(POLICY_AUDIT_ENFORCEMENT_COMPATIBILITY_GATE), env),
178
+ projectionStrategy: resolveInternalProjectionStrategy(env),
163
179
  };
164
180
  }
165
181
  export function serializeManagedRuntimeSettingsSnapshot(snapshot) {
166
- return JSON.stringify(snapshot);
182
+ return JSON.stringify({
183
+ ...snapshot,
184
+ claudePromptStrategy: snapshot.projectionStrategy,
185
+ });
167
186
  }
168
187
  export function createManagedRuntimeSettingsFingerprint(snapshot) {
169
188
  return createHash('sha256')
package/dist/config.d.ts CHANGED
@@ -3,6 +3,7 @@ export declare const MAX_TIMER_DELAY_MINUTES: number;
3
3
  export declare const DEFAULT_COPILOT_SESSION_TTL_MINUTES: number;
4
4
  export declare const PROVIDER_IDLE_SHUTDOWN_DISABLED_MINUTES = 0;
5
5
  export declare const DEFAULT_PROVIDER_IDLE_SHUTDOWN_MINUTES = 10;
6
+ export declare const DEFAULT_ALLOW_CROSS_AGENT_INDEPENDENT_WORKSPACE_HANDOFF = true;
6
7
  export declare const DEFAULT_CLAUDE_COMMAND = "claude-agent-acp";
7
8
  export declare const LEGACY_CLAUDE_COMMAND = "claude";
8
9
  export declare const LEGACY_CLAUDE_ONE_SHOT_ARGS: readonly ["--print", "--permission-mode", "bypassPermissions"];
@@ -13,6 +14,7 @@ export declare function parseArgs(value: string): string[];
13
14
  export declare function optionalStringArray(value: unknown, fieldName: string, sourceLabel: string): string[] | undefined;
14
15
  export declare function parseCopilotSessionTtlMinutesValue(value: unknown, sourceLabel: string): number;
15
16
  export declare function parseProviderIdleShutdownMinutesValue(value: unknown, sourceLabel: string): number;
17
+ export declare function parseBooleanValue(value: unknown, envName: string, sourceLabel: string): boolean;
16
18
  export declare function resolveProvider(rawValue: string, sourceLabel: string): ProviderKind;
17
19
  export declare function assertProviderCompatibility(provider: ProviderKind, sourceLabel: string, env?: NodeJS.ProcessEnv): void;
18
20
  export declare function isLegacyClaudeCompatibilityAlias(command: string, args: string[]): boolean;
package/dist/config.js CHANGED
@@ -6,6 +6,7 @@ export const MAX_TIMER_DELAY_MINUTES = MAX_TIMER_DELAY_MS / 60_000;
6
6
  export const DEFAULT_COPILOT_SESSION_TTL_MINUTES = 2 * 24 * 60;
7
7
  export const PROVIDER_IDLE_SHUTDOWN_DISABLED_MINUTES = 0;
8
8
  export const DEFAULT_PROVIDER_IDLE_SHUTDOWN_MINUTES = 10;
9
+ export const DEFAULT_ALLOW_CROSS_AGENT_INDEPENDENT_WORKSPACE_HANDOFF = true;
9
10
  export const DEFAULT_CLAUDE_COMMAND = 'claude-agent-acp';
10
11
  export const LEGACY_CLAUDE_COMMAND = 'claude';
11
12
  export const LEGACY_CLAUDE_ONE_SHOT_ARGS = ['--print', '--permission-mode', 'bypassPermissions'];
@@ -18,6 +19,7 @@ export const DEFAULT_PROVIDER_COMMAND_CONFIG = {
18
19
  copilotArgs: ['-s', '--no-color', '--allow-all-tools', '--output-format', 'text'],
19
20
  copilotSessionTtlMinutes: DEFAULT_COPILOT_SESSION_TTL_MINUTES,
20
21
  providerIdleShutdownMinutes: DEFAULT_PROVIDER_IDLE_SHUTDOWN_MINUTES,
22
+ allowCrossAgentIndependentWorkspaceHandoff: DEFAULT_ALLOW_CROSS_AGENT_INDEPENDENT_WORKSPACE_HANDOFF,
21
23
  };
22
24
  function requireEnv(name, env) {
23
25
  return requireNonEmptyString(env[name], `Missing required environment variable: ${name}`);
@@ -75,6 +77,19 @@ export function parseProviderIdleShutdownMinutesValue(value, sourceLabel) {
75
77
  }
76
78
  return parsed;
77
79
  }
80
+ export function parseBooleanValue(value, envName, sourceLabel) {
81
+ if (typeof value === 'boolean') {
82
+ return value;
83
+ }
84
+ const normalized = String(value).trim().toLowerCase();
85
+ if (normalized === 'true') {
86
+ return true;
87
+ }
88
+ if (normalized === 'false') {
89
+ return false;
90
+ }
91
+ throw new Error(`Invalid ${envName} in ${sourceLabel}: expected true or false`);
92
+ }
78
93
  export function resolveProvider(rawValue, sourceLabel) {
79
94
  const raw = rawValue.trim().toLowerCase();
80
95
  if (raw === 'claude' || raw === 'codex' || raw === 'copilot') {
@@ -134,6 +149,8 @@ export function resolveProviderCommandConfig(overrides = {}) {
134
149
  copilotSessionTtlMinutes: overrides.copilotSessionTtlMinutes ?? DEFAULT_PROVIDER_COMMAND_CONFIG.copilotSessionTtlMinutes,
135
150
  providerIdleShutdownMinutes: overrides.providerIdleShutdownMinutes
136
151
  ?? DEFAULT_PROVIDER_COMMAND_CONFIG.providerIdleShutdownMinutes,
152
+ allowCrossAgentIndependentWorkspaceHandoff: overrides.allowCrossAgentIndependentWorkspaceHandoff
153
+ ?? DEFAULT_PROVIDER_COMMAND_CONFIG.allowCrossAgentIndependentWorkspaceHandoff,
137
154
  };
138
155
  }
139
156
  export function loadConfigFromEnv(env = process.env) {
@@ -153,6 +170,10 @@ export function loadConfigFromEnv(env = process.env) {
153
170
  providerIdleShutdownMinutes: env.PROVIDER_IDLE_SHUTDOWN_MINUTES && env.PROVIDER_IDLE_SHUTDOWN_MINUTES.trim().length > 0
154
171
  ? parseProviderIdleShutdownMinutesValue(env.PROVIDER_IDLE_SHUTDOWN_MINUTES, 'environment variable PROVIDER_IDLE_SHUTDOWN_MINUTES')
155
172
  : DEFAULT_PROVIDER_COMMAND_CONFIG.providerIdleShutdownMinutes,
173
+ allowCrossAgentIndependentWorkspaceHandoff: env.ALLOW_CROSS_AGENT_INDEPENDENT_WORKSPACE_HANDOFF
174
+ && env.ALLOW_CROSS_AGENT_INDEPENDENT_WORKSPACE_HANDOFF.trim().length > 0
175
+ ? parseBooleanValue(env.ALLOW_CROSS_AGENT_INDEPENDENT_WORKSPACE_HANDOFF, 'ALLOW_CROSS_AGENT_INDEPENDENT_WORKSPACE_HANDOFF', 'environment variable ALLOW_CROSS_AGENT_INDEPENDENT_WORKSPACE_HANDOFF')
176
+ : DEFAULT_PROVIDER_COMMAND_CONFIG.allowCrossAgentIndependentWorkspaceHandoff,
156
177
  });
157
178
  assertProviderCommandCompatibility(provider, providerConfig, 'environment variables');
158
179
  return {
@@ -0,0 +1,2 @@
1
+ import type { PreparedPromptContext } from '../types.js';
2
+ export declare function buildClaudeFileBrief(context: PreparedPromptContext | undefined): string;
@@ -0,0 +1,83 @@
1
+ import { buildCollaborationCapabilityDeclarationSummaryLines, } from './collaboration-capabilities-diagnostics.js';
2
+ import { MAIN_SESSION_DELEGATION_LINES } from './main-session-delegation.js';
3
+ import { buildResolvedWorkspaceGuidanceLines } from './resolved-workspace.js';
4
+ import { buildSkillManualLines, buildSkillManualReadLine } from './skill-manual.js';
5
+ function buildStableSkillLines(context) {
6
+ if (!context?.skillRuntime) {
7
+ return [];
8
+ }
9
+ return context.gatewayCredentialPath
10
+ ? buildSkillManualLines(context.skillRuntime)
11
+ : [buildSkillManualReadLine(context.skillRuntime)];
12
+ }
13
+ function buildStableGatewayLines(context) {
14
+ if (!context?.localhostGateway || !context.gatewayCredentialPath) {
15
+ return [];
16
+ }
17
+ const lines = [`Gateway credential file: ${context.gatewayCredentialPath}`];
18
+ if (context.runtimeSurface?.task.currentThread === 'parent-channel') {
19
+ lines.push('This channel is a parent channel, not a task thread.', 'For parent-channel task operations, use the packaged borgee-agent task rail through this gateway credential file.', 'Do not invent a bare task or bare borgee command.');
20
+ if (context.runtimeSurface.task.currentTaskShorthand === 'requires-task-id') {
21
+ lines.push('In this parent channel, task get, task update, task history, and task property commands require an explicit task id.');
22
+ }
23
+ }
24
+ else if (context.runtimeSurface?.task.currentThread === 'task-assignment-thread') {
25
+ lines.push('This channel is an active task thread.', 'Task list and task create stay on the parent channel.', 'Keep the main work in this thread.', 'Return your normal final response in this thread, and do not move the main work back to the parent channel.');
26
+ if (context.taskAssignmentContext?.currentTaskId) {
27
+ lines.push(`Current assigned task id: ${context.taskAssignmentContext.currentTaskId}.`);
28
+ }
29
+ else if (context.taskAssignmentContext?.active === true) {
30
+ lines.push('No current task id is persisted in the injected thread context for this task thread.');
31
+ }
32
+ }
33
+ return lines;
34
+ }
35
+ function buildStableTaskThreadLines(context) {
36
+ if (context?.taskAssignmentContext?.active !== true) {
37
+ return [];
38
+ }
39
+ const lines = [
40
+ 'This session is an active task assignment thread.',
41
+ 'Keep the main work in this thread.',
42
+ 'Return your normal final response in this thread, and do not move the main work back to the parent channel.',
43
+ ];
44
+ if (context.taskAssignmentContext.currentTaskId) {
45
+ lines.push(`Current assigned task id: ${context.taskAssignmentContext.currentTaskId}.`);
46
+ }
47
+ else {
48
+ lines.push('No current task id is persisted in the injected thread context for this task thread.');
49
+ }
50
+ return lines;
51
+ }
52
+ export function buildClaudeFileBrief(context) {
53
+ const sessionDelegationLines = context?.skillRuntime ? [] : MAIN_SESSION_DELEGATION_LINES;
54
+ const lines = [
55
+ '# Borgee Claude runtime brief',
56
+ '',
57
+ 'This directory belongs to one Borgee Claude channel session hosted by agents-host.',
58
+ 'Keep visible replies concise, honest, and grounded in the current channel. Do not claim actions you did not actually perform.',
59
+ '',
60
+ ...sessionDelegationLines,
61
+ ...(() => {
62
+ const workspaceLines = buildResolvedWorkspaceGuidanceLines(context);
63
+ return workspaceLines.length > 0 ? ['', ...workspaceLines] : [];
64
+ })(),
65
+ ...(() => {
66
+ const capabilityLines = buildCollaborationCapabilityDeclarationSummaryLines(context?.collaborationCapabilities);
67
+ return capabilityLines.length > 0 ? ['', ...capabilityLines] : [];
68
+ })(),
69
+ ...(() => {
70
+ const taskThreadLines = buildStableTaskThreadLines(context);
71
+ return taskThreadLines.length > 0 ? ['', ...taskThreadLines] : [];
72
+ })(),
73
+ ...(() => {
74
+ const skillLines = buildStableSkillLines(context);
75
+ return skillLines.length > 0 ? ['', ...skillLines] : [];
76
+ })(),
77
+ ...(() => {
78
+ const gatewayLines = buildStableGatewayLines(context);
79
+ return gatewayLines.length > 0 ? ['', ...gatewayLines] : [];
80
+ })(),
81
+ ];
82
+ return `${lines.join('\n').trimEnd()}\n`;
83
+ }
@@ -0,0 +1,20 @@
1
+ import type { CompactionSnapshot, ProviderCompactionStage, ProviderKind } from '../types.js';
2
+ export declare function buildCompactionSnapshot(params: {
3
+ provider: ProviderKind;
4
+ stage: ProviderCompactionStage;
5
+ observedAt?: number;
6
+ turnExecutionId?: string;
7
+ usedTokens?: number;
8
+ contextWindowTokens?: number;
9
+ failureReason?: string;
10
+ }): CompactionSnapshot;
11
+ export declare function mergeCompactionSnapshot(current: CompactionSnapshot | undefined, update: {
12
+ provider: ProviderKind;
13
+ stage: ProviderCompactionStage;
14
+ observedAt?: number;
15
+ turnExecutionId?: string;
16
+ usedTokens?: number;
17
+ contextWindowTokens?: number;
18
+ failureReason?: string;
19
+ }): CompactionSnapshot;
20
+ export declare function parsePersistedCompactionSnapshot(raw: unknown): CompactionSnapshot | undefined;
@@ -0,0 +1,59 @@
1
+ function isRecord(value) {
2
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
3
+ }
4
+ function isProviderKind(value) {
5
+ return value === 'claude' || value === 'copilot' || value === 'codex';
6
+ }
7
+ function isCompactionStage(value) {
8
+ return value === 'started' || value === 'completed' || value === 'failed';
9
+ }
10
+ function isTerminalCompactionStage(value) {
11
+ return value === 'completed' || value === 'failed';
12
+ }
13
+ function normalizeFiniteNumber(value) {
14
+ return typeof value === 'number' && Number.isFinite(value) ? value : undefined;
15
+ }
16
+ function normalizeNonEmptyString(value) {
17
+ return typeof value === 'string' && value.trim().length > 0 ? value : undefined;
18
+ }
19
+ export function buildCompactionSnapshot(params) {
20
+ return {
21
+ source: 'host-observed',
22
+ provider: params.provider,
23
+ stage: params.stage,
24
+ observedAt: params.observedAt ?? Date.now(),
25
+ ...(params.turnExecutionId ? { turnExecutionId: params.turnExecutionId } : {}),
26
+ ...(params.usedTokens !== undefined ? { usedTokens: params.usedTokens } : {}),
27
+ ...(params.contextWindowTokens !== undefined
28
+ ? { contextWindowTokens: params.contextWindowTokens }
29
+ : {}),
30
+ ...(params.failureReason ? { failureReason: params.failureReason } : {}),
31
+ };
32
+ }
33
+ export function mergeCompactionSnapshot(current, update) {
34
+ const retainUsageFromCurrent = current?.stage === 'completed' && update.stage === 'completed';
35
+ return buildCompactionSnapshot({
36
+ provider: update.provider,
37
+ stage: update.stage,
38
+ observedAt: update.observedAt,
39
+ turnExecutionId: update.turnExecutionId,
40
+ usedTokens: update.usedTokens ?? (retainUsageFromCurrent ? current?.usedTokens : undefined),
41
+ contextWindowTokens: update.contextWindowTokens
42
+ ?? (retainUsageFromCurrent ? current?.contextWindowTokens : undefined),
43
+ failureReason: update.failureReason,
44
+ });
45
+ }
46
+ export function parsePersistedCompactionSnapshot(raw) {
47
+ if (!isRecord(raw) || !isProviderKind(raw.provider) || !isTerminalCompactionStage(raw.stage)) {
48
+ return undefined;
49
+ }
50
+ return buildCompactionSnapshot({
51
+ provider: raw.provider,
52
+ stage: raw.stage,
53
+ observedAt: normalizeFiniteNumber(raw.observedAt) ?? Date.now(),
54
+ turnExecutionId: normalizeNonEmptyString(raw.turnExecutionId),
55
+ usedTokens: normalizeFiniteNumber(raw.usedTokens),
56
+ contextWindowTokens: normalizeFiniteNumber(raw.contextWindowTokens),
57
+ failureReason: normalizeNonEmptyString(raw.failureReason),
58
+ });
59
+ }
@@ -1,4 +1,5 @@
1
- import type { AttentionSnapshot, CollaborationCapabilityDeclaration, CollaborationOutcomeSnapshot, LocalhostGatewayBootstrapMetadata, MissedCollaborationDiagnostic, ProviderCollaborationContext, SkillRuntimeBootstrapMetadata, TaskThreadCollaborationContract, TaskAssignmentThreadContext, TaskWorkspaceContext } from '../types.js';
1
+ import type { ChatControlPlane } from '../chat/chat-control-plane.js';
2
+ import type { AttentionSnapshot, ProjectionStrategy, CollaborationCapabilityDeclaration, CollaborationOutcomeSnapshot, CompactionSnapshot, LocalhostGatewayBootstrapMetadata, MissedCollaborationDiagnostic, ProviderKind, ProviderCollaborationContext, ResolvedWorkspaceContext, RuntimeSurface, SkillRuntimeBootstrapMetadata, TaskThreadCollaborationContract, TaskAssignmentThreadContext } from '../types.js';
2
3
  export interface SkillRuntimeBootstrapPayload {
3
4
  skillDirectoryPath: string;
4
5
  nodeCliPath: string;
@@ -7,24 +8,28 @@ export interface SkillRuntimeBootstrapPayload {
7
8
  export interface ChannelContextPayload {
8
9
  schemaVersion: 1;
9
10
  channelId: string;
11
+ runtimeSurface?: RuntimeSurface;
10
12
  collaborationOutcome?: CollaborationOutcomeSnapshot;
11
13
  attentionSnapshot?: AttentionSnapshot;
14
+ compactionSnapshot?: CompactionSnapshot;
12
15
  taskThreadCollaborationContract?: TaskThreadCollaborationContract;
13
16
  collaborationCapabilities?: CollaborationCapabilityDeclaration;
14
17
  missedCollaborationDiagnostic?: MissedCollaborationDiagnostic;
15
18
  skillRuntime?: SkillRuntimeBootstrapPayload;
16
19
  localhostGateway?: LocalhostGatewayBootstrapMetadata;
17
20
  taskAssignmentContext?: TaskAssignmentThreadContext;
18
- taskWorkspace?: TaskWorkspaceContext;
21
+ resolvedWorkspace?: ResolvedWorkspaceContext;
19
22
  }
20
23
  export interface PreparedChannelContext {
21
24
  directoryPath: string;
22
25
  payload: ChannelContextPayload;
23
26
  payloadPath?: string;
27
+ claudeProjectedBriefPath?: string;
28
+ claudeProjectedBriefHash?: string;
24
29
  gatewayCredentialPath?: string;
25
30
  skillRuntime?: SkillRuntimeBootstrapMetadata;
26
31
  localhostGateway?: LocalhostGatewayBootstrapMetadata;
27
- taskWorkspace?: TaskWorkspaceContext;
32
+ resolvedWorkspace?: ResolvedWorkspaceContext;
28
33
  }
29
34
  export declare class ChannelContextPreparationError extends Error {
30
35
  readonly partialContext: PreparedChannelContext;
@@ -33,24 +38,34 @@ export declare class ChannelContextPreparationError extends Error {
33
38
  export interface ChannelContextStore {
34
39
  prepare(input: {
35
40
  channelId: string;
41
+ provider?: ProviderKind;
42
+ projectionStrategy?: ProjectionStrategy;
36
43
  collaboration?: ProviderCollaborationContext;
37
44
  collaborationOutcome?: CollaborationOutcomeSnapshot;
38
45
  attentionSnapshot?: AttentionSnapshot;
46
+ compactionSnapshot?: CompactionSnapshot;
39
47
  taskThreadCollaborationContract?: TaskThreadCollaborationContract;
40
48
  collaborationCapabilities?: CollaborationCapabilityDeclaration;
41
49
  missedCollaborationDiagnostic?: MissedCollaborationDiagnostic;
42
50
  incomingMessageType?: string;
43
51
  incomingContent?: string;
52
+ taskAssignmentContextOverride?: TaskAssignmentThreadContext;
53
+ taskAssignmentContextOverridePersistence?: 'persist' | 'ephemeral';
44
54
  }): Promise<PreparedChannelContext>;
45
55
  prepare(channelId: string, options?: {
56
+ provider?: ProviderKind;
57
+ projectionStrategy?: ProjectionStrategy;
46
58
  collaboration?: ProviderCollaborationContext;
47
59
  collaborationOutcome?: CollaborationOutcomeSnapshot;
48
60
  attentionSnapshot?: AttentionSnapshot;
61
+ compactionSnapshot?: CompactionSnapshot;
49
62
  taskThreadCollaborationContract?: TaskThreadCollaborationContract;
50
63
  collaborationCapabilities?: CollaborationCapabilityDeclaration;
51
64
  missedCollaborationDiagnostic?: MissedCollaborationDiagnostic;
52
65
  incomingMessageType?: string;
53
66
  incomingContent?: string;
67
+ taskAssignmentContextOverride?: TaskAssignmentThreadContext;
68
+ taskAssignmentContextOverridePersistence?: 'persist' | 'ephemeral';
54
69
  }): Promise<PreparedChannelContext>;
55
70
  }
56
71
  export interface SkillAssetResolver {
@@ -84,23 +99,45 @@ interface ContextFileSystem {
84
99
  }): Promise<void>;
85
100
  unlink(path: string): Promise<void>;
86
101
  rename(oldPath: string, newPath: string): Promise<void>;
87
- access(path: string): Promise<void>;
102
+ access(path: string, mode?: number): Promise<void>;
103
+ stat?(path: string): Promise<{
104
+ isDirectory(): boolean;
105
+ }>;
88
106
  }
89
107
  interface FileChannelContextStoreOptions {
90
108
  fileSystem?: ContextFileSystem;
91
109
  skillRuntimeEnabled?: boolean;
92
110
  skillAssetResolver?: SkillAssetResolver;
93
111
  localhostGateway?: LocalhostGatewayContextPublisher;
94
- taskWorkspaceRootDir?: string;
112
+ workspaceCollectionRootDir?: string;
113
+ taskReader?: Pick<ChatControlPlane, 'getTask' | 'listChannels' | 'listTasks' | 'listUsers'>;
114
+ taskResolutionTimeoutMs?: number;
115
+ allowCrossAgentIndependentWorkspaceHandoff?: boolean;
116
+ resolveStableAgentId?: () => string | undefined;
117
+ env?: NodeJS.ProcessEnv;
118
+ resolvedHomeDir?: string;
95
119
  }
120
+ export declare function buildRuntimeSurfaceForTurn(options?: {
121
+ localhostGateway?: LocalhostGatewayBootstrapMetadata;
122
+ collaboration?: Pick<ProviderCollaborationContext, 'sendRoutesAllowed' | 'turnMode'>;
123
+ taskAssignmentContext?: TaskAssignmentThreadContext;
124
+ }): RuntimeSurface;
96
125
  export declare function extractTaskIdFromTaskAssignmentContent(incomingContent: string | undefined): string | undefined;
97
126
  export declare function encodeChannelPathSegment(channelId: string): string;
98
127
  export declare function resolveChannelContextDirectory(stateRootDir: string, channelId: string): string;
99
128
  export declare function resolveChannelContextPayloadPath(stateRootDir: string, channelId: string): string;
129
+ export declare function resolveTaskAssignmentStateDirectory(stateRootDir: string, channelId: string): string;
130
+ export declare function resolveTaskAssignmentStatePath(stateRootDir: string, channelId: string): string;
100
131
  export declare function resolveTaskWorkspaceRootDirectory(startupWorkspaceRootDir: string): string;
101
- export declare function resolveTaskWorkspaceDirectory(startupWorkspaceRootDir: string, channelId: string, taskId: string): string;
132
+ export declare function resolveManagedWorkspaceCollectionRoot(workspaceCollectionRootDir: string | undefined, env?: NodeJS.ProcessEnv, resolvedHomeDir?: string): string;
133
+ export declare function resolveChannelWorkspaceRootDirectory(workspaceCollectionRootDir: string, channelId: string): string;
134
+ export declare function resolveChannelWorkspaceDirectory(workspaceCollectionRootDir: string, channelId: string): string;
135
+ export declare function resolveTaskIsolatedWorkspaceDirectory(workspaceCollectionRootDir: string, channelId: string, taskId: string): string;
136
+ export declare const resolveTaskWorkspaceDirectory: typeof resolveTaskIsolatedWorkspaceDirectory;
137
+ export declare function resolveTaskThreadScratchWorkspaceDirectory(workspaceCollectionRootDir: string, channelId: string): string;
102
138
  export declare function resolveChannelGatewayCredentialPath(stateRootDir: string, channelId: string): string;
103
139
  export declare function resolveGatewayCredentialPathFromPayloadPath(payloadPath: string): string;
140
+ export declare function resolveClaudeProjectedBriefPathFromPayloadPath(payloadPath: string): string;
104
141
  export declare function isGatewayCredentialSidecarBasename(basename: string): boolean;
105
142
  export declare function resolveBorgeeAgentSkillRuntimeAssets(moduleUrl: string, fileSystem?: Pick<ContextFileSystem, 'access'>): Promise<SkillRuntimeBootstrapMetadata>;
106
143
  export declare class FileChannelContextStore implements ChannelContextStore {
@@ -109,27 +146,41 @@ export declare class FileChannelContextStore implements ChannelContextStore {
109
146
  private readonly skillRuntimeEnabled;
110
147
  private readonly skillAssetResolver;
111
148
  private readonly localhostGateway?;
112
- private readonly startupWorkspaceRootDir;
149
+ private readonly workspaceCollectionRootDir;
150
+ private readonly taskReader?;
151
+ private readonly taskResolutionTimeoutMs;
152
+ private readonly allowCrossAgentIndependentWorkspaceHandoff;
153
+ private readonly resolveStableAgentId?;
113
154
  constructor(stateRootDir: string, options?: FileChannelContextStoreOptions);
114
155
  prepare(inputOrChannelId: {
115
156
  channelId: string;
157
+ provider?: ProviderKind;
158
+ projectionStrategy?: ProjectionStrategy;
116
159
  collaboration?: ProviderCollaborationContext;
117
160
  collaborationOutcome?: CollaborationOutcomeSnapshot;
118
161
  attentionSnapshot?: AttentionSnapshot;
162
+ compactionSnapshot?: CompactionSnapshot;
119
163
  taskThreadCollaborationContract?: TaskThreadCollaborationContract;
120
164
  collaborationCapabilities?: CollaborationCapabilityDeclaration;
121
165
  missedCollaborationDiagnostic?: MissedCollaborationDiagnostic;
122
166
  incomingMessageType?: string;
123
167
  incomingContent?: string;
168
+ taskAssignmentContextOverride?: TaskAssignmentThreadContext;
169
+ taskAssignmentContextOverridePersistence?: 'persist' | 'ephemeral';
124
170
  } | string, options?: {
171
+ provider?: ProviderKind;
172
+ projectionStrategy?: ProjectionStrategy;
125
173
  collaboration?: ProviderCollaborationContext;
126
174
  collaborationOutcome?: CollaborationOutcomeSnapshot;
127
175
  attentionSnapshot?: AttentionSnapshot;
176
+ compactionSnapshot?: CompactionSnapshot;
128
177
  taskThreadCollaborationContract?: TaskThreadCollaborationContract;
129
178
  collaborationCapabilities?: CollaborationCapabilityDeclaration;
130
179
  missedCollaborationDiagnostic?: MissedCollaborationDiagnostic;
131
180
  incomingMessageType?: string;
132
181
  incomingContent?: string;
182
+ taskAssignmentContextOverride?: TaskAssignmentThreadContext;
183
+ taskAssignmentContextOverridePersistence?: 'persist' | 'ephemeral';
133
184
  }): Promise<PreparedChannelContext>;
134
185
  private resolveSkillRuntimeBestEffort;
135
186
  }