@concord-ai/concord-mcp 0.5.0 → 0.6.1

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 (151) hide show
  1. package/README.md +148 -61
  2. package/dist/artifacts/handoff-md.js +5 -1
  3. package/dist/artifacts/handoff-md.js.map +1 -1
  4. package/dist/artifacts/work-state-json.js +4 -0
  5. package/dist/artifacts/work-state-json.js.map +1 -1
  6. package/dist/artifacts/work-state-view.d.ts +12 -0
  7. package/dist/artifacts/work-state-view.js +26 -2
  8. package/dist/artifacts/work-state-view.js.map +1 -1
  9. package/dist/cli/commands/check.js +2 -1
  10. package/dist/cli/commands/check.js.map +1 -1
  11. package/dist/cli/commands/doctor.js +42 -4
  12. package/dist/cli/commands/doctor.js.map +1 -1
  13. package/dist/cli/commands/hook.d.ts +3 -3
  14. package/dist/cli/commands/hook.js +4 -4
  15. package/dist/cli/commands/hook.js.map +1 -1
  16. package/dist/cli/commands/setup.d.ts +21 -0
  17. package/dist/cli/commands/setup.js +117 -0
  18. package/dist/cli/commands/setup.js.map +1 -0
  19. package/dist/cli/commands/status.js +5 -1
  20. package/dist/cli/commands/status.js.map +1 -1
  21. package/dist/cli/commands/tasks.js +8 -4
  22. package/dist/cli/commands/tasks.js.map +1 -1
  23. package/dist/cli/commands/who.js +7 -2
  24. package/dist/cli/commands/who.js.map +1 -1
  25. package/dist/cli/context.d.ts +3 -2
  26. package/dist/cli/context.js +5 -4
  27. package/dist/cli/context.js.map +1 -1
  28. package/dist/cli/dashboard/app.js +2 -2
  29. package/dist/cli/dashboard/app.js.map +1 -1
  30. package/dist/cli/index.js +18 -7
  31. package/dist/cli/index.js.map +1 -1
  32. package/dist/cli/workspace-options.d.ts +21 -0
  33. package/dist/cli/workspace-options.js +36 -0
  34. package/dist/cli/workspace-options.js.map +1 -0
  35. package/dist/config/paths.d.ts +17 -3
  36. package/dist/config/paths.js +80 -10
  37. package/dist/config/paths.js.map +1 -1
  38. package/dist/db/index.d.ts +10 -1
  39. package/dist/db/index.js +6 -0
  40. package/dist/db/index.js.map +1 -1
  41. package/dist/db/repositories/agent-endpoints.d.ts +22 -0
  42. package/dist/db/repositories/agent-endpoints.js +87 -0
  43. package/dist/db/repositories/agent-endpoints.js.map +1 -0
  44. package/dist/db/repositories/agent-messages.d.ts +25 -0
  45. package/dist/db/repositories/agent-messages.js +151 -0
  46. package/dist/db/repositories/agent-messages.js.map +1 -0
  47. package/dist/db/repositories/handoffs.d.ts +9 -1
  48. package/dist/db/repositories/handoffs.js +38 -3
  49. package/dist/db/repositories/handoffs.js.map +1 -1
  50. package/dist/db/repositories/ownership-events.d.ts +19 -0
  51. package/dist/db/repositories/ownership-events.js +43 -0
  52. package/dist/db/repositories/ownership-events.js.map +1 -0
  53. package/dist/db/repositories/tasks.d.ts +12 -0
  54. package/dist/db/repositories/tasks.js +33 -5
  55. package/dist/db/repositories/tasks.js.map +1 -1
  56. package/dist/db/rows.d.ts +84 -3
  57. package/dist/db/rows.js +191 -2
  58. package/dist/db/rows.js.map +1 -1
  59. package/dist/db/schema.js +100 -0
  60. package/dist/db/schema.js.map +1 -1
  61. package/dist/domain/adoption.d.ts +3 -3
  62. package/dist/domain/adoption.js +2 -2
  63. package/dist/domain/adoption.js.map +1 -1
  64. package/dist/domain/operations.d.ts +42 -0
  65. package/dist/domain/operations.js +2 -0
  66. package/dist/domain/operations.js.map +1 -0
  67. package/dist/domain/presence.js +1 -1
  68. package/dist/domain/presence.js.map +1 -1
  69. package/dist/domain/schemas.d.ts +42 -251
  70. package/dist/domain/schemas.js +128 -98
  71. package/dist/domain/schemas.js.map +1 -1
  72. package/dist/index.js +12 -8
  73. package/dist/index.js.map +1 -1
  74. package/dist/install/agent-communications.d.ts +28 -0
  75. package/dist/install/agent-communications.js +61 -0
  76. package/dist/install/agent-communications.js.map +1 -0
  77. package/dist/install/codex-config.d.ts +21 -0
  78. package/dist/install/codex-config.js +68 -0
  79. package/dist/install/codex-config.js.map +1 -0
  80. package/dist/install/instructions.d.ts +6 -2
  81. package/dist/install/instructions.js +28 -34
  82. package/dist/install/instructions.js.map +1 -1
  83. package/dist/install/mcp-config.d.ts +24 -0
  84. package/dist/install/mcp-config.js +66 -0
  85. package/dist/install/mcp-config.js.map +1 -0
  86. package/dist/relay/adapters.d.ts +33 -0
  87. package/dist/relay/adapters.js +70 -0
  88. package/dist/relay/adapters.js.map +1 -0
  89. package/dist/relay/index.d.ts +4 -0
  90. package/dist/relay/index.js +5 -0
  91. package/dist/relay/index.js.map +1 -0
  92. package/dist/relay/protocol.d.ts +64 -0
  93. package/dist/relay/protocol.js +38 -0
  94. package/dist/relay/protocol.js.map +1 -0
  95. package/dist/relay/server.d.ts +40 -0
  96. package/dist/relay/server.js +196 -0
  97. package/dist/relay/server.js.map +1 -0
  98. package/dist/relay/socket-dispatcher.d.ts +9 -0
  99. package/dist/relay/socket-dispatcher.js +74 -0
  100. package/dist/relay/socket-dispatcher.js.map +1 -0
  101. package/dist/server.d.ts +9 -3
  102. package/dist/server.js +12 -15
  103. package/dist/server.js.map +1 -1
  104. package/dist/tools/agent-messages.d.ts +45 -0
  105. package/dist/tools/agent-messages.js +158 -0
  106. package/dist/tools/agent-messages.js.map +1 -0
  107. package/dist/tools/claim-work.d.ts +1 -19
  108. package/dist/tools/claim-work.js +8 -63
  109. package/dist/tools/claim-work.js.map +1 -1
  110. package/dist/tools/get-task-context.d.ts +5 -4
  111. package/dist/tools/get-task-context.js +4 -51
  112. package/dist/tools/get-task-context.js.map +1 -1
  113. package/dist/tools/get-work-state.d.ts +5 -6
  114. package/dist/tools/get-work-state.js +18 -36
  115. package/dist/tools/get-work-state.js.map +1 -1
  116. package/dist/tools/handoff-lifecycle.d.ts +10 -0
  117. package/dist/tools/handoff-lifecycle.js +151 -0
  118. package/dist/tools/handoff-lifecycle.js.map +1 -0
  119. package/dist/tools/handoff.d.ts +5 -9
  120. package/dist/tools/handoff.js +56 -93
  121. package/dist/tools/handoff.js.map +1 -1
  122. package/dist/tools/register-agent.d.ts +1 -4
  123. package/dist/tools/register-agent.js +0 -52
  124. package/dist/tools/register-agent.js.map +1 -1
  125. package/dist/tools/review-ready.d.ts +2 -4
  126. package/dist/tools/review-ready.js +36 -45
  127. package/dist/tools/review-ready.js.map +1 -1
  128. package/dist/tools/task-lifecycle.d.ts +12 -0
  129. package/dist/tools/task-lifecycle.js +200 -0
  130. package/dist/tools/task-lifecycle.js.map +1 -0
  131. package/dist/tools/update-task.d.ts +1 -4
  132. package/dist/tools/update-task.js +14 -29
  133. package/dist/tools/update-task.js.map +1 -1
  134. package/dist/tools/workflow.d.ts +47 -0
  135. package/dist/tools/workflow.js +566 -0
  136. package/dist/tools/workflow.js.map +1 -0
  137. package/dist/tools/workspace-routing.d.ts +8 -0
  138. package/dist/tools/workspace-routing.js +15 -0
  139. package/dist/tools/workspace-routing.js.map +1 -0
  140. package/dist/version.d.ts +1 -1
  141. package/dist/version.js +1 -1
  142. package/dist/workspaces/manager.d.ts +43 -0
  143. package/dist/workspaces/manager.js +124 -0
  144. package/dist/workspaces/manager.js.map +1 -0
  145. package/package.json +9 -3
  146. package/dist/cli/commands/init.d.ts +0 -6
  147. package/dist/cli/commands/init.js +0 -33
  148. package/dist/cli/commands/init.js.map +0 -1
  149. package/dist/cli/commands/install.d.ts +0 -2
  150. package/dist/cli/commands/install.js +0 -24
  151. package/dist/cli/commands/install.js.map +0 -1
