@concord-ai/concord-mcp 0.10.5 → 0.12.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (90) hide show
  1. package/README.md +8 -4
  2. package/dist/artifacts/work-state-view.js +21 -5
  3. package/dist/artifacts/work-state-view.js.map +1 -1
  4. package/dist/cli/commands/adapters.js +12 -1
  5. package/dist/cli/commands/adapters.js.map +1 -1
  6. package/dist/cli/commands/cloud-codex.d.ts +14 -0
  7. package/dist/cli/commands/cloud-codex.js +148 -0
  8. package/dist/cli/commands/cloud-codex.js.map +1 -0
  9. package/dist/cli/commands/cloud-hooks.d.ts +11 -0
  10. package/dist/cli/commands/cloud-hooks.js +121 -0
  11. package/dist/cli/commands/cloud-hooks.js.map +1 -0
  12. package/dist/cli/commands/cloud-inbox.d.ts +49 -0
  13. package/dist/cli/commands/cloud-inbox.js +167 -0
  14. package/dist/cli/commands/cloud-inbox.js.map +1 -0
  15. package/dist/cli/commands/cloud-views.d.ts +11 -0
  16. package/dist/cli/commands/cloud-views.js +92 -0
  17. package/dist/cli/commands/cloud-views.js.map +1 -0
  18. package/dist/cli/commands/cloud.d.ts +41 -0
  19. package/dist/cli/commands/cloud.js +226 -0
  20. package/dist/cli/commands/cloud.js.map +1 -0
  21. package/dist/cli/commands/export.js +7 -0
  22. package/dist/cli/commands/export.js.map +1 -1
  23. package/dist/cli/commands/hook.js +39 -19
  24. package/dist/cli/commands/hook.js.map +1 -1
  25. package/dist/cli/commands/inbox.js +129 -57
  26. package/dist/cli/commands/inbox.js.map +1 -1
  27. package/dist/cli/commands/session-start-message.d.ts +8 -0
  28. package/dist/cli/commands/session-start-message.js +21 -0
  29. package/dist/cli/commands/session-start-message.js.map +1 -0
  30. package/dist/cli/commands/setup.d.ts +7 -2
  31. package/dist/cli/commands/setup.js +26 -11
  32. package/dist/cli/commands/setup.js.map +1 -1
  33. package/dist/cli/commands/status.js +4 -2
  34. package/dist/cli/commands/status.js.map +1 -1
  35. package/dist/cli/commands/tasks.js +4 -2
  36. package/dist/cli/commands/tasks.js.map +1 -1
  37. package/dist/cli/commands/who.js +4 -2
  38. package/dist/cli/commands/who.js.map +1 -1
  39. package/dist/cli/index.js +16 -1
  40. package/dist/cli/index.js.map +1 -1
  41. package/dist/cloud/browser-login.d.ts +27 -0
  42. package/dist/cloud/browser-login.js +115 -0
  43. package/dist/cloud/browser-login.js.map +1 -0
  44. package/dist/cloud/client.d.ts +68 -0
  45. package/dist/cloud/client.js +114 -0
  46. package/dist/cloud/client.js.map +1 -0
  47. package/dist/cloud/http-transport.d.ts +18 -0
  48. package/dist/cloud/http-transport.js +40 -0
  49. package/dist/cloud/http-transport.js.map +1 -0
  50. package/dist/cloud/proxy.d.ts +56 -0
  51. package/dist/cloud/proxy.js +162 -0
  52. package/dist/cloud/proxy.js.map +1 -0
  53. package/dist/cloud/runtime.d.ts +152 -0
  54. package/dist/cloud/runtime.js +332 -0
  55. package/dist/cloud/runtime.js.map +1 -0
  56. package/dist/cloud/settings.d.ts +62 -0
  57. package/dist/cloud/settings.js +162 -0
  58. package/dist/cloud/settings.js.map +1 -0
  59. package/dist/cloud/tokens.d.ts +20 -0
  60. package/dist/cloud/tokens.js +87 -0
  61. package/dist/cloud/tokens.js.map +1 -0
  62. package/dist/config/paths.d.ts +13 -0
  63. package/dist/config/paths.js +40 -0
  64. package/dist/config/paths.js.map +1 -1
  65. package/dist/db/repositories/reviews.d.ts +1 -0
  66. package/dist/db/repositories/reviews.js +23 -0
  67. package/dist/db/repositories/reviews.js.map +1 -1
  68. package/dist/db/repositories/tasks.d.ts +1 -0
  69. package/dist/db/repositories/tasks.js +9 -0
  70. package/dist/db/repositories/tasks.js.map +1 -1
  71. package/dist/domain/project-key.d.ts +23 -0
  72. package/dist/domain/project-key.js +109 -0
  73. package/dist/domain/project-key.js.map +1 -0
  74. package/dist/domain/pull-inbox.d.ts +12 -0
  75. package/dist/domain/pull-inbox.js +14 -1
  76. package/dist/domain/pull-inbox.js.map +1 -1
  77. package/dist/domain/schemas.d.ts +1 -1
  78. package/dist/index.js +11 -2
  79. package/dist/index.js.map +1 -1
  80. package/dist/install/adapters/index.js +6 -13
  81. package/dist/install/adapters/index.js.map +1 -1
  82. package/dist/relay/server.d.ts +2 -0
  83. package/dist/relay/server.js +26 -5
  84. package/dist/relay/server.js.map +1 -1
  85. package/dist/server.d.ts +1 -1
  86. package/dist/version.d.ts +1 -1
  87. package/dist/version.js +1 -1
  88. package/package.json +1 -1
  89. package/plugin/concord-relay/scripts/watch-inbox.sh +11 -0
  90. package/plugin/cursor/concord-relay/cursor-hook.mjs +16 -1
