@1agents/acp-service 0.1.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.
@@ -0,0 +1,38 @@
1
+ export type HistoryTurnRef = {
2
+ turnId: string;
3
+ clientRequestId?: string;
4
+ runtimeRequestId?: string;
5
+ promptMessageId?: string;
6
+ promptText?: string;
7
+ };
8
+ export type HistoryItem = {
9
+ kind: string;
10
+ turnId?: string;
11
+ text?: string;
12
+ };
13
+ export type RuntimeTurnResult = {
14
+ prompt_message_id?: string;
15
+ };
16
+ export type HistoryToolUse = {
17
+ input?: unknown;
18
+ raw_input?: string;
19
+ kind?: string;
20
+ locations?: Array<{
21
+ path?: string;
22
+ }>;
23
+ };
24
+ /** Merge ACP locations into history input so Cursor's empty-input file tools keep their paths. */
25
+ export declare function historyToolInput(tool: HistoryToolUse): unknown;
26
+ /** Prefer a journal/runtime id that agent_turns can ResolveTurnID. */
27
+ export declare function resolvableTurnId(turn: HistoryTurnRef): string;
28
+ /**
29
+ * Map a persisted User.id onto the turn_results key (runtime request id).
30
+ * Keys are request ids; User.id may instead be prompt_message_id.
31
+ */
32
+ export declare function resolveRuntimeTurnId(userId: string | undefined, turnResults: Record<string, RuntimeTurnResult | undefined>): string | undefined;
33
+ /**
34
+ * Copy a resolvable turnId onto every item in a user→assistant slice.
35
+ * Already-stamped user items keep their id; unstamped users match journal
36
+ * turns by prompt text, then unused turns in chronological order.
37
+ */
38
+ export declare function stampHistoryTurnIds<T extends HistoryItem>(items: T[], turns: HistoryTurnRef[]): T[];
@@ -0,0 +1,116 @@
1
+ function hasStructuredPath(input) {
2
+ return [
3
+ 'path',
4
+ 'file_path',
5
+ 'filePath',
6
+ 'file',
7
+ 'target_file',
8
+ 'targetFile',
9
+ 'paths',
10
+ 'files',
11
+ ].some((key) => {
12
+ const value = input[key];
13
+ return typeof value === 'string'
14
+ ? value.trim().length > 0
15
+ : Array.isArray(value) && value.length > 0;
16
+ });
17
+ }
18
+ function parseRawInput(raw) {
19
+ if (typeof raw !== 'string' || !raw.trim() || raw === '{}')
20
+ return undefined;
21
+ try {
22
+ const parsed = JSON.parse(raw);
23
+ if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) {
24
+ return { ...parsed };
25
+ }
26
+ }
27
+ catch {
28
+ // raw_input is a display string
29
+ }
30
+ return undefined;
31
+ }
32
+ function parseObjectInput(tool) {
33
+ if (tool.input && typeof tool.input === 'object' && !Array.isArray(tool.input)) {
34
+ return { ...tool.input };
35
+ }
36
+ return parseRawInput(tool.raw_input);
37
+ }
38
+ function extractLocations(tool) {
39
+ return (tool.locations ?? [])
40
+ .map((location) => location.path?.trim())
41
+ .filter((path) => !!path);
42
+ }
43
+ /** Merge ACP locations into history input so Cursor's empty-input file tools keep their paths. */
44
+ export function historyToolInput(tool) {
45
+ const input = parseObjectInput(tool);
46
+ const paths = extractLocations(tool);
47
+ if (paths.length === 0)
48
+ return input ?? tool.input ?? {};
49
+ const next = input ?? {};
50
+ if (!hasStructuredPath(next)) {
51
+ if (paths.length === 1)
52
+ next.path = paths[0];
53
+ else
54
+ next.paths = paths;
55
+ }
56
+ return next;
57
+ }
58
+ /** Prefer a journal/runtime id that agent_turns can ResolveTurnID. */
59
+ export function resolvableTurnId(turn) {
60
+ return turn.turnId || turn.clientRequestId || turn.runtimeRequestId || turn.promptMessageId || '';
61
+ }
62
+ /**
63
+ * Map a persisted User.id onto the turn_results key (runtime request id).
64
+ * Keys are request ids; User.id may instead be prompt_message_id.
65
+ */
66
+ export function resolveRuntimeTurnId(userId, turnResults) {
67
+ if (!userId)
68
+ return undefined;
69
+ if (turnResults[userId])
70
+ return userId;
71
+ for (const [requestId, result] of Object.entries(turnResults)) {
72
+ if (result?.prompt_message_id === userId)
73
+ return requestId;
74
+ }
75
+ return undefined;
76
+ }
77
+ /**
78
+ * Copy a resolvable turnId onto every item in a user→assistant slice.
79
+ * Already-stamped user items keep their id; unstamped users match journal
80
+ * turns by prompt text, then unused turns in chronological order.
81
+ */
82
+ export function stampHistoryTurnIds(items, turns) {
83
+ if (items.length === 0)
84
+ return items;
85
+ const unused = turns.filter((turn) => resolvableTurnId(turn));
86
+ let currentTurnId;
87
+ let changed = false;
88
+ const next = items.map((item) => {
89
+ if (item.kind === 'user') {
90
+ if (item.turnId) {
91
+ currentTurnId = item.turnId;
92
+ const index = unused.findIndex((turn) => turnOwnsHistoryId(turn, item.turnId));
93
+ if (index >= 0)
94
+ unused.splice(index, 1);
95
+ }
96
+ else {
97
+ const byPrompt = unused.findIndex((turn) => !!turn.promptText && turn.promptText === item.text);
98
+ const turn = byPrompt >= 0 ? unused.splice(byPrompt, 1)[0] : unused.shift();
99
+ currentTurnId = turn ? resolvableTurnId(turn) : undefined;
100
+ }
101
+ }
102
+ if (!currentTurnId || item.turnId)
103
+ return item;
104
+ changed = true;
105
+ return { ...item, turnId: currentTurnId };
106
+ });
107
+ return changed ? next : items;
108
+ }
109
+ function turnOwnsHistoryId(turn, historyTurnId) {
110
+ if (!historyTurnId)
111
+ return false;
112
+ return (turn.turnId === historyTurnId ||
113
+ turn.clientRequestId === historyTurnId ||
114
+ turn.runtimeRequestId === historyTurnId ||
115
+ turn.promptMessageId === historyTurnId);
116
+ }
@@ -0,0 +1,10 @@
1
+ /**
2
+ * @1agents/acp-service
3
+ *
4
+ * DreamMate Network ACP Agent Runtime Service.
5
+ */
6
+ export { buildManifest, ACP_CAPABILITIES, DEFAULT_ACP_PORT } from './manifest.js';
7
+ export type { AccessDescriptor, NetworkService, NodeIdentity, NodeManifest, Reachability } from './manifest.js';
8
+ export { createAcpServer, serveAcpService } from './server.js';
9
+ export type { ServerOptions } from './server.js';
10
+ export { attachBridgeServer, activeSessions, sessionBackgroundTasks, killAllManagedAgents } from './bridge.js';
@@ -0,0 +1,8 @@
1
+ /**
2
+ * @1agents/acp-service
3
+ *
4
+ * DreamMate Network ACP Agent Runtime Service.
5
+ */
6
+ export { buildManifest, ACP_CAPABILITIES, DEFAULT_ACP_PORT } from './manifest.js';
7
+ export { createAcpServer, serveAcpService } from './server.js';
8
+ export { attachBridgeServer, activeSessions, sessionBackgroundTasks, killAllManagedAgents } from './bridge.js';
@@ -0,0 +1,19 @@
1
+ /**
2
+ * acp-service 作为 DreamMate Network Service 时的 manifest 构建。
3
+ *
4
+ * 节点身份来自 `@1agents/dreammate-node`(优先 tailnet,回退本地),
5
+ * 保证整台机器上的所有服务共享同一个 node_id 与 name。
6
+ */
7
+ import { nodeIdentity, type NodeIdentity } from '@1agents/dreammate-node';
8
+ import { PROTOCOL_VERSION, type AccessDescriptor, type NodeManifest, type Reachability, type Service as NetworkService } from '@1agents/dreammate-network';
9
+ export { nodeIdentity, PROTOCOL_VERSION };
10
+ export type { AccessDescriptor, NetworkService, NodeIdentity, NodeManifest, Reachability };
11
+ /**
12
+ * 默认 ACP 运行时端口(36xx2 服务系列约定)
13
+ */
14
+ export declare const DEFAULT_ACP_PORT = 36812;
15
+ /**
16
+ * 该 Agent Runtime Service 支持的能力列表
17
+ */
18
+ export declare const ACP_CAPABILITIES: readonly ["agent.prompt", "agent.session", "agent.cancel", "agent.mode", "runtime.claude", "runtime.grok", "runtime.codex"];
19
+ export declare function buildManifest(baseUrl: string): Promise<NodeManifest>;
@@ -0,0 +1,66 @@
1
+ /**
2
+ * acp-service 作为 DreamMate Network Service 时的 manifest 构建。
3
+ *
4
+ * 节点身份来自 `@1agents/dreammate-node`(优先 tailnet,回退本地),
5
+ * 保证整台机器上的所有服务共享同一个 node_id 与 name。
6
+ */
7
+ import { nodeIdentity } from '@1agents/dreammate-node';
8
+ import { PROTOCOL_VERSION, } from '@1agents/dreammate-network';
9
+ export { nodeIdentity, PROTOCOL_VERSION };
10
+ /**
11
+ * 默认 ACP 运行时端口(36xx2 服务系列约定)
12
+ */
13
+ export const DEFAULT_ACP_PORT = 36812;
14
+ /**
15
+ * 该 Agent Runtime Service 支持的能力列表
16
+ */
17
+ export const ACP_CAPABILITIES = [
18
+ 'agent.prompt',
19
+ 'agent.session',
20
+ 'agent.cancel',
21
+ 'agent.mode',
22
+ 'runtime.claude',
23
+ 'runtime.grok',
24
+ 'runtime.codex',
25
+ ];
26
+ export async function buildManifest(baseUrl) {
27
+ const identity = await nodeIdentity();
28
+ const url = new URL(baseUrl);
29
+ const port = url.port || String(DEFAULT_ACP_PORT);
30
+ const atWs = (host) => ({
31
+ protocol: 'acp',
32
+ base_url: `ws://${host}:${port}`,
33
+ });
34
+ const atHttp = (host) => ({
35
+ protocol: 'http',
36
+ base_url: `http://${host}:${port}`,
37
+ });
38
+ // MagicDNS 名在前(可读、IP 变了也不用改),tailnet IP 兜底
39
+ const access = [
40
+ ...(identity.dnsName ? [atWs(identity.dnsName), atHttp(identity.dnsName)] : []),
41
+ ...(identity.ipv4 && identity.ipv4 !== identity.dnsName
42
+ ? [atWs(identity.ipv4), atHttp(identity.ipv4)]
43
+ : []),
44
+ ];
45
+ return {
46
+ node_id: identity.node_id,
47
+ name: identity.name,
48
+ type: identity.type,
49
+ tailscale_name: identity.dnsName ?? process.env.DREAMMATE_TAILSCALE_NAME?.trim() ?? null,
50
+ online: true,
51
+ metadata: {
52
+ protocol_version: PROTOCOL_VERSION,
53
+ identity_source: identity.source,
54
+ service_type: 'agent_runtime',
55
+ },
56
+ services: [
57
+ {
58
+ id: 'acp-service',
59
+ name: 'acp-service',
60
+ kind: 'agent_runtime',
61
+ capabilities: [...ACP_CAPABILITIES],
62
+ access: access.length > 0 ? access : [atWs(url.hostname), atHttp(url.hostname)],
63
+ },
64
+ ],
65
+ };
66
+ }
@@ -0,0 +1,25 @@
1
+ /**
2
+ * acp-service HTTP 与 WebSocket 复合服务。
3
+ *
4
+ * 单端口复用:
5
+ * - GET /health: 供 dreammate-node 与探活方检查运行状态
6
+ * - GET /manifest: 返回符合 DreamMate Network 规范的节点能力清单
7
+ * - WebSocket: 处理与客户端(Web Chat、IM 机器人等)的全双工 ACP 会话
8
+ */
9
+ import http from 'node:http';
10
+ import { attachBridgeServer } from './bridge.js';
11
+ export interface ServerOptions {
12
+ port?: number;
13
+ host?: string;
14
+ report?: boolean;
15
+ }
16
+ export declare function createAcpServer(): {
17
+ server: http.Server;
18
+ bridge: ReturnType<typeof attachBridgeServer>;
19
+ };
20
+ export declare function serveAcpService(options?: ServerOptions): Promise<{
21
+ server: http.Server;
22
+ bridge: ReturnType<typeof attachBridgeServer>;
23
+ port: number;
24
+ close: () => Promise<void>;
25
+ }>;
@@ -0,0 +1,109 @@
1
+ /**
2
+ * acp-service HTTP 与 WebSocket 复合服务。
3
+ *
4
+ * 单端口复用:
5
+ * - GET /health: 供 dreammate-node 与探活方检查运行状态
6
+ * - GET /manifest: 返回符合 DreamMate Network 规范的节点能力清单
7
+ * - WebSocket: 处理与客户端(Web Chat、IM 机器人等)的全双工 ACP 会话
8
+ */
9
+ import http from 'node:http';
10
+ import { nodeIdentity } from '@1agents/dreammate-node';
11
+ import { reportAndHoldRegistration } from '@1agents/dreammate-node/client';
12
+ import { buildManifest, ACP_CAPABILITIES, DEFAULT_ACP_PORT } from './manifest.js';
13
+ import { attachBridgeServer, activeSessions, sessionBackgroundTasks, killAllManagedAgents } from './bridge.js';
14
+ const json = (res, status, body) => {
15
+ const payload = JSON.stringify(body, null, 2);
16
+ res.writeHead(status, {
17
+ 'content-type': 'application/json; charset=utf-8',
18
+ 'content-length': Buffer.byteLength(payload),
19
+ });
20
+ res.end(payload);
21
+ };
22
+ export function createAcpServer() {
23
+ const server = http.createServer((req, res) => {
24
+ void (async () => {
25
+ try {
26
+ const url = new URL(req.url ?? '/', `http://${req.headers.host ?? 'localhost'}`);
27
+ const { pathname } = url;
28
+ const identity = await nodeIdentity();
29
+ if (req.method === 'GET' && pathname === '/health') {
30
+ return json(res, 200, {
31
+ status: 'ok',
32
+ node_id: identity.node_id,
33
+ service: 'acp-service',
34
+ kind: 'agent_runtime',
35
+ sessions: activeSessions.size,
36
+ background_tasks: sessionBackgroundTasks.size,
37
+ uptime: process.uptime(),
38
+ });
39
+ }
40
+ if (req.method === 'GET' && pathname === '/manifest') {
41
+ const baseUrl = `http://${req.headers.host ?? 'localhost'}`;
42
+ const manifest = await buildManifest(baseUrl);
43
+ return json(res, 200, manifest);
44
+ }
45
+ if (req.method === 'GET' && pathname === '/services') {
46
+ return json(res, 200, {
47
+ service: 'acp-service',
48
+ active_sessions: activeSessions.size,
49
+ background_tasks: sessionBackgroundTasks.size,
50
+ });
51
+ }
52
+ json(res, 404, { error: `no route: ${req.method} ${pathname}` });
53
+ }
54
+ catch (error) {
55
+ json(res, 500, { error: error instanceof Error ? error.message : String(error) });
56
+ }
57
+ })();
58
+ });
59
+ const bridge = attachBridgeServer(server);
60
+ return { server, bridge };
61
+ }
62
+ export async function serveAcpService(options = {}) {
63
+ const { server, bridge } = createAcpServer();
64
+ const host = options.host ?? '0.0.0.0';
65
+ const wantedPort = options.port ?? DEFAULT_ACP_PORT;
66
+ await new Promise((resolve, reject) => {
67
+ server.once('error', (err) => {
68
+ if (err.code === 'EADDRINUSE') {
69
+ reject(new Error(`端口 ${wantedPort} 已被占用。可换端口:--port <n>;或检查占用进程:lsof -nP -iTCP:${wantedPort} -sTCP:LISTEN`));
70
+ }
71
+ else {
72
+ reject(err);
73
+ }
74
+ });
75
+ server.listen(wantedPort, host, resolve);
76
+ });
77
+ const { port } = server.address();
78
+ const identity = await nodeIdentity();
79
+ const reachability = host === '127.0.0.1' || host === 'localhost' || host === '::1' ? 'localhost' : 'network';
80
+ const reported = options.report === false
81
+ ? undefined
82
+ : await reportAndHoldRegistration({
83
+ id: 'acp-service',
84
+ name: 'acp-service',
85
+ kind: 'agent_runtime',
86
+ capabilities: [...ACP_CAPABILITIES],
87
+ port,
88
+ reachability,
89
+ health: '/health',
90
+ });
91
+ console.log(`acp-service — node ${identity.name} (${identity.node_id})`);
92
+ console.log(` HTTP: http://${host}:${port}/manifest`);
93
+ console.log(` Health: http://${host}:${port}/health`);
94
+ console.log(` WebSocket: ws://${host}:${port}/`);
95
+ console.log(` capabilities: ${ACP_CAPABILITIES.join(', ')}`);
96
+ if (reported) {
97
+ console.log(reported.ok
98
+ ? ` 已向本机 node agent 报备(reachability=${reachability})`
99
+ : ` 未报备:${reported.reason}(node-agent 未就绪时不影响本服务独立提供能力)`);
100
+ }
101
+ const close = async () => {
102
+ await new Promise((resolve) => server.close(() => resolve()));
103
+ try {
104
+ await killAllManagedAgents();
105
+ }
106
+ catch { }
107
+ };
108
+ return { server, bridge, port, close };
109
+ }
package/package.json ADDED
@@ -0,0 +1,61 @@
1
+ {
2
+ "name": "@1agents/acp-service",
3
+ "version": "0.1.0",
4
+ "description": "DreamMate Network ACP Agent Runtime Service: cross-agent execution runtime for Claude Code, Grok, Codex and ACP-compatible agents.",
5
+ "keywords": [
6
+ "dreammate",
7
+ "acp",
8
+ "agent-runtime",
9
+ "claude-code",
10
+ "grok",
11
+ "codex"
12
+ ],
13
+ "license": "MIT",
14
+ "repository": {
15
+ "type": "git",
16
+ "url": "git+https://github.com/scottzx/acp-service.git"
17
+ },
18
+ "publishConfig": {
19
+ "access": "public",
20
+ "registry": "https://registry.npmjs.org"
21
+ },
22
+ "type": "module",
23
+ "main": "./dist/src/index.js",
24
+ "types": "./dist/src/index.d.ts",
25
+ "exports": {
26
+ ".": {
27
+ "types": "./dist/src/index.d.ts",
28
+ "import": "./dist/src/index.js"
29
+ },
30
+ "./package.json": "./package.json"
31
+ },
32
+ "bin": {
33
+ "acp-service": "dist/bin/acp-service.js"
34
+ },
35
+ "files": [
36
+ "dist",
37
+ "README.md"
38
+ ],
39
+ "scripts": {
40
+ "build": "tsc -p tsconfig.build.json",
41
+ "typecheck": "tsc -p tsconfig.json --noEmit",
42
+ "test": "node --import tsx --test test/*.test.ts",
43
+ "prepack": "npm run build",
44
+ "start": "tsx bin/acp-service.ts"
45
+ },
46
+ "engines": {
47
+ "node": ">=22.5"
48
+ },
49
+ "dependencies": {
50
+ "@1agents/dreammate-network": "^0.3.1",
51
+ "@1agents/dreammate-node": "^0.4.0",
52
+ "@scottzx/1acp": "^0.14.0",
53
+ "ws": "^8.18.0"
54
+ },
55
+ "devDependencies": {
56
+ "@types/node": "^22.10.2",
57
+ "@types/ws": "^8.5.14",
58
+ "tsx": "^4.19.2",
59
+ "typescript": "^5.7.2"
60
+ }
61
+ }