@@ -1,42 +1,36 @@
1
- /** The canonical instruction block written into each client's config. */
1
+ /** Version of the generated agent workflow contract. */
2
+ export const CONCORD_INSTRUCTION_VERSION = '2';
3
+ /** Concise MCP-native guidance, versioned with the running server. */
4
+ export const CONCORD_SERVER_INSTRUCTIONS = `Concord coordinates coding agents through five workflow tools.
5
+ - Call start_work before editing. It registers your agent, claims or accepts the task, and reports overlaps.
6
+ - Use inspect_work to read workspace, task, agent, or message context. Use update_work for durable progress or to prompt/reply to another promptable workspace agent, including while that agent is busy.
7
+ - Use transfer_work for assignment, acceptance, decline, release, reassignment, evidence-bearing handoff offers, and reopening.
8
+ - Call finish_work before finishing, review, or closure with changed files, tests, assumptions, decisions, risks, and provenance.
9
+ Keep claims small and resolve reported overlaps before editing.`;
10
+ /** Canonical fallback block written into supported client instruction files. */
2
11
  export const CONCORD_INSTRUCTIONS = `## Concord — shared work-state for coding agents
3
12
 
4
- This project uses Concord MCP. Use its tools so your work is visible before PRs:
13
+ <!-- concord:workflow-version=${CONCORD_INSTRUCTION_VERSION} -->
5
14
 
6
- - **At session start, call \`register_agent\`** with your kind (e.g. claude-code),
7
- a one-line summary of what you are working on, and your status. Reuse the
8
- returned \`agent_id\` on every later Concord call so your presence stays
9
- attributed to one instance, and call \`register_agent\` again when your focus
10
- changes. Then call \`get_work_state\` to see who else is active before you
11
- start — it shows the agent roster, active claims, overlaps, and stale claims.
12
- - **Keep each claim small.** Break work into the smallest independently
13
- handoff-able unit and \`claim_work\` each piece separately, rather than
14
- claiming one broad task. Concord flags claims that look too broad.
15
- - **Before editing code**, call \`claim_work\` with the task id, title, your
16
- \`agent_id\`, and the files/modules you expect to touch. Concord warns about
17
- overlaps with other active work.
18
- - **While working**, call \`update_task\` (with your \`agent_id\`) for durable
19
- intent, progress, assumptions, decisions, questions, answers, blockers, and
20
- findings. When resuming or coordinating on a task, call \`get_task_context\`
21
- first.
22
- - **Before finishing or when blocked**, call \`handoff\` with what changed, tests
23
- run, assumptions, decisions, and guardrails you checked. **Before a PR**, set
24
- \`ready_for_review\` (with open questions and provenance) to also produce a
25
- review packet.
15
+ This project uses Concord MCP. Keep coordination to the five workflow tools:
26
16
 
27
- Concord regenerates human-readable \`HANDOFF.md\` and \`REVIEW_PACKET.md\` in
28
- \`.concord/\` so humans can review your work.
17
+ - **Before editing**, call \`start_work\` with the task, your agent kind/id, and
18
+ expected files or modules. It registers presence, accepts assigned work when
19
+ appropriate, claims the scope, and returns overlap warnings.
20
+ - Use \`inspect_work\` to read the workspace, one task, one agent, or one message
21
+ thread. Use \`update_work\` for durable progress and for live prompts/replies
22
+ to another promptable workspace agent, including while that agent is busy.
23
+ - Use \`transfer_work\` for assignment, acceptance, decline, release,
24
+ reassignment, evidence-bearing handoff offers, and reopening.
25
+ - **Before finishing**, call \`finish_work\` once with the outcome, changed
26
+ files, tests, assumptions, decisions, risks, guardrails, and provenance. It
27
+ records evidence and can mark work review-ready or terminal.
29
28
 
30
- Enforcement note: on clients with hooks/command registration this can be
31
- enforced; elsewhere it is instruction-based and may be skipped. \`concord doctor\`
32
- shows per-task adoption either way. For edit-time enforcement, wire a PreToolUse
33
- (or git pre-commit) hook to \`concord check <files> --task <your-task-id>\`; it
34
- exits non-zero when your edits collide with another agent's active claim. On
35
- Claude Code, \`concord install --claude-hooks\` installs this automatically — set
36
- \`CONCORD_TASK=<your task id>\` so the hook excludes your own claim. It also
37
- installs a SessionStart hook that auto-registers your presence and tells you the
38
- \`agent_id\` to reuse, so you are visible in the roster even before your first
39
- tool call.`;
29
+ Keep each claim small and resolve reported overlaps before editing. Concord
30
+ regenerates human-readable review artifacts in \`.concord/\`.
31
+
32
+ Enforcement remains client-dependent. \`concord doctor\` reports setup and
33
+ workflow adoption; optional hooks can block exact-file collisions.`;
40
34
  /** MDC frontmatter used when creating a fresh Cursor rules file. */