@@ -0,0 +1,162 @@
1
+ import { existsSync, realpathSync } from 'node:fs';
2
+ import { isAbsolute, relative, sep } from 'node:path';
3
+ import { Client } from '@modelcontextprotocol/sdk/client/index.js';
4
+ import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
5
+ import { CallToolRequestSchema, ListToolsRequestSchema, } from '@modelcontextprotocol/sdk/types.js';
6
+ import { z } from 'zod';
7
+ import { CONCORD_SERVER_INSTRUCTIONS } from '../install/instructions.js';
8
+ import { VERSION } from '../version.js';
9
+ import { HttpClientTransport } from './http-transport.js';
10
+ import { bearerFor } from './tokens.js';
11
+ import { assertKeySafeUrl, sameApi } from './client.js';
12
+ import { readCredentials, readLink, readMachineKey } from './settings.js';
13
+ /**
14
+ * The cloud session for a repository: undefined when it is not linked, so
15
+ * Concord stays local. A link this machine cannot use is an error rather than a
16
+ * silent fall back to local state, which no other agent would see.
17
+ */
18
+ export function cloudSessionFor(repoRoot, env, identity, checkoutRoot = repoRoot) {
19
+ const link = readLink(repoRoot);
20
+ if (link === undefined)
21
+ return undefined;
22
+ const credentials = readCredentials(env);
23
+ const machineKey = readMachineKey(env);
24
+ if (credentials === undefined || machineKey === undefined) {
25
+ throw new Error(`${repoRoot} is linked to Concord Cloud, but this machine is not logged in. ` +
26
+ 'Run `concord cloud login`, or `concord cloud unlink` to work locally.');
27
+ }
28
+ if (!sameApi(credentials.apiUrl, link.apiUrl)) {
29
+ throw new Error(`${repoRoot} is linked to ${link.apiUrl}, but this machine is logged in to ` +
30
+ `${credentials.apiUrl}. Log in to the linked API, or link again.`);
31
+ }
32
+ assertKeySafeUrl(credentials.apiUrl);
33
+ return {
34
+ apiUrl: credentials.apiUrl,
35
+ bearer: bearerFor(env, credentials.apiUrl, fetch),
36
+ machineKey,
37
+ projectKey: link.projectKey,
38
+ repoRoot,
39
+ checkoutRoot,
40
+ identity,
41
+ };
42
+ }
43
+ /** The tools that act as an agent, and so act as this session's. */
44
+ const WRITE_TOOLS = new Set(['start_work', 'update_work', 'transfer_work', 'finish_work']);
45
+ const toolArguments = z.record(z.string(), z.json());
46
+ /** `path` relative to `root`, or undefined when it is not inside it. */
47
+ function inside(root, path) {
48
+ const within = relative(root, path);
49
+ if (within === '' || within === '..' || within.startsWith(`..${sep}`) || isAbsolute(within)) {
50
+ return undefined;
51
+ }
52
+ return within.split(sep).join('/');
53
+ }
54
+ /**
55
+ * An absolute path inside the checkout this session works in, or the primary
56
+ * one, made relative; anything else as given. Tried as written and resolved,
57
+ * so a path through a symlink (`/tmp` on macOS) still matches.
58
+ */
59
+ export function repoRelative(session, path) {
60
+ if (!isAbsolute(path))
61
+ return path;
62
+ const candidates = existsSync(path) ? [path, realpathSync(path)] : [path];
63
+ for (const root of [session.checkoutRoot, session.repoRoot]) {
64
+ for (const candidate of candidates) {
65
+ const within = inside(root, candidate);
66
+ if (within !== undefined)
67
+ return within;
68
+ }
69
+ }
70
+ return path;
71
+ }
72
+ /** A tool call's arguments as the cloud should receive them. */
73
+ export function forwardedArguments(tool, args, session) {
74
+ const forwarded = {};
75
+ for (const [name, value] of Object.entries(args)) {
76
+ forwarded[name] =
77
+ name.endsWith('files') && Array.isArray(value)
78
+ ? value.map((item) => (typeof item === 'string' ? repoRelative(session, item) : item))
79
+ : value;
80
+ }
81
+ // The session is the authority, as `resolveActorId` makes it locally.
82
+ const identity = session.identity;
83
+ if (identity !== undefined && WRITE_TOOLS.has(tool)) {
84
+ forwarded['agent_id'] = identity.agentId;
85
+ if (tool === 'start_work')
86
+ forwarded['kind'] = identity.kind;
87
+ }
88
+ return forwarded;
89
+ }
90
+ /** Opens an MCP client session with the cloud's `/mcp`, as this repository and machine. */
91
+ export async function connectCloud(session, fetchImpl) {
92
+ const transport = new HttpClientTransport(new URL(`${session.apiUrl.replace(/\/+$/, '')}/mcp`), {
93
+ 'x-concord-project': session.projectKey,
94
+ 'x-concord-machine': session.machineKey,
95
+ },
96
+ // The token is fetched per request, so a long session is never sent with
97
+ // one that has expired since it connected.
98
+ async (input, init) => {
99
+ const headers = new Headers(init?.headers);
100
+ headers.set('Authorization', `Bearer ${await session.bearer()}`);
101
+ return (fetchImpl ?? fetch)(input, { ...init, headers });
102
+ });
103
+ const client = new Client({ name: 'concord-mcp', version: VERSION });
104
+ await client.connect(transport);
105
+ return client;
106
+ }
107
+ function failure(reason) {
108
+ return {
109
+ isError: true,
110
+ content: [{ type: 'text', text: `Concord Cloud could not be reached: ${reason}` }],
111
+ };
112
+ }
113
+ /**
114
+ * The stdio-facing server for cloud mode. It connects lazily, on the first
115
+ * request, and again after a failure, so a cold or briefly unreachable API
116
+ * costs one failed call rather than the whole session.
117
+ */
118
+ export function createCloudProxyServer(session, connect) {
119
+ const server = new McpServer({ name: 'concord-mcp', version: VERSION }, { instructions: CONCORD_SERVER_INSTRUCTIONS, capabilities: { tools: {} } });
120
+ // One client, shared; dropped whenever a connection or a call through it
121
+ // fails, so the next call connects afresh instead of reusing a broken one.
122
+ // A tool's own error comes back as a result, never as a failure here.
123
+ let pending;
124
+ const forget = (attempt) => {
125
+ if (pending === attempt)
126
+ pending = undefined;
127
+ };
128
+ const cloud = () => {
129
+ if (pending === undefined) {
130
+ const attempt = connect();
131
+ pending = attempt;
132
+ attempt.catch(() => {
133
+ forget(attempt);
134
+ });
135
+ }
136
+ return pending;
137
+ };
138
+ server.server.setRequestHandler(ListToolsRequestSchema, async () => {
139
+ const attempt = cloud();
140
+ try {
141
+ return await (await attempt).listTools();
142
+ }
143
+ catch (error) {
144
+ forget(attempt);
145
+ throw error;
146
+ }
147
+ });
148
+ server.server.setRequestHandler(CallToolRequestSchema, async (request) => {
149
+ const attempt = cloud();
150
+ try {
151
+ const { name } = request.params;
152
+ const args = toolArguments.parse(request.params.arguments ?? {});
153
+ return await (await attempt).callTool({ name, arguments: forwardedArguments(name, args, session) });
154
+ }
155
+ catch (error) {
156
+ forget(attempt);
157
+ return failure(error instanceof Error ? error.message : String(error));
158
+ }
159
+ });
160
+ return server;
161
+ }
162
+ //# sourceMappingURL=proxy.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"proxy.js","sourceRoot":"","sources":["../../src/cloud/proxy.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,YAAY,EAAE,MAAM,SAAS,CAAC;AACnD,OAAO,EAAE,UAAU,EAAE,QAAQ,EAAE,GAAG,EAAE,MAAM,WAAW,CAAC;AAEtD,OAAO,EAAE,MAAM,EAAE,MAAM,2CAA2C,CAAC;AACnE,OAAO,EAAE,SAAS,EAAE,MAAM,yCAAyC,CAAC;AAEpE,OAAO,EACL,qBAAqB,EACrB,sBAAsB,GAEvB,MAAM,oCAAoC,CAAC;AAC5C,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAGxB,OAAO,EAAE,2BAA2B,EAAE,MAAM,4BAA4B,CAAC;AACzE,OAAO,EAAE,OAAO,EAAE,MAAM,eAAe,CAAC;AACxC,OAAO,EAAE,mBAAmB,EAAE,MAAM,qBAAqB,CAAC;AAC1D,OAAO,EAAE,SAAS,EAAe,MAAM,aAAa,CAAC;AACrD,OAAO,EAAE,gBAAgB,EAAE,OAAO,EAAE,MAAM,aAAa,CAAC;AACxD,OAAO,EAAE,eAAe,EAAE,QAAQ,EAAE,cAAc,EAAE,MAAM,eAAe,CAAC;AA6B1E;;;;GAIG;AACH,MAAM,UAAU,eAAe,CAC7B,QA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+ import type { CloudSession } from './proxy.js';
5
+ /**
6
+ * A session's runtime against Concord Cloud: what the inbox commands and the
7
+ * session-start hook do locally over SQLite, done over the cloud's REST API.
8
+ *
9
+ * Agents are named by the runtime's own key; the cloud's ids for this machine
10
+ * and its agents are kept in `.concord/cloud-agents/`, one file each, so a hook that runs
11
+ * after every tool call costs one request rather than four. A cached id the
12
+ * cloud no longer knows is registered again and the call retried once.
13
+ */
14
+ export type CloudRuntime = Pick<CloudSession, 'apiUrl' | 'bearer' | 'machineKey' | 'projectKey' | 'repoRoot' | 'checkoutRoot'> & {
15
+ readonly fetch: Fetch;
16
+ /**
17
+ * When everything this runtime is asked to do must be over, in ms since the
18
+ * epoch: a hook runs inside its harness's own limit, retries included.
19
+ * Without one, each request has the usual timeout.
20
+ */
21
+ readonly deadline?: number;
22
+ };
23
+ /** A drain waits at most this long; the cloud allows 25 seconds. */
24
+ export declare const MAX_WAIT_SECONDS = 25;
25
+ /** An answer the cloud gave that was not a success. */
26
+ export declare class CloudApiError extends Error {
27
+ readonly status: number;
28
+ constructor(status: number, message: string);
29
+ }
30
+ /** `work`, unless `signal` gives up on it first: then a timeout, as a request's own would be. */
31
+ export declare function before<T>(work: Promise<T>, signal: AbortSignal): Promise<T>;
32
+ declare const cachedAgent: z.ZodObject<{
33
+ agentId: z.ZodString;
34
+ machineId: z.ZodString;
35
+ }, z.core.$strip>;
36
+ export type CloudAgentRef = z.infer<typeof cachedAgent>;
37
+ declare const cacheSchema: z.ZodObject<{
38
+ agentId: z.ZodString;
39
+ machineId: z.ZodString;
40
+ apiUrl: z.ZodString;
41
+ machineKey: z.ZodString;
42
+ watchingUntil: z.ZodOptional<z.ZodNumber>;
43
+ }, z.core.$strip>;
44
+ export type CloudAgentState = z.infer<typeof cacheSchema>;
45
+ /**
46
+ * One file per agent, so sessions registering at once never overwrite each
47
+ * other's ids. The key is hashed into the name: agent keys hold `:` and are
48
+ * chosen by the runtime, never fit to be a path as written.
49
+ */
50
+ export declare function agentCachePath(repoRoot: string, agentKey: string): string;
51
+ /** What this machine knows of the agent, when it was recorded for this API and machine. */
52
+ export declare function readAgentState(runtime: CloudRuntime, agentKey: string): CloudAgentState | undefined;
53
+ /** Records the agent's ids, or changes what is known of it; a no-op before its ids are known. */
54
+ export declare function updateAgentState(runtime: CloudRuntime, agentKey: string, change: {
55
+ readonly [K in keyof CloudAgentState]?: CloudAgentState[K] | undefined;
56
+ }): void;
57
+ /** A drain's key, held from before it asks until its answer has arrived. */
58
+ export interface DrainTicket {
59
+ readonly key: string;
60
+ /** True when this key's drain may already have happened, so the cloud replays it. */
61
+ readonly replay: boolean;
62
+ /** The answer arrived: nothing left to replay. */
63
+ readonly finish: () => void;
64
+ }
65
+ /**
66
+ * A key for the agent's next drain. Each drain in flight is a file named for
67
+ * its key and its process, removed once answered; one left by a process that
68
+ * has ended had its answer lost, and is taken over (by an atomic rename) so
69
+ * the cloud replays its batch. A key another running process holds is never
70
+ * reused, so two drains can never share one and see one batch twice.
71
+ */
72
+ export declare function takeDrainKey(runtime: CloudRuntime, agentKey: string): DrainTicket;
73
+ export interface AgentRegistration {
74
+ readonly agentKey: string;
75
+ readonly kind: string;
76
+ readonly cwd?: string | undefined;
77
+ }
78
+ /** Registers this machine and the agent on it, idempotently, and caches their ids. */
79
+ export declare function registerCloudAgent(runtime: CloudRuntime, registration: AgentRegistration): Promise<CloudAgentRef>;
80
+ /**
81
+ * Runs `work` as the agent, registering it first when its id is not cached,
82
+ * and once more when the cloud no longer knows the cached one. Any other
83
+ * refusal is the caller's to see: retrying it would only repeat it.
84
+ */
85
+ export declare function asCloudAgent<T>(runtime: CloudRuntime, registration: AgentRegistration, work: (agent: CloudAgentRef) => Promise<T>, onRegistered?: (agent: CloudAgentRef) => Promise<void>): Promise<T>;
86
+ /** Advertises that the agent drains its own messages, as `registerPullEndpoint` does locally. */
87
+ export declare function connectPullEndpoint(runtime: CloudRuntime, agent: CloudAgentRef, agentKey: string, provider: string, capabilities: readonly string[]): Promise<void>;
88
+ /** Promises a running receiver for `ttlSeconds`; while it lasts, only drains take messages. */
89
+ export declare function renewReceiver(runtime: CloudRuntime, agent: CloudAgentRef, ttlSeconds: number): Promise<void>;
90
+ export declare function releaseReceiver(runtime: CloudRuntime, agent: CloudAgentRef): Promise<void>;
91
+ declare const messageSchema: z.ZodObject<{
92
+ id: z.ZodString;
93
+ senderAgentKey: z.ZodNullable<z.ZodString>;
94
+ taskKey: z.ZodNullable<z.ZodString>;
95
+ replyToMessageId: z.ZodNullable<z.ZodString>;
96
+ content: z.ZodString;
97
+ createdAt: z.ZodString;
98
+ deliveredAt: z.ZodNullable<z.ZodString>;
99
+ }, z.core.$strip>;
100
+ type CloudMessage = z.infer<typeof messageSchema>;
101
+ /**
102
+ * Takes the agent's pending messages, waiting up to `waitSeconds` for one.
103
+ * Exactly once per `drainKey`: a retry with the same key replays its batch.
104
+ */
105
+ export declare function drainCloud(runtime: CloudRuntime, agent: CloudAgentRef, drainKey: string, waitSeconds?: number, signal?: AbortSignal): Promise<readonly CloudMessage[]>;
106
+ declare const agentSchema: z.ZodObject<{
107
+ id: z.ZodString;
108
+ agentKey: z.ZodString;
109
+ kind: z.ZodString;
110
+ summary: z.ZodNullable<z.ZodString>;
111
+ status: z.ZodString;
112
+ lastSeenAt: z.ZodString;
113
+ }, z.core.$strip>;
114
+ export type CloudAgent = z.infer<typeof agentSchema>;
115
+ /** Everyone in the organization, as discovery shows them. */
116
+ export declare function listCloudAgents(runtime: CloudRuntime): Promise<readonly CloudAgent[]>;
117
+ /**
118
+ * Drained messages as the inbox renders them: senders and tasks by the keys
119
+ * agents use, which the drain itself returns, so rendering needs no request
120
+ * that could fail after the messages were taken.
121
+ */
122
+ export declare function toDeliverables(messages: readonly CloudMessage[]): DeliverableMessage[];
123
+ declare const claimSchema: z.ZodObject<{
124
+ file: z.ZodString;
125
+ taskKey: z.ZodString;
126
+ title: z.ZodString;
127
+ status: z.ZodString;
128
+ agentKey: z.ZodNullable<z.ZodString>;
129
+ }, z.core.$strip>;
130
+ export type CloudClaim = z.infer<typeof claimSchema>;
131
+ /** Who holds these repository files in the linked project, by the cloud's live claims. */
132
+ export declare function listClaims(runtime: CloudRuntime, files: readonly string[], signal?: AbortSignal): Promise<readonly CloudClaim[]>;
133
+ /** The most tasks the cloud returns at once. */
134
+ export declare const TASK_PAGE = 200;
135
+ declare const taskSchema: z.ZodObject<{
136
+ taskKey: z.ZodString;
137
+ title: z.ZodString;
138
+ status: z.ZodString;
139
+ version: z.ZodNumber;
140
+ agentId: z.ZodNullable<z.ZodString>;
141
+ assignedAgentId: z.ZodNullable<z.ZodString>;
142
+ updatedAt: z.ZodString;
143
+ }, z.core.$strip>;
144
+ export type CloudTask = z.infer<typeof taskSchema>;
145
+ /** The linked project's tasks, most recently updated first, as many as the cloud gives at once. */
146
+ export declare function listCloudTasks(runtime: CloudRuntime): Promise<readonly CloudTask[]>;
147
+ /**
148
+ * Records that a drained message could not be handed to its session, so its
149
+ * sender sees it failed rather than taking silence for delivery.
150
+ */
151
+ export declare function reportDeliveryFailure(runtime: CloudRuntime, agent: CloudAgentRef, messageId: string, detail: string): Promise<void>;
152
+ export {};
@@ -0,0 +1,332 @@
1
+ import { createHash, randomUUID } from 'node:crypto';
2
+ import { mkdirSync, readdirSync, rmSync, readFileSync, renameSync, writeFileSync } from 'node:fs';
3
+ import { hostname } from 'node:os';
4
+ import { dirname, join } from 'node:path';
5
+ import { z } from 'zod';
6
+ import { toDeliverable } from '../domain/pull-inbox.js';
7
+ import { VERSION } from '../version.js';
8
+ import { errorDetail, sameApi, TIMEOUT_MS, url } from './client.js';
9
+ /** A drain waits at most this long; the cloud allows 25 seconds. */
10
+ export const MAX_WAIT_SECONDS = 25;
11
+ /** An answer the cloud gave that was not a success. */
12
+ export class CloudApiError extends Error {
13
+ status;
14
+ constructor(status, message) {
15
+ super(message);
16
+ this.status = status;
17
+ }
18
+ }
19
+ /** `work`, unless `signal` gives up on it first: then a timeout, as a request's own would be. */
20
+ export function before(work, signal) {
21
+ return new Promise((resolve, reject) => {
22
+ const giveUp = () => {
23
+ reject(new DOMException('Concord Cloud did not answer in time.', 'TimeoutError'));
24
+ };
25
+ // Settled either way, so a rejection after giving up is never unhandled.
26
+ work.catch(() => undefined);
27
+ if (signal.aborted) {
28
+ giveUp();
29
+ return;
30
+ }
31
+ signal.addEventListener('abort', giveUp, { once: true });
32
+ work.then(resolve, reject).finally(() => {
33
+ signal.removeEventListener('abort', giveUp);
34
+ });
35
+ });
36
+ }
37
+ async function call(runtime, method, path, schema, body, waitSeconds = 0, signal) {
38
+ // A cold Cloud Run start is the slow case; a long-poll adds its wait.
39
+ const budget = runtime.deadline === undefined
40
+ ? TIMEOUT_MS + waitSeconds * 1000
41
+ : Math.max(0, runtime.deadline - Date.now());
42
+ const timeout = AbortSignal.timeout(budget);
43
+ // Within the same budget: a browser login refreshing its token is a request
44
+ // too, and ends with it rather than keeping a hook's process alive.
45
+ const token = await before(runtime.bearer(timeout), timeout);
46
+ const response = await runtime.fetch(url(runtime.apiUrl, path), {
47
+ method,
48
+ headers: {
49
+ Authorization: `Bearer ${token}`,
50
+ ...(body === undefined ? {} : { 'Content-Type': 'application/json' }),
51
+ },
52
+ ...(body === undefined ? {} : { body: JSON.stringify(body) }),
53
+ signal: signal === undefined ? timeout : AbortSignal.any([timeout, signal]),
54
+ });
55
+ if (!response.ok) {
56
+ throw new CloudApiError(response.status, `Concord Cloud answered ${String(response.status)} to ${method} ${path}: ${await errorDetail(response)}`);
57
+ }
58
+ if (response.status === 204)
59
+ return schema.parse({});
60
+ const raw = await response.json();
61
+ return schema.parse(raw);
62
+ }
63
+ const withId = z.object({ id: z.string() });
64
+ const empty = z.object({});
65
+ const cachedAgent = z.object({ agentId: z.string(), machineId: z.string() });
66
+ const cacheSchema = cachedAgent.extend({
67
+ apiUrl: z.string(),
68
+ machineKey: z.string(),
69
+ /** Until when a running `inbox watch` holds this agent's receiver, in ms. */
70
+ watchingUntil: z.number().optional(),
71
+ });
72
+ /**
73
+ * One file per agent, so sessions registering at once never overwrite each
74
+ * other's ids. The key is hashed into the name: agent keys hold `:` and are
75
+ * chosen by the runtime, never fit to be a path as written.
76
+ */
77
+ export function agentCachePath(repoRoot, agentKey) {
78
+ const name = createHash('sha256').update(agentKey).digest('hex').slice(0, 16);
79
+ return join(repoRoot, '.concord', 'cloud-agents', `${name}.json`);
80
+ }
81
+ /** What this machine knows of the agent, when it was recorded for this API and machine. */
82
+ export function readAgentState(runtime, agentKey) {
83
+ try {
84
+ const raw = JSON.parse(readFileSync(agentCachePath(runtime.repoRoot, agentKey), 'utf8'));
85
+ const parsed = cacheSchema.safeParse(raw);
86
+ return parsed.success &&
87
+ sameApi(parsed.data.apiUrl, runtime.apiUrl) &&
88
+ parsed.data.machineKey === runtime.machineKey
89
+ ? parsed.data
90
+ : undefined;
91
+ }
92
+ catch {
93
+ return undefined;
94
+ }
95
+ }
96
+ /** Records the agent's ids, or changes what is known of it; a no-op before its ids are known. */
97
+ export function updateAgentState(runtime, agentKey, change) {
98
+ const current = readAgentState(runtime, agentKey);
99
+ const next = { ...current, ...change, apiUrl: runtime.apiUrl, machineKey: runtime.machineKey };
100
+ const parsed = cacheSchema.safeParse(next);
101
+ if (!parsed.success)
102
+ return;
103
+ const path = agentCachePath(runtime.repoRoot, agentKey);
104
+ mkdirSync(dirname(path), { recursive: true });
105
+ const temp = `${path}.${String(process.pid)}.tmp`;
106
+ writeFileSync(temp, `${JSON.stringify(parsed.data, null, 2)}\n`);
107
+ renameSync(temp, path);
108
+ }
109
+ function running(pid) {
110
+ try {
111
+ process.kill(pid, 0);
112
+ return true;
113
+ }
114
+ catch (error) {
115
+ // EPERM: it exists, and belongs to someone else.
116
+ return error instanceof Error && 'code' in error && error.code === 'EPERM';
117
+ }
118
+ }
119
+ /**
120
+ * A key for the agent's next drain. Each drain in flight is a file named for
121
+ * its key and its process, removed once answered; one left by a process that
122
+ * has ended had its answer lost, and is taken over (by an atomic rename) so
123
+ * the cloud replays its batch. A key another running process holds is never
124
+ * reused, so two drains can never share one and see one batch twice.
125
+ */
126
+ export function takeDrainKey(runtime, agentKey) {
127
+ const dir = agentCachePath(runtime.repoRoot, agentKey).replace(/\.json$/, '.drains');
128
+ mkdirSync(dir, { recursive: true });
129
+ const ticket = (key, replay) => {
130
+ const path = join(dir, `${key}.${String(process.pid)}`);
131
+ return {
132
+ key,
133
+ replay,
134
+ finish: () => {
135
+ rmSync(path, { force: true });
136
+ },
137
+ };
138
+ };
139
+ for (const name of readdirSync(dir)) {
140
+ const [key, owner] = name.split('.');
141
+ const pid = Number(owner);
142
+ if (key === undefined || (pid !== process.pid && running(pid)))
143
+ continue;
144
+ try {
145
+ renameSync(join(dir, name), join(dir, `${key}.${String(process.pid)}`));
146
+ return ticket(key, true);
147
+ }
148
+ catch {
149
+ // Taken over by another process first.
150
+ }
151
+ }
152
+ const key = randomUUID();
153
+ writeFileSync(join(dir, `${key}.${String(process.pid)}`), '');
154
+ return ticket(key, false);
155
+ }
156
+ /** Registers this machine and the agent on it, idempotently, and caches their ids. */
157
+ export async function registerCloudAgent(runtime, registration) {
158
+ const host = hostname();
159
+ const { machine } = await call(runtime, 'POST', '/v1/machines', z.object({ machine: withId }), {
160
+ machineKey: runtime.machineKey,
161
+ name: host,
162
+ hostname: host,
163
+ platform: process.platform,
164
+ runtimeVersion: VERSION,
165
+ });
166
+ const { agent } = await call(runtime, 'POST', '/v1/agents', z.object({ agent: withId }), {
167
+ agentKey: registration.agentKey,
168
+ kind: registration.kind,
169
+ machineId: machine.id,
170
+ pid: process.pid,
171
+ ...(registration.cwd === undefined ? {} : { cwd: registration.cwd }),
172
+ });
173
+ const ref = { agentId: agent.id, machineId: machine.id };
174
+ updateAgentState(runtime, registration.agentKey, ref);
175
+ return ref;
176
+ }
177
+ /**
178
+ * Runs `work` as the agent, registering it first when its id is not cached,
179
+ * and once more when the cloud no longer knows the cached one. Any other
180
+ * refusal is the caller's to see: retrying it would only repeat it.
181
+ */
182
+ export async function asCloudAgent(runtime, registration, work, onRegistered = () => Promise.resolve()) {
183
+ const register = async () => {
184
+ const agent = await registerCloudAgent(runtime, registration);
185
+ try {
186
+ await onRegistered(agent);
187
+ }
188
+ catch (error) {
189
+ // Not cached until finished, so the next call registers it again.
190
+ rmSync(agentCachePath(runtime.repoRoot, registration.agentKey), { force: true });
191
+ throw error;
192
+ }
193
+ return agent;
194
+ };
195
+ const state = readAgentState(runtime, registration.agentKey);
196
+ if (state === undefined)
197
+ return work(await register());
198
+ const cached = { agentId: state.agentId, machineId: state.machineId };
199
+ try {
200
+ return await work(cached);
201
+ }
202
+ catch (error) {
203
+ if (!(error instanceof CloudApiError) || ![403, 404].includes(error.status))
204
+ throw error;
205
+ if (await agentExists(runtime, cached))
206
+ throw error;
207
+ return work(await register());
208
+ }
209
+ }
210
+ /** Whether the cloud still has this agent, for this caller. */
211
+ async function agentExists(runtime, agent) {
212
+ try {
213
+ await call(runtime, 'GET', `/v1/agents/${agent.agentId}`, z.object({ agent: withId }));
214
+ return true;
215
+ }
216
+ catch (error) {
217
+ if (error instanceof CloudApiError && error.status === 404)
218
+ return false;
219
+ throw error;
220
+ }
221
+ }
222
+ /** Advertises that the agent drains its own messages, as `registerPullEndpoint` does locally. */
223
+ export async function connectPullEndpoint(runtime, agent, agentKey, provider, capabilities) {
224
+ await call(runtime, 'PUT', `/v1/agents/${agent.agentId}/endpoint`, empty, {
225
+ provider,
226
+ transport: 'pull',
227
+ capabilities,
228
+ address: `pull:${agentKey}`,
229
+ // A pull endpoint is never dialled, so it has no credential to hash.
230
+ credentialHash: 'none',
231
+ });
232
+ }
233
+ /** Promises a running receiver for `ttlSeconds`; while it lasts, only drains take messages. */
234
+ export async function renewReceiver(runtime, agent, ttlSeconds) {
235
+ await call(runtime, 'PUT', `/v1/agents/${agent.agentId}/endpoint/receiver`, empty, {
236
+ ttlSeconds,
237
+ });
238
+ }
239
+ export async function releaseReceiver(runtime, agent) {
240
+ await call(runtime, 'DELETE', `/v1/agents/${agent.agentId}/endpoint/receiver`, empty);
241
+ }
242
+ const messageSchema = z.object({
243
+ id: z.string(),
244
+ senderAgentKey: z.string().nullable(),
245
+ taskKey: z.string().nullable(),
246
+ replyToMessageId: z.string().nullable(),
247
+ content: z.string(),
248
+ createdAt: z.string(),
249
+ deliveredAt: z.string().nullable(),
250
+ });
251
+ /**
252
+ * Takes the agent's pending messages, waiting up to `waitSeconds` for one.
253
+ * Exactly once per `drainKey`: a retry with the same key replays its batch.
254
+ */
255
+ export async function drainCloud(runtime, agent, drainKey, waitSeconds = 0, signal) {
256
+ const wait = Math.max(0, Math.min(MAX_WAIT_SECONDS, Math.floor(waitSeconds)));
257
+ const { messages } = await call(runtime, 'POST', '/v1/messages/drain', z.object({ messages: z.array(messageSchema) }), { agentId: agent.agentId, drainKey, waitSeconds: wait }, wait, signal);
258
+ return messages;
259
+ }
260
+ const agentSchema = z.object({
261
+ id: z.string(),
262
+ agentKey: z.string(),
263
+ kind: z.string(),
264
+ summary: z.string().nullable(),
265
+ status: z.string(),
266
+ lastSeenAt: z.string(),
267
+ });
268
+ /** Everyone in the organization, as discovery shows them. */
269
+ export async function listCloudAgents(runtime) {
270
+ const { agents } = await call(runtime, 'GET', '/v1/agents', z.object({ agents: z.array(agentSchema) }));
271
+ return agents;
272
+ }
273
+ /**
274
+ * Drained messages as the inbox renders them: senders and tasks by the keys
275
+ * agents use, which the drain itself returns, so rendering needs no request
276
+ * that could fail after the messages were taken.
277
+ */
278
+ export function toDeliverables(messages) {
279
+ return messages.map((message) => toDeliverable({
280
+ messageId: message.id,
281
+ senderAgentId: message.senderAgentKey ?? 'unknown',
282
+ taskId: message.taskKey,
283
+ content: message.content,
284
+ replyToMessageId: message.replyToMessageId,
285
+ createdAt: message.createdAt,
286
+ deliveredAt: message.deliveredAt,
287
+ }));
288
+ }
289
+ const claimSchema = z.object({
290
+ file: z.string(),
291
+ taskKey: z.string(),
292
+ title: z.string(),
293
+ status: z.string(),
294
+ agentKey: z.string().nullable(),
295
+ });
296
+ /** Who holds these repository files in the linked project, by the cloud's live claims. */
297
+ export async function listClaims(runtime, files, signal) {
298
+ const query = new URLSearchParams({ projectKey: runtime.projectKey });
299
+ for (const file of files)
300
+ query.append('file', file);
301
+ const { claims } = await call(runtime, 'GET', `/v1/claims?${query.toString()}`, z.object({ claims: z.array(claimSchema) }), undefined, 0, signal);
302
+ return claims;
303
+ }
304
+ /** The most tasks the cloud returns at once. */
305
+ export const TASK_PAGE = 200;
306
+ const taskSchema = z.object({
307
+ taskKey: z.string(),
308
+ title: z.string(),
309
+ status: z.string(),
310
+ version: z.number(),
311
+ agentId: z.string().nullable(),
312
+ assignedAgentId: z.string().nullable(),
313
+ updatedAt: z.string(),
314
+ });
315
+ /** The linked project's tasks, most recently updated first, as many as the cloud gives at once. */
316
+ export async function listCloudTasks(runtime) {
317
+ const query = new URLSearchParams({ projectKey: runtime.projectKey, limit: String(TASK_PAGE) });
318
+ const { tasks } = await call(runtime, 'GET', `/v1/tasks?${query.toString()}`, z.object({ tasks: z.array(taskSchema) }));
319
+ return tasks;
320
+ }
321
+ /**
322
+ * Records that a drained message could not be handed to its session, so its
323
+ * sender sees it failed rather than taking silence for delivery.
324
+ */
325
+ export async function reportDeliveryFailure(runtime, agent, messageId, detail) {
326
+ await call(runtime, 'POST', `/v1/messages/${messageId}/failure`, z.object({}).loose(), {
327
+ agentId: agent.agentId,
328
+ errorCode: 'target_not_promptable',
329
+ errorDetail: detail.slice(0, 5000),
330
+ });
331
+ }
332
+ //# sourceMappingURL=runtime.js.map