41
35
  export const CURSOR_MDC_HEADER = `---
42
36
  description: Concord shared work-state tools for coding agents
@@ -1 +1 @@
1
- {"version":3,"file":"instructions.js","sourceRoot":"","sources":["../../src/install/instructions.ts"],"names":[],"mappings":"AAAA,yEAAyE;AACzE,MAAM,CAAC,MAAM,oBAAoB,GAAG;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;WAqCzB,CAAC;AAEZ,oEAAoE;AACpE,MAAM,CAAC,MAAM,iBAAiB,GAAG;;;;CAIhC,CAAC"}
1
+ {"version":3,"file":"instructions.js","sourceRoot":"","sources":["../../src/install/instructions.ts"],"names":[],"mappings":"AAAA,wDAAwD;AACxD,MAAM,CAAC,MAAM,2BAA2B,GAAG,GAAG,CAAC;AAE/C,sEAAsE;AACtE,MAAM,CAAC,MAAM,2BAA2B,GAAG;;;;;gEAKqB,CAAC;AAEjE,gFAAgF;AAChF,MAAM,CAAC,MAAM,oBAAoB,GAAG;;gCAEJ,2BAA2B;;;;;;;;;;;;;;;;;;;;mEAoBQ,CAAC;AAEpE,oEAAoE;AACpE,MAAM,CAAC,MAAM,iBAAiB,GAAG;;;;CAIhC,CAAC"}
@@ -0,0 +1,24 @@
1
+ /** The key Concord registers itself under in an `mcpServers` map. */
2
+ export declare const CONCORD_SERVER_KEY = "concord";
3
+ /** The binary clients spawn to run the stdio MCP server. */
4
+ export declare const CONCORD_SERVER_COMMAND = "concord-mcp";
5
+ /**
6
+ * Thrown when an existing config file cannot be parsed. The caller reports this
7
+ * and leaves the file untouched rather than overwriting hand-written config.
8
+ */
9
+ export declare class McpConfigParseError extends Error {
10
+ readonly relPath: string;
11
+ constructor(relPath: string);
12
+ }
13
+ /**
14
+ * Idempotently add Concord's server entry to an `mcpServers` config string.
15
+ * Every other server and every unrelated top-level key is preserved, and
16
+ * passing the previous output back in is a no-op.
17
+ */
18
+ export declare function upsertMcpServer(existing: string | undefined, repoRoot: string): string;
19
+ /**
20
+ * Register Concord in every JSON-shaped client config under `repoRoot`
21
+ * (Claude Code's `.mcp.json` and Cursor's `.cursor/mcp.json`), creating each
22
+ * file if absent. Returns the relative paths written.
23
+ */
24
+ export declare function installMcpConfigs(repoRoot: string): string[];
@@ -0,0 +1,66 @@
1
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
2
+ import { dirname, join } from 'node:path';
3
+ import { z } from 'zod';
4
+ /** The key Concord registers itself under in an `mcpServers` map. */
5
+ export const CONCORD_SERVER_KEY = 'concord';
6
+ /** The binary clients spawn to run the stdio MCP server. */
7
+ export const CONCORD_SERVER_COMMAND = 'concord-mcp';
8
+ /** Repo-relative config paths that share the `mcpServers` JSON shape. */
9
+ const JSON_TARGETS = ['.mcp.json', join('.cursor', 'mcp.json')];
10
+ const mcpConfigSchema = z.object({ mcpServers: z.record(z.unknown()).optional() }).passthrough();
11
+ /**
12
+ * Thrown when an existing config file cannot be parsed. The caller reports this
13
+ * and leaves the file untouched rather than overwriting hand-written config.
14
+ */
15
+ export class McpConfigParseError extends Error {
16
+ relPath;
17
+ constructor(relPath) {
18
+ super(`${relPath} is not valid JSON — fix or remove it, then re-run.`);
19
+ this.relPath = relPath;
20
+ this.name = 'McpConfigParseError';
21
+ }
22
+ }
23
+ /**
24
+ * Idempotently add Concord's server entry to an `mcpServers` config string.
25
+ * Every other server and every unrelated top-level key is preserved, and
26
+ * passing the previous output back in is a no-op.
27
+ */
28
+ export function upsertMcpServer(existing, repoRoot) {
29
+ const source = existing === undefined || existing.trim() === '' ? {} : JSON.parse(existing);
30
+ const config = mcpConfigSchema.parse(source);
31
+ const servers = config.mcpServers ?? {};
32
+ const next = {
33
+ ...config,
34
+ mcpServers: {
35
+ ...servers,
36
+ [CONCORD_SERVER_KEY]: {
37
+ command: CONCORD_SERVER_COMMAND,
38
+ env: { CONCORD_REPO_ROOT: repoRoot },
39
+ },
40
+ },
41
+ };
42
+ return `${JSON.stringify(next, null, 2)}\n`;
43
+ }
44
+ function writeMcpConfig(repoRoot, relPath) {
45
+ const fullPath = join(repoRoot, relPath);
46
+ const existing = existsSync(fullPath) ? readFileSync(fullPath, 'utf8') : undefined;
47
+ let updated;
48
+ try {
49
+ updated = upsertMcpServer(existing, repoRoot);
50
+ }
51
+ catch {
52
+ throw new McpConfigParseError(relPath);
53
+ }
54
+ mkdirSync(dirname(fullPath), { recursive: true });
55
+ writeFileSync(fullPath, updated);
56
+ return relPath;
57
+ }
58
+ /**
59
+ * Register Concord in every JSON-shaped client config under `repoRoot`
60
+ * (Claude Code's `.mcp.json` and Cursor's `.cursor/mcp.json`), creating each
61
+ * file if absent. Returns the relative paths written.
62
+ */
63
+ export function installMcpConfigs(repoRoot) {
64
+ return JSON_TARGETS.map((relPath) => writeMcpConfig(repoRoot, relPath));
65
+ }
66
+ //# sourceMapp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entSessionDelivery } from './server.js';
2
+ export interface CodexAppServerClient {
3
+ request(method: 'turn/steer' | 'turn/start', params: Record<string, unknown>): Promise<unknown>;
4
+ }
5
+ /** Codex app-server adapter: an active turn is steered; idle starts a new turn. */
6
+ export declare class CodexAppServerAdapter implements AgentSessionAdapter {
7
+ private readonly client;
8
+ private readonly threadId;
9
+ private readonly currentTurnId;
10
+ readonly provider = "codex";
11
+ constructor(client: CodexAppServerClient, threadId: string, currentTurnId: () => string | undefined);
12
+ steer(delivery: AgentSessionDelivery): Promise<string | undefined>;
13
+ startTurn(delivery: AgentSessionDelivery): Promise<string | undefined>;
14
+ }
15
+ export interface PushPromptSession {
16
+ pushPrompt(content: string, mode: 'steer' | 'start'): Promise<string | undefined>;
17
+ }
18
+ /** Claude managed-session adapter using its streaming-input prompt channel. */
19
+ export declare class ClaudeStreamingAdapter implements AgentSessionAdapter {
20
+ private readonly session;
21
+ readonly provider = "claude";
22
+ constructor(session: PushPromptSession);
23
+ steer(delivery: AgentSessionDelivery): Promise<string | undefined>;
24
+ startTurn(delivery: AgentSessionDelivery): Promise<string | undefined>;
25
+ }
26
+ /** Cursor adapter for a client integration that exposes immediate follow-up injection. */
27
+ export declare class CursorSessionAdapter implements AgentSessionAdapter {
28
+ private readonly session;
29
+ readonly provider = "cursor";
30
+ constructor(session: PushPromptSession);
31
+ steer(delivery: AgentSessionDelivery): Promise<string | undefined>;
32
+ startTurn(delivery: AgentSessionDelivery): Promise<string | undefined>;
33
+ }
@@ -0,0 +1,70 @@
1
+ import { z } from 'zod';
2
+ /** Codex app-server adapter: an active turn is steered; idle starts a new turn. */
3
+ export class CodexAppServerAdapter {
4
+ client;
5
+ threadId;
6
+ currentTurnId;
7
+ provider = 'codex';
8
+ constructor(client, threadId, currentTurnId) {
9
+ this.client = client;
10
+ this.threadId = threadId;
11
+ this.currentTurnId = currentTurnId;
12
+ }
13
+ async steer(delivery) {
14
+ const turnId = this.currentTurnId();
15
+ if (turnId === undefined)
16
+ throw new Error('Codex session has no active turn to steer.');
17
+ await this.client.request('turn/steer', {
18
+ threadId: this.threadId,
19
+ turnId,
20
+ input: [{ type: 'text', text: delivery.content }],
21
+ });
22
+ return turnId;
23
+ }
24
+ async startTurn(delivery) {
25
+ const result = await this.client.request('turn/start', {
26
+ threadId: this.threadId,
27
+ input: [{ type: 'text', text: delivery.content }],
28
+ });
29
+ return receiptFrom(result);
30
+ }
31
+ }
32
+ /** Claude managed-session adapter using its streaming-input prompt channel. */
33
+ export class ClaudeStreamingAdapter {
34
+ session;
35
+ provider = 'claude';
36
+ constructor(session) {
37
+ this.session = session;
38
+ }
39
+ steer(delivery) {
40
+ return this.session.pushPrompt(delivery.content, 'steer');
41
+ }
42
+ startTurn(delivery) {
43
+ return this.session.pushPrompt(delivery.content, 'start');
44
+ }
45
+ }
46
+ /** Cursor adapter for a client integration that exposes immediate follow-up injection. */
47
+ export class CursorSessionAdapter {
48
+ session;
49
+ provider = 'cursor';
50
+ constructor(session) {
51
+ this.session = session;
52
+ }
53
+ steer(delivery) {
54
+ return this.session.pushPrompt(delivery.content, 'steer');
55
+ }
56
+ startTurn(delivery) {
57
+ return this.session.pushPrompt(delivery.content, 'start');
58
+ }
59
+ }
60
+ function receiptFrom(value) {
61
+ const parsed = z.record(z.unknown()).safeParse(value);
62
+ if (!parsed.success)
63
+ return undefined;
64
+ for (const key of ['turnId', 'turn_id', 'id']) {
65
+ if (typeof parsed.data[key] === 'string')
66
+ return parsed.data[key];
67
+ }
68
+ return undefined;
69
+ }
70
+ //# sourceMappingURL=adapters.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"adapters.js","sourceRoot":"","sources":["../../src/relay/adapters.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAMxB,mFAAmF;AACnF,MAAM,OAAO,qBAAqB;IAIb;IACA;IACA;IALV,QAAQ,GAAG,OAAO,CAAC;IAE5B,YACmB,MAA4B,EAC5B,QAAgB,EAChB,aAAuC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,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC;IAC5D,CAAC;CACF;AAED,0FAA0F;AAC1F,MAAM,OAAO,oBAAoB;IAEF;IADpB,QAAQ,GAAG,QAAQ,CAAC;IAC7B,YAA6B,OAA0B;QAA1B,YAAO,GAAP,OAAO,CAAmB;IAAG,CAAC;IAC3D,KAAK,CAAC,QAA8B;QAClC,OAAO,IAAI,CAAC,OAAO,CAAC,UAAU,CAAC,QAAQ,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC;IAC5D,CAAC;IACD,SAAS,CAAC,QAA8B;QACtC,OAAO,IAAI,CAAC,OAAO,CAAC,UAAU,CAAC,QAAQ,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC;IAC5D,CAAC;CACF;AAED,SAAS,WAAW,CAAC,KAAc;IACjC,MAAM,MAAM,GAAG,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,OAAO,EAAE,CAAC,CAAC,SAAS,CAAC,KAAK,CAAC,CAAC;IACtD,IAAI,CAAC,MAAM,CAAC,OAAO;QAAE,OAAO,SAAS,CAAC;IACtC,KAAK,MAAM,GAAG,IAAI,CAAC,QAAQ,EAAE,SAAS,EAAE,IAAI,CAAC,EAAE,CAAC;QAC9C,IAAI,OAAO,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,KAAK,QAAQ;YAAE,OAAO,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;IACpE,CAAC;IACD,OAAO,SAAS,CAAC;AACnB,CAAC"}
@@ -0,0 +1,4 @@
1
+ export { ClaudeStreamingAdapter, CodexAppServerAdapter, CursorSessionAdapter, type CodexAppServerClient, type PushPromptSession, } from './adapters.js';
2
+ export { MAX_RELAY_FRAME_BYTES, RELAY_PROTOCOL_VERSION, type RelayDelivery, type RelayResponse, } from './protocol.js';
3
+ export { startAgentRelay, startWorkspaceAgentRelay, type AgentRelayServerOptions, type AgentSessionAdapter, type AgentSessionDelivery, type RunningAgentRelay, type WorkspaceAgentRelayServerOptions, } from './server.js';
4
+ export { SocketAgentMessageDispatcher } from './socket-dispatcher.js';
@@ -0,0 +1,5 @@
1
+ export { ClaudeStreamingAdapter, CodexAppServerAdapter, CursorSessionAdapter, } from './adapters.js';
2
+ export { MAX_RELAY_FRAME_BYTES, RELAY_PROTOCOL_VERSION, } from './protocol.js';
3
+ export { startAgentRelay, startWorkspaceAgentRelay, } from './server.js';
4
+ export { SocketAgentMessageDispatcher } from './socket-dispatcher.js';
5
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/relay/index.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,sBAAsB,EACtB,qBAAqB,EACrB,oBAAoB,GAGrB,MAAM,eAAe,CAAC;AACvB,OAAO,EACL,qBAAqB,EACrB,sBAAsB,GAGvB,MAAM,eAAe,CAAC;AACvB,OAAO,EACL,eAAe,EACf,wBAAwB,GAMzB,MAAM,aAAa,CAAC;AACrB,OAAO,EAAE,4BAA4B,EAAE,MAAM,wBAAwB,CAAC"}
@@ -0,0 +1,64 @@
1
+ import { z } from 'zod';
2
+ export declare const RELAY_PROTOCOL_VERSION = 1;
3
+ export declare const relayDeliverySchema: z.ZodObject<{
4
+ version: z.ZodLiteral<1>;
5
+ type: z.ZodLiteral<"deliver">;
6
+ messageId: z.ZodString;
7
+ senderAgentId: z.ZodString;
8
+ recipientAgentId: z.ZodString;
9
+ credentialProof: z.ZodString;
10
+ content: z.ZodString;
11
+ activeTurn: z.ZodBoolean;
12
+ }, "strip", z.ZodTypeAny, {
13
+ type: "deliver";
14
+ version: 1;
15
+ content: string;
16
+ recipientAgentId: string;
17
+ messageId: string;
18
+ senderAgentId: string;
19
+ credentialProof: string;
20
+ activeTurn: boolean;
21
+ }, {
22
+ type: "deliver";
23
+ version: 1;
24
+ content: string;
25
+ recipientAgentId: string;
26
+ messageId: string;
27
+ senderAgentId: string;
28
+ credentialProof: string;
29
+ activeTurn: boolean;
30
+ }>;
31
+ export type RelayDelivery = z.infer<typeof relayDeliverySchema>;
32
+ export declare const relayResponseSchema: z.ZodDiscriminatedUnion<"ok", [z.ZodObject<{
33
+ version: z.ZodLiteral<1>;
34
+ ok: z.ZodLiteral<true>;
35
+ provider: z.ZodString;
36
+ receipt: z.ZodOptional<z.ZodString>;
37
+ }, "strip", z.ZodTypeAny, {
38
+ version: 1;
39
+ provider: string;
40
+ ok: true;
41
+ receipt?: string | undefined;
42
+ }, {
43
+ version: 1;
44
+ provider: string;
45
+ ok: true;
46
+ receipt?: string | undefined;
47
+ }>, z.ZodObject<{
48
+ version: z.ZodLiteral<1>;
49
+ ok: z.ZodLiteral<false>;
50
+ error: z.ZodString;
51
+ }, "strip", z.ZodTypeAny, {
52
+ error: string;
53
+ version: 1;
54
+ ok: false;
55
+ }, {
56
+ error: string;
57
+ version: 1;
58
+ ok: false;
59
+ }>]>;
60
+ export type RelayResponse = z.infer<typeof relayResponseSchema>;
61
+ export declare const MAX_RELAY_FRAME_BYTES: number;
62
+ export declare function encodeRelayFrame(value: RelayDelivery | RelayResponse): string;
63
+ export declare function decodeRelayDelivery(frame: string): RelayDelivery;
64
+ export declare function decodeRelayResponse(frame: string): RelayResponse;
@@ -0,0 +1,38 @@
1
+ import { z } from 'zod';
2
+ export const RELAY_PROTOCOL_VERSION = 1;
3
+ export const relayDeliverySchema = z.object({
4
+ version: z.literal(RELAY_PROTOCOL_VERSION),
5
+ type: z.literal('deliver'),
6
+ messageId: z.string().min(1),
7
+ senderAgentId: z.string().min(1),
8
+ recipientAgentId: z.string().min(1),
9
+ credentialProof: z.string().min(1),
10
+ content: z.string().min(1),
11
+ activeTurn: z.boolean(),
12
+ });
13
+ export const relayResponseSchema = z.discriminatedUnion('ok', [
14
+ z.object({
15
+ version: z.literal(RELAY_PROTOCOL_VERSION),
16
+ ok: z.literal(true),
17
+ provider: z.string().min(1),
18
+ receipt: z.string().optional(),
19
+ }),
20
+ z.object({
21
+ version: z.literal(RELAY_PROTOCOL_VERSION),
22
+ ok: z.literal(false),
23
+ error: z.string().min(1),
24
+ }),
25
+ ]);
26
+ export const MAX_RELAY_FRAME_BYTES = 256 * 1024;
27
+ export function encodeRelayFrame(value) {
28
+ return `${JSON.stringify(value)}\n`;
29
+ }
30
+ export function decodeRelayDelivery(frame) {
31
+ const parsed = JSON.parse(frame);
32
+ return relayDeliverySchema.parse(parsed);
33
+ }
34
+ export function decodeRelayResponse(frame) {
35
+ const parsed = JSON.parse(frame);
36
+ return relayResponseSchema.parse(parsed);
37
+ }
38
+ //# sourceMappingURL=protocol.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"protocol.js","sourceRoot":"","sources":["../../src/relay/protocol.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAExB,MAAM,CAAC,MAAM,sBAAsB,GAAG,CAAC,CAAC;AAExC,MAAM,CAAC,MAAM,mBAAmB,GAAG,CAAC,CAAC,MAAM,CAAC;IAC1C,OAAO,EAAE,CAAC,CAAC,OAAO,CAAC,sBAAsB,CAAC;IAC1C,IAAI,EAAE,CAAC,CAAC,OAAO,CAAC,SAAS,CAAC;IAC1B,SAAS,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,GAAG,CAAC,CAAC,CAAC;IAC5B,aAAa,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,GAAG,CAAC,CAAC,CAAC;IAChC,gBAAgB,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,GAAG,CAAC,CAAC,CAAC;IACnC,eAAe,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,GAAG,CAAC,CAAC,CAAC;IAClC,OAAO,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,GAAG,CAAC,CAAC,CAAC;IAC1B,UAAU,EAAE,CAAC,CAAC,OAAO,EAAE;CACxB,CAAC,CAAC;AAGH,MAAM,CAAC,MAAM,mBAAmB,GAAG,CAAC,CAAC,kBAAkB,CAAC,IAAI,EAAE;IAC5D,CAAC,CAAC,MAAM,CAAC;QACP,OAAO,EAAE,CAAC,CAAC,OAAO,CAAC,sBAAsB,CAAC;QAC1C,EAAE,EAAE,CAAC,CAAC,OAAO,CAAC,IAAI,CAAC;QACnB,QAAQ,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,GAAG,CAAC,CAAC,CAAC;QAC3B,OAAO,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,QAAQ,EAAE;KAC/B,CAAC;IACF,CAAC,CAAC,MAAM,CAAC;QACP,OAAO,EAAE,CAAC,CAAC,OAAO,CAAC,sBAAsB,CAAC;QAC1C,EAAE,EAAE,CAAC,CAAC,OAAO,CAAC,KAAK,CAAC;QACpB,KAAK,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,GAAG,CAAC,CAAC,CAAC;KACzB,CAAC;CACH,CAAC,CAAC;AAGH,MAAM,CAAC,MAAM,qBAAqB,GAAG,GAAG,GAAG,IAAI,CAAC;AAEhD,MAAM,UAAU,gBAAgB,CAAC,KAAoC;IACnE,OAAO,GAAG,IAAI,CAAC,SAAS,CAAC,KAAK,CAAC,IAAI,CAAC;AACtC,CAAC;AAED,MAAM,UAAU,mBAAmB,CAAC,KAAa;IAC/C,MAAM,MAAM,GAAY,IAAI,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC;IAC1C,OAAO,mBAAmB,CAAC,KAAK,CAAC,MAAM,CAAC,CAAC;AAC3C,CAAC;AAED,MAAM,UAAU,mBAAmB,CAAC,KAAa;IAC/C,MAAM,MAAM,GAAY,IAAI,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC;IAC1C,OAAO,mBAAmB,CAAC,KAAK,CAAC,MAAM,CAAC,CAAC;AAC3C,CAAC"}
@@ -0,0 +1,40 @@
1
+ import { type Repositories } from '../db/index.js';
2
+ import { type RelayDelivery } from './protocol.js';
3
+ export interface AgentSessionAdapter {
4
+ readonly provider: string;
5
+ /** Inject into the current turn. Called only when the endpoint reports an active turn. */
6
+ steer(delivery: AgentSessionDelivery): Promise<string | undefined>;
7
+ /** Start a new turn immediately when the endpoint is idle. */
8
+ startTurn(delivery: AgentSessionDelivery): Promise<string | undefined>;
9
+ }
10
+ export type AgentSessionDelivery = Omit<RelayDelivery, 'credentialProof'>;
11
+ export interface AgentRelayServerOptions {
12
+ repos: Repositories;
13
+ agentId: string;
14
+ address: string;
15
+ adapter: AgentSessionAdapter;
16
+ /** Dynamic state supplied by the client integration, not inferred from agent liveness. */
17
+ hasActiveTurn: () => boolean;
18
+ ttlMs?: number;
19
+ }
20
+ export interface RunningAgentRelay {
21
+ endpointId: string;
22
+ credential: string;
23
+ address: string;
24
+ close(): Promise<void>;
25
+ }
26
+ export interface WorkspaceAgentRelayServerOptions extends Omit<AgentRelayServerOptions, 'repos'> {
27
+ repoRoot: string;
28
+ }
29
+ /**
30
+ * Host a local, one-frame relay for a live client session. The integration that
31
+ * owns the session supplies the provider adapter, so busy-turn steering happens
32
+ * through the provider's supported in-process/app-server API.
33
+ */
34
+ export declare function startAgentRelay(options: AgentRelayServerOptions): Promise<RunningAgentRelay>;
35
+ /**
36
+ * Public package entry point for client integrations. It binds the relay to a
37
+ * repository's Concord database and owns that connection for the relay's
38
+ * lifetime, so an installed host does not need Concord's internal repositories.
39
+ */
40
+ export declare function startWorkspaceAgentRelay(options: WorkspaceAgentRelayServerOptions): Promise<RunningAgentRelay>;
@@ -0,0 +1,196 @@
1
+ import { createHash, randomBytes, randomUUID, timingSafeEqual } from 'node:crypto';
2
+ import { chmodSync, existsSync, lstatSync, unlinkSync } from 'node:fs';
3
+ import { createServer } from 'node:net';
4
+ import { openRepositories } from '../db/index.js';
5
+ import { databasePath, resolveExplicitRepoRoot } from '../config/paths.js';
6
+ import { decodeRelayDelivery, encodeRelayFrame, MAX_RELAY_FRAME_BYTES, RELAY_PROTOCOL_VERSION, } from './protocol.js';
7
+ function respond(socket, response) {
8
+ socket.end(encodeRelayFrame(response));
9
+ }
10
+ function removeUnixSocket(address) {
11
+ if (process.platform === 'win32' || !existsSync(address))
12
+ return;
13
+ if (!lstatSync(address).isSocket()) {
14
+ throw new Error(`Refusing to replace non-socket relay path: ${address}`);
15
+ }
16
+ unlinkSync(address);
17
+ }
18
+ function listen(server, address) {
19
+ return new Promise((resolve, reject) => {
20
+ server.once('error', reject);
21
+ server.listen(address, () => {
22
+ server.off('error', reject);
23
+ resolve();
24
+ });
25
+ });
26
+ }
27
+ function toSessionDelivery(delivery) {
28
+ return {
29
+ version: delivery.version,
30
+ type: delivery.type,
31
+ messageId: delivery.messageId,
32
+ senderAgentId: delivery.senderAgentId,
33
+ recipientAgentId: delivery.recipientAgentId,
34
+ content: delivery.content,
35
+ activeTurn: delivery.activeTurn,
36
+ };
37
+ }
38
+ /**
39
+ * Host a local, one-frame relay for a live client session. The integration that
40
+ * owns the session supplies the provider adapter, so busy-turn steering happens
41
+ * through the provider's supported in-process/app-server API.
42
+ */
43
+ export async function startAgentRelay(options) {
44
+ const agent = options.repos.agents.get(options.agentId);
45
+ if (agent === undefined)
46
+ throw new Error(`Agent ${options.agentId} is not registered.`);
47
+ removeUnixSocket(options.address);
48
+ const ttlMs = options.ttlMs ?? 15_000;
49
+ const endpointId = randomUUID();
50
+ const credential = randomBytes(32).toString('base64url');
51
+ const credentialHash = createHash('sha256').update(credential).digest('hex');
52
+ let closed = false;
53
+ const server = createServer((socket) => {
54
+ let buffer = '';
55
+ socket.on('data', (chunk) => {
56
+ buffer += chunk.toString('utf8');
57
+ if (Buffer.byteLength(buffer, 'utf8') > MAX_RELAY_FRAME_BYTES) {
58
+ respond(socket, {
59
+ version: RELAY_PROTOCOL_VERSION,
60
+ ok: false,
61
+ error: 'relay request exceeded maximum frame size',
62
+ });
63
+ return;
64
+ }
65
+ const newline = buffer.indexOf('\n');
66
+ if (newline < 0)
67
+ return;
68
+ socket.removeAllListeners('data');
69
+ void (async () => {
70
+ try {
71
+ const delivery = decodeRelayDelivery(buffer.slice(0, newline));
72
+ const suppliedProof = Buffer.from(delivery.credentialProof, 'utf8');
73
+ const expectedProof = Buffer.from(credentialHash, 'utf8');
74
+ if (suppliedProof.length !== expectedProof.length ||
75
+ !timingSafeEqual(suppliedProof, expectedProof)) {
76
+ throw new Error('Relay credential was rejected.');
77
+ }
78
+ if (delivery.recipientAgentId !== options.agentId) {
79
+ throw new Error(`Relay endpoint belongs to ${options.agentId}.`);
80
+ }
81
+ const sessionDelivery = toSessionDelivery(delivery);
82
+ const activeTurn = options.hasActiveTurn();
83
+ const receipt = activeTurn
84
+ ? await options.adapter.steer({ ...sessionDelivery, activeTurn })
85
+ : await options.adapter.startTurn({ ...sessionDelivery, activeTurn });
86
+ respond(socket, {
87
+ version: RELAY_PROTOCOL_VERSION,
88
+ ok: true,
89
+ provider: options.adapter.provider,
90
+ ...(receipt === undefined ? {} : { receipt }),
91
+ });
92
+ }
93
+ catch (error) {
94
+ respond(socket, {
95
+ version: RELAY_PROTOCOL_VERSION,
96
+ ok: false,
97
+ error: error instanceof Error ? error.message : String(error),
98
+ });
99
+ }
100
+ })();
101
+ });
102
+ });
103
+ await listen(server, options.address);
104
+ if (process.platform !== 'win32')
105
+ chmodSync(options.address, 0o600);
106
+ const expiresAt = () => new Date(Date.now() + ttlMs).toISOString();
107
+ const capabilities = () => [
108
+ 'steer',
109
+ 'start-turn',
110
+ ...(options.hasActiveTurn() ? ['active-turn'] : []),
111
+ ];
112
+ options.repos.agentEndpoints.upsert({
113
+ endpointId,
114
+ agentId: options.agentId,
115
+ provider: options.adapter.provider,
116
+ transport: 'local-socket',
117
+ capabilities: capabilities(),
118
+ address: options.address,
119
+ credentialHash,
120
+ expiresAt: expiresAt(),
121
+ });
122
+ const heartbeat = setInterval(() => {
123
+ if (closed)
124
+ return;
125
+ const current = options.repos.agentEndpoints.get(endpointId);
126
+ if (current === undefined)
127
+ return;
128
+ options.repos.agentEndpoints.upsert({
129
+ endpointId,
130
+ agentId: options.agentId,
131
+ provider: options.adapter.provider,
132
+ transport: 'local-socket',
133
+ capabilities: capabilities(),
134
+ address: options.address,
135
+ credentialHash: current.credentialHash,
136
+ expiresAt: expiresAt(),
137
+ });
138
+ }, Math.max(1_000, Math.floor(ttlMs / 3)));
139
+ heartbeat.unref();
140
+ return {
141
+ endpointId,
142
+ credential,
143
+ address: options.address,
144
+ close: async () => {
145
+ if (closed)
146
+ return;
147
+ closed = true;
148
+ clearInterval(heartbeat);
149
+ options.repos.agentEndpoints.disconnect(endpointId);
150
+ await new Promise((resolve, reject) => {
151
+ server.close((error) => {
152
+ if (error === undefined)
153
+ resolve();
154
+ else
155
+ reject(error);
156
+ });
157
+ });
158
+ removeUnixSocket(options.address);
159
+ },
160
+ };
161
+ }
162
+ /**
163
+ * Public package entry point for client integrations. It binds the relay to a
164
+ * repository's Concord database and owns that connection for the relay's
165
+ * lifetime, so an installed host does not need Concord's internal repositories.
166
+ */
167
+ export async function startWorkspaceAgentRelay(options) {
168
+ const { repoRoot, ...relayOptions } = options;
169
+ const repos = openRepositories(databasePath(resolveExplicitRepoRoot(repoRoot)));
170
+ let relay;
171
+ try {
172
+ relay = await startAgentRelay({ ...relayOptions, repos });
173
+ }
174
+ catch (error) {
175
+ repos.db.close();
176
+ throw error;
177
+ }
178
+ let closed = false;
179
+ return {
180
+ endpointId: relay.endpointId,
181
+ credential: relay.credential,
182
+ address: relay.address,
183
+ close: async () => {
184
+ if (closed)
185
+ return;
186
+ closed = true;
187
+ try {
188
+ await relay.close();
189
+ }
190
+ finally {
191
+ repos.db.close();
192
+ }
193
+ },
194
+ };
195
+ }
196
+ //# sourceMappingURL=server.js.map