@1agents/acp-service 0.11.0 → 0.11.2
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.
- package/dist/bin/a2a.js +1 -1
- package/dist/src/a2a/executor.js +18 -2
- package/dist/src/a2a/gateway.d.ts +9 -0
- package/dist/src/a2a/gateway.js +29 -0
- package/dist/src/a2a/index.d.ts +2 -0
- package/dist/src/a2a/index.js +1 -0
- package/dist/src/a2a/model-catalog.d.ts +30 -0
- package/dist/src/a2a/model-catalog.js +15 -0
- package/dist/src/a2a/server.js +32 -0
- package/dist/src/a2a/types.d.ts +3 -0
- package/dist/src/acp-connection.js +33 -0
- package/dist/src/bridge.js +44 -1
- package/dist/src/capacity-queue.d.ts +3 -1
- package/dist/src/capacity-queue.js +4 -0
- package/package.json +2 -1
- package/skills/acp-service/SKILL.md +1 -1
- package/skills/acp-service/references/a2a.md +2 -1
- package/vendor/dsh/README.md +2 -0
- package/vendor/dsh/a2a-executor.d.ts +59 -1
- package/vendor/dsh/a2a-executor.js +134 -12
- package/vendor/dsh/a2a.js +1 -0
- package/vendor/dsh/adapter.d.ts +6 -0
- package/vendor/dsh/adapter.js +23 -0
- package/vendor/dsh/index.js +29 -0
- package/vendor/dsh/sync-global.d.ts +19 -0
- package/vendor/dsh/sync-global.js +81 -0
package/dist/bin/a2a.js
CHANGED
|
@@ -17,7 +17,7 @@ export async function runA2ACli(args) {
|
|
|
17
17
|
|
|
18
18
|
invoke reads a JSON parameters object from stdin. Credentials stay in the
|
|
19
19
|
gateway config file (chmod 600), outside tool arguments. Remote cwd is absolute.
|
|
20
|
-
Methods: remote_agent_preflight, remote_agent_spawn, remote_agent_get, remote_agent_message,
|
|
20
|
+
Methods: remote_agent_preflight, remote_agent_model_catalog, remote_agent_spawn, remote_agent_get, remote_agent_message,
|
|
21
21
|
remote_agent_cancel, remote_agent_close, remote_agent_sessions, remote_agent_list, remote_agent_inbox, remote_agent_ack,
|
|
22
22
|
session_bind, session_send, session_delivery_get, session_delivery_resolve,
|
|
23
23
|
execution_project_scan, execution_project_list,
|
package/dist/src/a2a/executor.js
CHANGED
|
@@ -40,7 +40,22 @@ export function validateA2AExecutionOptions(options) {
|
|
|
40
40
|
class RoleSkillLoadingError extends Error {
|
|
41
41
|
constructor(cause) { super('Role skills could not be loaded or verified; the model was not started', { cause }); }
|
|
42
42
|
}
|
|
43
|
-
const sessionFailureCodes = new Set(['SESSION_NOT_FOUND', 'SESSION_DELETED', 'SESSION_CLOSED', 'SESSION_CONFLICT', 'SESSION_ATTACH_IN_PROGRESS', 'MODEL_UNAVAILABLE', 'MODEL_SELECTION_UNSUPPORTED']);
|
|
43
|
+
const sessionFailureCodes = new Set(['SESSION_NOT_FOUND', 'SESSION_DELETED', 'SESSION_CLOSED', 'SESSION_CONFLICT', 'SESSION_ATTACH_IN_PROGRESS', 'MODEL_UNAVAILABLE', 'MODEL_SELECTION_UNSUPPORTED', 'UNKNOWN_MODEL_OR_GROUP']);
|
|
44
|
+
/** Host-authored model ids only. A mismatch keeps the static sentence and drops whatever else the error carried. */
|
|
45
|
+
const MODEL_FAILURE_MESSAGE = /^(?:Unknown model or routing group: [A-Za-z0-9][A-Za-z0-9._:/@+-]*(?:\. Available: [A-Za-z0-9][A-Za-z0-9._:/@+-]*(?:, [A-Za-z0-9][A-Za-z0-9._:/@+-]*)*)?|The requested model is not in the DSH model catalog\.|DSH did not select [A-Za-z0-9][A-Za-z0-9._:/@+-]*)$/;
|
|
46
|
+
function modelFailureMessage(error, code) {
|
|
47
|
+
if (code !== 'UNKNOWN_MODEL_OR_GROUP' && code !== 'MODEL_UNAVAILABLE' && code !== 'MODEL_SELECTION_UNSUPPORTED')
|
|
48
|
+
return undefined;
|
|
49
|
+
const message = error && typeof error === 'object' && typeof error.message === 'string'
|
|
50
|
+
? error.message : '';
|
|
51
|
+
if (MODEL_FAILURE_MESSAGE.test(message))
|
|
52
|
+
return message;
|
|
53
|
+
if (code === 'UNKNOWN_MODEL_OR_GROUP')
|
|
54
|
+
return 'Unknown model or routing group.';
|
|
55
|
+
if (code === 'MODEL_SELECTION_UNSUPPORTED')
|
|
56
|
+
return 'provider and model apply only to standard presets';
|
|
57
|
+
return 'The requested model is not in the DSH model catalog.';
|
|
58
|
+
}
|
|
44
59
|
function sessionFailureCode(error) {
|
|
45
60
|
const seen = new Set();
|
|
46
61
|
const queue = [error];
|
|
@@ -429,7 +444,8 @@ export class A2ASessionExecutor {
|
|
|
429
444
|
resultMetadata.validation = { status: 'failed', code: 'result-record-write-failed' };
|
|
430
445
|
delete resultMetadata.recordPath;
|
|
431
446
|
}
|
|
432
|
-
|
|
447
|
+
const modelCode = sessionFailureCode(error);
|
|
448
|
+
status(controller.signal.aborted ? TaskState.TASK_STATE_CANCELED : TaskState.TASK_STATE_FAILED, capacityFailure?.message ?? modelFailureMessage(error, modelCode) ?? returnedFailureMessage ?? safe.message, safe);
|
|
433
449
|
}
|
|
434
450
|
finally {
|
|
435
451
|
// Release failures retain the durable reservation and cannot strand close().
|
|
@@ -153,6 +153,13 @@ export declare const REMOTE_AGENT_METHODS: {
|
|
|
153
153
|
originSessionId: z.ZodString;
|
|
154
154
|
}, z.core.$strict>>;
|
|
155
155
|
};
|
|
156
|
+
remote_agent_model_catalog: {
|
|
157
|
+
description: string;
|
|
158
|
+
parameters: z.core.ZodStandardJSONSchemaPayload<z.ZodObject<{
|
|
159
|
+
remote: z.ZodString;
|
|
160
|
+
originSessionId: z.ZodString;
|
|
161
|
+
}, z.core.$strict>>;
|
|
162
|
+
};
|
|
156
163
|
remote_agent_spawn: {
|
|
157
164
|
description: string;
|
|
158
165
|
parameters: z.core.ZodStandardJSONSchemaPayload<z.ZodObject<{
|
|
@@ -1186,6 +1193,8 @@ export declare class RemoteAgentGateway {
|
|
|
1186
1193
|
private client;
|
|
1187
1194
|
private auth;
|
|
1188
1195
|
private preflight;
|
|
1196
|
+
/** Standard routes on the execution host. Does not create a session or send a prompt. */
|
|
1197
|
+
private modelCatalog;
|
|
1189
1198
|
/** Host extensions sit beside the JSONRPC endpoint the remote advertises, and only on its configured origin. */
|
|
1190
1199
|
private hostRoute;
|
|
1191
1200
|
/** One verified artifact, read from the host that produced it and checked against the recorded receipt again here. */
|
package/dist/src/a2a/gateway.js
CHANGED
|
@@ -14,6 +14,7 @@ import { A2AAutomation, automationConfigSchema, createAutomationServer } from '.
|
|
|
14
14
|
import { sessionHostSchema } from './session-hosts.js';
|
|
15
15
|
import { SessionDelivery, sessionBindSchema, sessionSendSchema, sessionMessageSchema, sessionResolveSchema } from './session-delivery.js';
|
|
16
16
|
import { artifactLinks, formatNotice } from './notices.js';
|
|
17
|
+
import { a2aModelCatalogSchema } from './model-catalog.js';
|
|
17
18
|
import { a2aPreflightInputSchema, a2aPreflightRequirementsSchema, a2aPreflightReportSchema } from './preflight.js';
|
|
18
19
|
import { a2aResultContractSchema } from './result-metadata.js';
|
|
19
20
|
import { ARTIFACT_CONTENT_LIMIT } from './artifact-content.js';
|
|
@@ -110,6 +111,7 @@ const spawnSchema = z.object({ ...originFields, remote: string, prompt,
|
|
|
110
111
|
provider: string.optional(), model: string.optional(), initiatedBy: actorSchema.optional(),
|
|
111
112
|
}).strict();
|
|
112
113
|
const preflightSchema = a2aPreflightInputSchema.extend({ ...originFields, remote: string }).strict();
|
|
114
|
+
const modelCatalogQuerySchema = z.object({ ...originFields, remote: string }).strict();
|
|
113
115
|
const taskSchema = z.object(taskFields).strict();
|
|
114
116
|
const messageSchema = z.object({ ...taskFields, prompt, initiatedBy: actorSchema.optional(), clientRequestId: string.optional(), roleId: string.optional(), preflight: a2aPreflightRequirementsSchema.optional(), resultContract: a2aResultContractSchema.optional(), lifecycle: sessionLifecycleSchema.optional(), autoResume: z.boolean().optional(), provider: string.optional(), model: string.optional() }).strict();
|
|
115
117
|
const closeSchema = z.object({ ...originFields, remote: string, taskId: string.optional(), contextId: string.optional(), sessionId: string.optional(), mode: z.enum(['close', 'delete']).optional(), force: z.boolean().optional(), clientRequestId: string.optional() }).strict();
|
|
@@ -162,6 +164,7 @@ const EXECUTION_METHODS = {
|
|
|
162
164
|
export const REMOTE_AGENT_METHODS = {
|
|
163
165
|
...EXECUTION_METHODS,
|
|
164
166
|
remote_agent_preflight: { description: '在执行宿主检查真实 cwd、任务可写目录和指定运行时依赖,不创建会话、不调用模型。ok=false 时修复检查项后再派单;spawn 的 preflight 还会在受理前重检。', parameters: z.toJSONSchema(preflightSchema) },
|
|
167
|
+
remote_agent_model_catalog: { description: '读取执行宿主 standard 预设当前可选的 provider 与 model,含默认路由和 routing group。不创建会话、不调用模型。填 remote_agent_spawn 或 remote_agent_message 时,provider 用 groups[].id,model 用其中的 models[].id。', parameters: z.toJSONSchema(modelCatalogQuerySchema) },
|
|
165
168
|
remote_agent_spawn: { description: '在配置的远端 DSH 工作目录中派发独立任务,立即返回 taskId。prompt 必须包含完整上下文。cwd 是远端绝对路径;每次 spawn 创建新会话。完成事件进入 originSessionId 的持久收件箱。可选 lifecycle 省略时为 one-shot:完成、失败或取消后普通关闭进程,之后 message 用 session/load 接回;runtime 仍是 persistent。需要进程常驻等追问时显式传 mode persistent。provider 与 model 只用于 standard 等非 oneagents-acp-* 预设,须一起传;宿主模型目录里没有时任务失败,不退回默认模型;省略时用 DSH 当时的默认模型。', parameters: z.toJSONSchema(spawnSchema) },
|
|
166
169
|
remote_agent_get: { description: '查询当前主会话派发的远端任务。离线时返回缓存与 stale 标记,离线不等于任务失败。进程名额排队时 state 仍是 submitted,并带 capacity 的队列位置和已等时长,以及 taskSlot 与 processSlot。', parameters: z.toJSONSchema(taskSchema) },
|
|
167
170
|
remote_agent_cancel: { description: '取消指定远端任务,只取消这项任务自己的执行。不能释放已经完成的会话进程;释放进程用 remote_agent_close。', parameters: z.toJSONSchema(taskSchema) },
|
|
@@ -1168,6 +1171,28 @@ export class RemoteAgentGateway {
|
|
|
1168
1171
|
this.controllers.delete(controller);
|
|
1169
1172
|
}
|
|
1170
1173
|
}
|
|
1174
|
+
/** Standard routes on the execution host. Does not create a session or send a prompt. */
|
|
1175
|
+
async modelCatalog(remote) {
|
|
1176
|
+
const config = this.config.remotes[remote];
|
|
1177
|
+
if (!config)
|
|
1178
|
+
throw new Error(`Unknown remote: ${remote}`);
|
|
1179
|
+
const url = await this.hostRoute(remote, config.url, '/model-catalog');
|
|
1180
|
+
const controller = new AbortController();
|
|
1181
|
+
this.controllers.add(controller);
|
|
1182
|
+
try {
|
|
1183
|
+
const response = await fetch(url, { method: 'POST', redirect: 'error',
|
|
1184
|
+
headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${config.token}` },
|
|
1185
|
+
body: '{}', signal: AbortSignal.any([controller.signal, AbortSignal.timeout(20_000)]) });
|
|
1186
|
+
if (!response.ok) {
|
|
1187
|
+
await response.body?.cancel();
|
|
1188
|
+
throw new Error(`Remote model catalog failed (HTTP ${response.status})`);
|
|
1189
|
+
}
|
|
1190
|
+
return a2aModelCatalogSchema.parse(await response.json());
|
|
1191
|
+
}
|
|
1192
|
+
finally {
|
|
1193
|
+
this.controllers.delete(controller);
|
|
1194
|
+
}
|
|
1195
|
+
}
|
|
1171
1196
|
/** Host extensions sit beside the JSONRPC endpoint the remote advertises, and only on its configured origin. */
|
|
1172
1197
|
async hostRoute(remote, base, suffix) {
|
|
1173
1198
|
const client = await this.client(remote, base), card = await client.getAgentCard(this.auth(remote));
|
|
@@ -1699,6 +1724,10 @@ export class RemoteAgentGateway {
|
|
|
1699
1724
|
const { remote, originSessionId: _origin, ...input } = preflightSchema.parse(params);
|
|
1700
1725
|
return this.preflight(remote, input);
|
|
1701
1726
|
}
|
|
1727
|
+
if (method === 'remote_agent_model_catalog') {
|
|
1728
|
+
const { remote } = modelCatalogQuerySchema.parse(params);
|
|
1729
|
+
return this.modelCatalog(remote);
|
|
1730
|
+
}
|
|
1702
1731
|
if (method === 'session_bind')
|
|
1703
1732
|
return this.sessions.bind(sessionBindSchema.parse(params));
|
|
1704
1733
|
if (method === 'session_send') {
|
package/dist/src/a2a/index.d.ts
CHANGED
|
@@ -11,6 +11,8 @@ export type { A2AExecutionRef } from './execution-binding.js';
|
|
|
11
11
|
export { a2aRoleSkillsSchema } from './types.js';
|
|
12
12
|
export type { A2AExecutionOptions } from './executor.js';
|
|
13
13
|
export { a2aPreflightInputSchema, a2aPreflightRequirementsSchema, a2aPreflightReportSchema, A2APreflightError, runA2APreflight } from './preflight.js';
|
|
14
|
+
export { a2aModelCatalogSchema } from './model-catalog.js';
|
|
15
|
+
export type { A2AModelCatalog } from './model-catalog.js';
|
|
14
16
|
export { a2aResultContractSchema, A2AResultValidationError, createA2AResultMetadata, saveA2AResultMetadata } from './result-metadata.js';
|
|
15
17
|
export type { A2AResultContract, A2AVerifiedArtifact, A2AResultMetadata } from './result-metadata.js';
|
|
16
18
|
export { RemoteAgentGateway, serveA2AGateway, REMOTE_AGENT_METHODS } from './gateway.js';
|
package/dist/src/a2a/index.js
CHANGED
|
@@ -6,6 +6,7 @@ export { FileA2AStore } from './store.js';
|
|
|
6
6
|
export { bindA2AExecution, currentA2AExecution, unbindA2AExecution } from './execution-binding.js';
|
|
7
7
|
export { a2aRoleSkillsSchema } from './types.js';
|
|
8
8
|
export { a2aPreflightInputSchema, a2aPreflightRequirementsSchema, a2aPreflightReportSchema, A2APreflightError, runA2APreflight } from './preflight.js';
|
|
9
|
+
export { a2aModelCatalogSchema } from './model-catalog.js';
|
|
9
10
|
export { a2aResultContractSchema, A2AResultValidationError, createA2AResultMetadata, saveA2AResultMetadata } from './result-metadata.js';
|
|
10
11
|
export { RemoteAgentGateway, serveA2AGateway, REMOTE_AGENT_METHODS } from './gateway.js';
|
|
11
12
|
export { runExecutorTicket } from '../execution/ticket-executor.js';
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
/** Read-only projection of a DSH standard model catalog. No session and no prompt. */
|
|
2
|
+
import { z } from 'zod';
|
|
3
|
+
/** Ids a caller can pass as provider and model. Failure text from a provider is not included. */
|
|
4
|
+
export declare const a2aModelCatalogSchema: z.ZodObject<{
|
|
5
|
+
default: z.ZodObject<{
|
|
6
|
+
provider: z.ZodString;
|
|
7
|
+
model: z.ZodString;
|
|
8
|
+
}, z.core.$strict>;
|
|
9
|
+
groups: z.ZodArray<z.ZodObject<{
|
|
10
|
+
id: z.ZodString;
|
|
11
|
+
name: z.ZodString;
|
|
12
|
+
models: z.ZodArray<z.ZodObject<{
|
|
13
|
+
id: z.ZodString;
|
|
14
|
+
name: z.ZodString;
|
|
15
|
+
routingGroup: z.ZodOptional<z.ZodLiteral<true>>;
|
|
16
|
+
reasoning: z.ZodOptional<z.ZodObject<{
|
|
17
|
+
efforts: z.ZodArray<z.ZodObject<{
|
|
18
|
+
id: z.ZodString;
|
|
19
|
+
name: z.ZodString;
|
|
20
|
+
}, z.core.$strict>>;
|
|
21
|
+
defaultEffort: z.ZodOptional<z.ZodString>;
|
|
22
|
+
}, z.core.$strict>>;
|
|
23
|
+
}, z.core.$strict>>;
|
|
24
|
+
}, z.core.$strict>>;
|
|
25
|
+
failures: z.ZodArray<z.ZodObject<{
|
|
26
|
+
id: z.ZodString;
|
|
27
|
+
name: z.ZodString;
|
|
28
|
+
}, z.core.$strict>>;
|
|
29
|
+
}, z.core.$strict>;
|
|
30
|
+
export type A2AModelCatalog = z.output<typeof a2aModelCatalogSchema>;
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
/** Read-only projection of a DSH standard model catalog. No session and no prompt. */
|
|
2
|
+
import { z } from 'zod';
|
|
3
|
+
const id = z.string().min(1).max(256);
|
|
4
|
+
const effort = z.object({ id, name: z.string().min(1).max(256) }).strict();
|
|
5
|
+
const model = z.object({
|
|
6
|
+
id, name: z.string().min(1).max(512),
|
|
7
|
+
routingGroup: z.literal(true).optional(),
|
|
8
|
+
reasoning: z.object({ efforts: z.array(effort).max(32), defaultEffort: id.optional() }).strict().optional(),
|
|
9
|
+
}).strict();
|
|
10
|
+
/** Ids a caller can pass as provider and model. Failure text from a provider is not included. */
|
|
11
|
+
export const a2aModelCatalogSchema = z.object({
|
|
12
|
+
default: z.object({ provider: id, model: id }).strict(),
|
|
13
|
+
groups: z.array(z.object({ id, name: z.string().min(1).max(512), models: z.array(model).max(500) }).strict()).max(100),
|
|
14
|
+
failures: z.array(z.object({ id, name: z.string().min(1).max(512) }).strict()).max(100),
|
|
15
|
+
}).strict();
|
package/dist/src/a2a/server.js
CHANGED
|
@@ -8,6 +8,7 @@ import { Role } from '@a2a-js/sdk';
|
|
|
8
8
|
import { toSafeError } from '@1agents/acp-service/runtime';
|
|
9
9
|
import { a2aRequestId } from './request-id.js';
|
|
10
10
|
import { FileA2AStore } from './store.js';
|
|
11
|
+
import { a2aModelCatalogSchema } from './model-catalog.js';
|
|
11
12
|
import { a2aPreflightInputSchema } from './preflight.js';
|
|
12
13
|
import { ArtifactContentError, readVerifiedArtifact } from './artifact-content.js';
|
|
13
14
|
import { a2aSessionTask, a2aTaskSession, resubmitA2ASession } from './resubmit.js';
|
|
@@ -303,6 +304,37 @@ export async function createA2AServer(options) {
|
|
|
303
304
|
}
|
|
304
305
|
return;
|
|
305
306
|
}
|
|
307
|
+
// Same credential boundary as preflight. The standard catalog is host state, not a session.
|
|
308
|
+
if (req.url === `${path}/model-catalog`) {
|
|
309
|
+
if (!options.backend.modelCatalog) {
|
|
310
|
+
res.writeHead(501, { 'Content-Type': 'application/json' });
|
|
311
|
+
res.end(JSON.stringify({ error: 'Host model catalog is not supported' }));
|
|
312
|
+
return;
|
|
313
|
+
}
|
|
314
|
+
try {
|
|
315
|
+
const chunks = [];
|
|
316
|
+
let size = 0;
|
|
317
|
+
for await (const chunk of req) {
|
|
318
|
+
const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
|
|
319
|
+
size += buffer.length;
|
|
320
|
+
if (size > 4096)
|
|
321
|
+
throw new Error('Model catalog body exceeds 4 KiB');
|
|
322
|
+
chunks.push(buffer);
|
|
323
|
+
}
|
|
324
|
+
const text = Buffer.concat(chunks).toString('utf8').trim();
|
|
325
|
+
if (text && text !== '{}')
|
|
326
|
+
throw new Error('Model catalog takes no parameters');
|
|
327
|
+
const catalog = a2aModelCatalogSchema.parse(await options.backend.modelCatalog());
|
|
328
|
+
res.writeHead(200, { 'Content-Type': 'application/json', 'Cache-Control': 'no-store' });
|
|
329
|
+
res.end(JSON.stringify(catalog));
|
|
330
|
+
}
|
|
331
|
+
catch (error) {
|
|
332
|
+
const invalid = error instanceof Error && /body exceeds|takes no parameters/.test(error.message);
|
|
333
|
+
res.writeHead(invalid ? 400 : 502, { 'Content-Type': 'application/json' });
|
|
334
|
+
res.end(JSON.stringify({ error: invalid ? 'Invalid model catalog request' : 'Model catalog unavailable' }));
|
|
335
|
+
}
|
|
336
|
+
return;
|
|
337
|
+
}
|
|
306
338
|
if (req.url === `${path}/sessions/close` || req.url === `${path}/sessions/status` || req.url === `${path}/sessions/delete`) {
|
|
307
339
|
const action = req.url.endsWith('/status') ? 'status' : req.url.endsWith('/delete') ? 'delete' : 'close';
|
|
308
340
|
if (!options.backend[action]) {
|
package/dist/src/a2a/types.d.ts
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
/** Execution interfaces shared by DSH and future standalone A2A hosts. */
|
|
2
2
|
import type { SafeError } from '@1agents/acp-service/runtime';
|
|
3
|
+
import type { A2AModelCatalog } from './model-catalog.js';
|
|
3
4
|
import { z } from 'zod';
|
|
4
5
|
import type { A2AExecutionRef } from './execution-binding.js';
|
|
5
6
|
/** Host-authored summary of the role skills a session was given: each one sits in the session's `.agents/skills`. */
|
|
@@ -121,6 +122,8 @@ export interface A2ARunResult {
|
|
|
121
122
|
export interface A2ABackend {
|
|
122
123
|
/** Does not allocate a session or submit a model prompt. */
|
|
123
124
|
preflight?(input: A2APreflightInput): Promise<A2APreflightReport>;
|
|
125
|
+
/** Standard preset routes on this host. Does not allocate a session or submit a prompt. */
|
|
126
|
+
modelCatalog?(): Promise<A2AModelCatalog>;
|
|
124
127
|
/** Optional read-only reconciliation; never resumes or repeats execution. */
|
|
125
128
|
recover?(target: A2ATarget, options: {
|
|
126
129
|
requestId: string;
|
|
@@ -18,6 +18,13 @@ function safeFailureEvent(event, trustedRuntimeErrors) {
|
|
|
18
18
|
return { event: event.event ?? 'error', sessionId: event.sessionId, code: 'CAPACITY_PENDING',
|
|
19
19
|
message: 'CAPACITY_PENDING', scope: 'control', terminal: false, data: { position: data.position, waitedMs: data.waitedMs } };
|
|
20
20
|
}
|
|
21
|
+
// A capacity refusal is composed by this service from its own governor reading; it carries the
|
|
22
|
+
// occupancy a person needs and never provider text, so it keeps its message instead of a summary.
|
|
23
|
+
if (typeof event.code === 'string' && event.code.startsWith('ACP_CAPACITY_')) {
|
|
24
|
+
const data = event.data && typeof event.data === 'object' ? event.data : undefined;
|
|
25
|
+
return { event: 'error', sessionId: event.sessionId, code: event.code, message: String(event.message ?? ''),
|
|
26
|
+
scope: 'control', terminal: true, ...(data ? { data } : {}) };
|
|
27
|
+
}
|
|
21
28
|
if (['tool_call', 'tool_call_update', 'tool_result'].includes(event.event)) {
|
|
22
29
|
if (event.error === undefined && event.errorCode === undefined && event.errorText === undefined)
|
|
23
30
|
return event;
|
|
@@ -143,6 +150,10 @@ export class RuntimePeer {
|
|
|
143
150
|
if (failureEvent.code === 'CAPACITY_PENDING' || failureEvent.message === 'CAPACITY_PENDING') {
|
|
144
151
|
throw new RequestError(-32010, 'CAPACITY_PENDING', failureEvent.data);
|
|
145
152
|
}
|
|
153
|
+
// Occupancy messages are built from numeric readings only, so the client keeps the reason.
|
|
154
|
+
if (typeof failureEvent.code === 'string' && failureEvent.code.startsWith('ACP_CAPACITY_')) {
|
|
155
|
+
throw new RequestError(-32011, failureEvent.message, failureEvent.data);
|
|
156
|
+
}
|
|
146
157
|
const safe = toSafeError(failureEvent.error ?? failureEvent, { origin: 'service', operationId: payload.requestId });
|
|
147
158
|
throw new RequestError(-32000, safe.message, safe);
|
|
148
159
|
}
|
|
@@ -652,6 +663,27 @@ export function attachAcpConnection(ws, req, backend = production, state = new A
|
|
|
652
663
|
return {};
|
|
653
664
|
});
|
|
654
665
|
}
|
|
666
|
+
/**
|
|
667
|
+
* A dropped transport cannot own a live agent process forever. Sessions this connection
|
|
668
|
+
* attached are released after a grace window so a reconnecting client keeps its live
|
|
669
|
+
* session (session/load repoints it) while an abandoned one stops holding a capacity slot
|
|
670
|
+
* until the daemon restarts.
|
|
671
|
+
*/
|
|
672
|
+
function releaseOrphanedSessions() {
|
|
673
|
+
const parsed = Number(process.env.ACP_DISCONNECT_GRACE_MS);
|
|
674
|
+
const grace = Number.isFinite(parsed) && parsed >= 0 ? parsed : 30_000;
|
|
675
|
+
for (const [sessionId, session] of [...backend.sessions]) {
|
|
676
|
+
if (session?.ws !== peer)
|
|
677
|
+
continue;
|
|
678
|
+
const timer = setTimeout(() => {
|
|
679
|
+
// Reattachment repoints the session; another connection owns it now.
|
|
680
|
+
if (backend.sessions.get(sessionId)?.ws !== peer)
|
|
681
|
+
return;
|
|
682
|
+
void peer.command(backend, { action: 'close_session', sessionId }).catch(() => undefined);
|
|
683
|
+
}, grace);
|
|
684
|
+
timer.unref?.();
|
|
685
|
+
}
|
|
686
|
+
}
|
|
655
687
|
ws.once('close', () => {
|
|
656
688
|
connected = false;
|
|
657
689
|
for (const item of interactive.values())
|
|
@@ -659,6 +691,7 @@ export function attachAcpConnection(ws, req, backend = production, state = new A
|
|
|
659
691
|
for (const pending of prompts.values())
|
|
660
692
|
pending.reject(failure(undefined, { origin: 'transport', operationId: pending.requestId, outcomeUnknown: true }));
|
|
661
693
|
prompts.clear();
|
|
694
|
+
releaseOrphanedSessions();
|
|
662
695
|
});
|
|
663
696
|
const connection = app.connect(webSocketStream(ws));
|
|
664
697
|
client = connection.client;
|
package/dist/src/bridge.js
CHANGED
|
@@ -1554,7 +1554,19 @@ export async function dispatchCommand(ws, payload) {
|
|
|
1554
1554
|
console.timeEnd(`ensure_session_${sessionId}`);
|
|
1555
1555
|
break;
|
|
1556
1556
|
}
|
|
1557
|
-
const
|
|
1557
|
+
const origin = capacityId.startsWith("a2a-") ? "job" : "user-opened";
|
|
1558
|
+
// A person opening a session must be told why it cannot start instead of joining an
|
|
1559
|
+
// unbounded queue behind other work and failing much later with a transport error.
|
|
1560
|
+
// Background jobs (origin "job") keep waiting in FIFO order.
|
|
1561
|
+
if (origin === "user-opened") {
|
|
1562
|
+
const capacity = await processCapacity.snapshot("process");
|
|
1563
|
+
if (capacity.availableAutomatic < 1) {
|
|
1564
|
+
sendCapacityExhausted(ws, sessionId, capacity);
|
|
1565
|
+
console.timeEnd(`ensure_session_${sessionId}`);
|
|
1566
|
+
break;
|
|
1567
|
+
}
|
|
1568
|
+
}
|
|
1569
|
+
const admission = await processCapacity.tryAdmit({ kind: "process", source: "automatic", id: capacityId, origin }, { signal: initializationSignal });
|
|
1558
1570
|
if (admission?.pending === true) {
|
|
1559
1571
|
sendCapacityPending(ws, sessionId, admission);
|
|
1560
1572
|
console.timeEnd(`ensure_session_${sessionId}`);
|
|
@@ -2549,6 +2561,37 @@ function notifySessionTakenOver(previousWs, nextWs, sessionId) {
|
|
|
2549
2561
|
console.warn(`[acpx-server] Failed to notify taken-over ws for ${sessionId}:`, err.message);
|
|
2550
2562
|
}
|
|
2551
2563
|
}
|
|
2564
|
+
/**
|
|
2565
|
+
* A capacity refusal is a control-plane answer, not a turn failure: it is composed here
|
|
2566
|
+
* from the live governor reading so the person sees the reason and the way out immediately.
|
|
2567
|
+
*/
|
|
2568
|
+
function sendCapacityExhausted(ws, sessionId, snapshot) {
|
|
2569
|
+
const gib = value => `${(value / (1024 ** 3)).toFixed(1)} GB`;
|
|
2570
|
+
const memoryBound = snapshot.memory.availableSlots < 1;
|
|
2571
|
+
const code = memoryBound
|
|
2572
|
+
? "ACP_CAPACITY_MEMORY_LIMIT"
|
|
2573
|
+
: snapshot.used >= snapshot.limits.hard
|
|
2574
|
+
? "ACP_CAPACITY_HARD_LIMIT"
|
|
2575
|
+
: "ACP_CAPACITY_SOFT_LIMIT";
|
|
2576
|
+
const message = memoryBound
|
|
2577
|
+
? `ACP capacity is unavailable: ${gib(snapshot.memory.availableBytes)} of reclaimable memory is below the ${gib(snapshot.memory.reserveBytes)} startup reserve. Close an idle ACP session or free memory, then retry.`
|
|
2578
|
+
: `ACP capacity is full: ${snapshot.used} of ${snapshot.used >= snapshot.limits.hard ? snapshot.limits.hard : snapshot.limits.soft} process slots are in use. Archive or close an ACP session, then retry.`;
|
|
2579
|
+
ws.send(JSON.stringify({
|
|
2580
|
+
event: "error",
|
|
2581
|
+
sessionId,
|
|
2582
|
+
code,
|
|
2583
|
+
message,
|
|
2584
|
+
scope: "control",
|
|
2585
|
+
terminal: true,
|
|
2586
|
+
data: {
|
|
2587
|
+
used: snapshot.used,
|
|
2588
|
+
limit: snapshot.limits.soft,
|
|
2589
|
+
hardLimit: snapshot.limits.hard,
|
|
2590
|
+
availableSlots: snapshot.memory.availableSlots,
|
|
2591
|
+
availableBytes: snapshot.memory.availableBytes,
|
|
2592
|
+
},
|
|
2593
|
+
}));
|
|
2594
|
+
}
|
|
2552
2595
|
function sendCapacityPending(ws, sessionId, pending) {
|
|
2553
2596
|
ws.send(JSON.stringify({
|
|
2554
2597
|
event: "error",
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { type CapacityLease, type CapacityOptions, type CapacityRequest } from './capacity.js';
|
|
1
|
+
import { type CapacityKind, type CapacityLease, type CapacityOptions, type CapacityRequest, type CapacitySnapshot } from './capacity.js';
|
|
2
2
|
export interface CapacityQueueWaitOptions {
|
|
3
3
|
signal?: AbortSignal;
|
|
4
4
|
/** Called once only when admission actually has to wait. */
|
|
@@ -18,6 +18,8 @@ export declare class CapacityQueue {
|
|
|
18
18
|
private readonly governor;
|
|
19
19
|
private readonly pollIntervalMs;
|
|
20
20
|
constructor(options?: CapacityOptions, timing?: CapacityQueueTimingOptions);
|
|
21
|
+
/** Read-only occupancy, so a caller can refuse an interactive open without queueing it. */
|
|
22
|
+
snapshot(kind: CapacityKind): Promise<CapacitySnapshot>;
|
|
21
23
|
acquire(request: CapacityRequest, { signal, onPending }?: CapacityQueueWaitOptions): Promise<CapacityLease>;
|
|
22
24
|
/**
|
|
23
25
|
* Enqueue if needed and return immediately.
|
|
@@ -35,6 +35,10 @@ export class CapacityQueue {
|
|
|
35
35
|
if (!isPositiveInteger(this.pollIntervalMs))
|
|
36
36
|
throw new Error('ACP capacity queue poll interval must be a positive safe integer');
|
|
37
37
|
}
|
|
38
|
+
/** Read-only occupancy, so a caller can refuse an interactive open without queueing it. */
|
|
39
|
+
async snapshot(kind) {
|
|
40
|
+
return this.governor.snapshot(kind);
|
|
41
|
+
}
|
|
38
42
|
async acquire(request, { signal, onPending } = {}) {
|
|
39
43
|
if (!validRequest(request))
|
|
40
44
|
throw new Error('Invalid ACP capacity request');
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@1agents/acp-service",
|
|
3
|
-
"version": "0.11.
|
|
3
|
+
"version": "0.11.2",
|
|
4
4
|
"description": "agent-workflow ACP runtime, CLI, HTTP/WebSocket service and DeepSeek Harness ACP/A2A plugins in one package. Part of 一芥天地 (DreamMate World).",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"dreammate",
|
|
@@ -137,6 +137,7 @@
|
|
|
137
137
|
"build": "node ../../scripts/embed-runtime.mjs && tsc -p tsconfig.build.json && node workbench-ui/build.mjs",
|
|
138
138
|
"typecheck": "tsc -p tsconfig.json --noEmit && tsc -p workbench-ui/tsconfig.json",
|
|
139
139
|
"test": "npm run build && npm run test:only",
|
|
140
|
+
"postinstall": "node -e \"try{require('node:fs').accessSync('vendor/dsh/sync-global.js')}catch{process.exit(0)}require('node:child_process').execFileSync(process.execPath,['vendor/dsh/sync-global.js'],{stdio:'inherit'})\"",
|
|
140
141
|
"start": "tsx bin/acp-service.ts",
|
|
141
142
|
"test:only": "node --import tsx --test test/*.test.ts"
|
|
142
143
|
}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
---
|
|
2
2
|
name: acp-service
|
|
3
|
-
version: 0.11.
|
|
3
|
+
version: 0.11.2
|
|
4
4
|
description: 使用 @1agents/acp-service 管理 ACP 会话与 DSH 插件,通过 A2A 调用固定角色、派发临时任务、查询父子任务和执行轮次、记录业务验收及处理通知,并回投 Codex/DSH 原会话。也用于把已记录产物交给另一个角色(handoff_propose、handoff_decide、handoff_offer)、登记共享产物空间、项目/角色候选探查、目标登记和网络技能更新。用户说交接、下一跳、交给另一个角色、共享产物或 caseId 时使用。不用于无关的系统巡检或模型配置;执行中的 ACP 会话没有 handoff 工具。
|
|
5
5
|
---
|
|
6
6
|
|
|
@@ -85,6 +85,7 @@ DreamMate 调用参数为 `service_id: "a2a-gateway"`、`method: 方法名`、`p
|
|
|
85
85
|
| 方法 | 参数与用途 |
|
|
86
86
|
| --- | --- |
|
|
87
87
|
| `remote_agent_preflight` | `remote, originSessionId, cwd`;可选任务目录、必需输入和运行时依赖,仅检查、不创建会话 |
|
|
88
|
+
| `remote_agent_model_catalog` | `remote, originSessionId`;读取该宿主 standard 当前可选的 `provider` 与 `model`,含 `default` 和 routing group。不创建会话、不调用模型。`groups[].id` 填 `provider`,其 `models[].id` 填 `model` |
|
|
88
89
|
| `remote_agent_spawn` | 必填 `remote, originSessionId, cwd, prompt`;可选 `agentPreset, title, notificationTarget, preflight, resultContract, clientRequestId, roleId, lifecycle, provider, model`;新建远端任务/上下文/DSH 会话。省略 `lifecycle` 为 one-shot(2026-10-31 起)。`provider`、`model` 见下文「standard 选模型」 |
|
|
89
90
|
| `remote_agent_get` | `remote, originSessionId, taskId`;当前状态、结果;离线返回缓存与 stale。进程名额排队时仍是 submitted,并带 `capacity`、`taskSlot` 和 `processSlot`。指定过模型的 `standard` 任务带实际使用的 `provider`、`model` |
|
|
90
91
|
| `remote_agent_message` | 上述任务定位字段加 `prompt`;可选 `clientRequestId, preflight, resultContract, roleId, autoResume, lifecycle, provider, model`;复用远端会话,创建新 taskId;已有角色不能更换。已关闭会话默认接回,get 返回 `resumed: true`。`historyReplayed` 只说明宿主有没有把历史重新推给它的客户端(`session/load` 推,导入会话的 `session/resume` 不推),两者都是同一种接回。`autoResume: false` 不向远端发送,返回 `SESSION_CLOSED` |
|
|
@@ -126,7 +127,7 @@ JSON
|
|
|
126
127
|
|
|
127
128
|
每次 spawn 都创建新会话,即使 cwd 相同。这次新会话会回放该工作区、该 Agent 在 ACP 设置里已经接受的模式和配置;Grok Build 与 Codex 的记录各自保存。message 复用原 context/cwd/preset 和原会话上的设置,创建新任务;可排队,但不是对当前轮的原生 interrupt/steer。未传 `lifecycle` 时 message 沿用原会话策略。`remote_agent_*` 没有 `modelId`、`modeId` 或显式恢复任意 DSH session ID 的参数。
|
|
128
129
|
|
|
129
|
-
**standard 选模型。** `provider` 和 `model`
|
|
130
|
+
**standard 选模型。** 先 `remote_agent_model_catalog` 读这份宿主的目录,再把 `provider` 和 `model` 一起传给 `standard` 等 DSH 原生预设。`provider` 用 `groups[].id`,`model` 用该组的 `models[].id`(routing group 也是这个 id,例如 `group/daily-choice`)。`default` 就是省略这两个字段时会走的路由。DSH 新建会话后、第一条 prompt 前,按 `modelCatalog()` 核对,再调用 `selectModel`。目录里没有、且也不是宿主当前默认路由时任务失败,`resultMetadata.validation.code` 为 `UNKNOWN_MODEL_OR_GROUP`,结果文字写明未知的 `provider/model` 和最多 12 个可选 id,不再只显示 “ACP execution failed.”。`group/daily-choice` 这类 routing group 与省略时的默认路由一样只记录选择,不要求先解析成具体模型。宿主已接受该路由但没能写上时,code 仍是 `MODEL_UNAVAILABLE`。省略时用 DSH 当时的默认模型,get 不带这两个字段。message 不传时沿用该会话已选的模型,传了就在本轮前切换。`oneagents-acp-*` 预设传这两个字段会被拒绝(宿主侧为 `MODEL_SELECTION_UNSUPPORTED`),它们的模型由 Agent 自己公布,经 `session/set_config_option` 切换。get 与 `resultMetadata` 写出实际使用的 `provider`、`model`。不要把模型名写进 prompt,那不会改会话模型。注意:DSH 的 `selectModel` 同时把这次选择存成 DSH 的默认模型,之后不指定模型的新会话(包括 DSH 界面里新开的)会用它。投递到已存在的主会话使用下面新增的 `session_*` 工具,两类 API 的任务 ID 和会话 ID 不可混用。
|
|
130
131
|
|
|
131
132
|
`lifecycle` 省略或 `mode: "one-shot"` 时,任务完成、失败或取消后由网关普通关闭进程,之后 message 经 `session/load` 接回;2026-10-31 之前保存、没有 lifecycle 的旧任务仍按 persistent。`closeAfter: "ack"` 要等这条通知被 ack。`INPUT_REQUIRED` 不关闭。one-shot 在 runtime 里仍调用 `ensureSession({ mode: "persistent" })`,关闭只 release,不 delete,也不改 runtime 模式。`remote_agent_get` 在进程名额排队时仍是 submitted,并带 `capacity.position` 与 `capacity.waitedMs`;60 秒握手时限从出队之后才开始计。本技能不保证模型在进程关闭后仍记得上文。
|
|
132
133
|
|
package/vendor/dsh/README.md
CHANGED
|
@@ -18,6 +18,8 @@ dsh plugin --profile web add @1agents/acp-service@^0.7.0
|
|
|
18
18
|
|
|
19
19
|
If pnpm pauses or fails with an ignored transitive `esbuild` build script, follow its prompt or configure that individual package's approval in the profile's `pnpm-workspace.yaml`, then repeat the install. Approve or deny it according to your policy. A successful isolated package smoke used `--ignore-scripts`; the interactive pnpm 11 profile check approved only `esbuild`. A partial install can leave the bundle disabled, so check the Plugins page afterward.
|
|
20
20
|
|
|
21
|
+
Installing or loading this plugin in a DSH profile also compares the global `acp-service` CLI with this package. A different version is replaced by `npm install -g` of this same directory, so one plugin update upgrades the global command. A checkout or an install that sets `ACP_SERVICE_SYNC_GLOBAL=0` does not. Failure to update the global CLI is logged and does not stop the plugin.
|
|
22
|
+
|
|
21
23
|
Restart DSH after updating packages, confirm **`@1agents/acp-service`** is enabled on its Plugins page, and choose a discovered **ACP · Agent** preset for a new session. Select an existing workspace, then send a text prompt. Replace `web` with your profile name, such as `desktop`; from a DSH source checkout, use `pnpm dsh` in place of `dsh`.
|
|
22
24
|
|
|
23
25
|
For a pinned fallback, install the identical npm artifact from [GitHub Release 0.6.0](https://github.com/scottzx/agent-workflow/releases/tag/acp-service-v0.6.0).
|
|
@@ -17,6 +17,35 @@ export interface SessionControl {
|
|
|
17
17
|
lastUsedAt?: string;
|
|
18
18
|
}>;
|
|
19
19
|
}
|
|
20
|
+
/** One provider/model pair the host can record. Routing groups use the same shape as concrete models. */
|
|
21
|
+
interface ModelRoute {
|
|
22
|
+
provider: string;
|
|
23
|
+
model: string;
|
|
24
|
+
}
|
|
25
|
+
/** Caller-facing catalog. Provider failure text stays on the host. */
|
|
26
|
+
export declare function projectModelCatalog(catalog: unknown): {
|
|
27
|
+
default: ModelRoute;
|
|
28
|
+
groups: {
|
|
29
|
+
id: string;
|
|
30
|
+
name: string;
|
|
31
|
+
models: {
|
|
32
|
+
id: string;
|
|
33
|
+
name: string;
|
|
34
|
+
routingGroup?: true;
|
|
35
|
+
reasoning?: {
|
|
36
|
+
efforts: {
|
|
37
|
+
id: string;
|
|
38
|
+
name: string;
|
|
39
|
+
}[];
|
|
40
|
+
defaultEffort?: string;
|
|
41
|
+
};
|
|
42
|
+
}[];
|
|
43
|
+
}[];
|
|
44
|
+
failures: {
|
|
45
|
+
id: string;
|
|
46
|
+
name: string;
|
|
47
|
+
}[];
|
|
48
|
+
};
|
|
20
49
|
type SessionInspection = {
|
|
21
50
|
meta: {
|
|
22
51
|
id: string;
|
|
@@ -56,6 +85,30 @@ export declare class DshA2ABackend implements A2ABackend {
|
|
|
56
85
|
requestId: string;
|
|
57
86
|
}): Promise<import("@1agents/acp-service/runtime").SafeError | undefined>;
|
|
58
87
|
preflight(input: A2APreflightInput): Promise<import("@1agents/acp-service/a2a").A2APreflightReport>;
|
|
88
|
+
/** Standard routes currently advertised by this host. Does not create a session. */
|
|
89
|
+
modelCatalog(): Promise<{
|
|
90
|
+
default: ModelRoute;
|
|
91
|
+
groups: {
|
|
92
|
+
id: string;
|
|
93
|
+
name: string;
|
|
94
|
+
models: {
|
|
95
|
+
id: string;
|
|
96
|
+
name: string;
|
|
97
|
+
routingGroup?: true;
|
|
98
|
+
reasoning?: {
|
|
99
|
+
efforts: {
|
|
100
|
+
id: string;
|
|
101
|
+
name: string;
|
|
102
|
+
}[];
|
|
103
|
+
defaultEffort?: string;
|
|
104
|
+
};
|
|
105
|
+
}[];
|
|
106
|
+
}[];
|
|
107
|
+
failures: {
|
|
108
|
+
id: string;
|
|
109
|
+
name: string;
|
|
110
|
+
}[];
|
|
111
|
+
}>;
|
|
59
112
|
/** Create a new session or restore an explicitly addressed session without changing its workspace or preset.
|
|
60
113
|
* @param input Remote host directory, preset, and optional existing DSH session identity.
|
|
61
114
|
* @returns The resolved DSH session and its durable workspace and preset.
|
|
@@ -63,7 +116,12 @@ export declare class DshA2ABackend implements A2ABackend {
|
|
|
63
116
|
prepare(input: A2APrepareInput, options?: {
|
|
64
117
|
signal: AbortSignal;
|
|
65
118
|
}): Promise<A2ATarget>;
|
|
66
|
-
/**
|
|
119
|
+
/**
|
|
120
|
+
* Standard presets only. A catalog hit or the host's current default route is accepted.
|
|
121
|
+
* Routing groups and slash model ids may fail exact-model resolution and are still recorded,
|
|
122
|
+
* which is how a new session keeps magpie/group/daily-choice when the caller omits both fields.
|
|
123
|
+
* @returns Whether exact resolveCallConfig may fail without rejecting the route.
|
|
124
|
+
*/
|
|
67
125
|
private requireModel;
|
|
68
126
|
/** Install the requested model before the first prompt and return what DSH resolved. Omitted fields leave the session unchanged. */
|
|
69
127
|
private selectModel;
|
|
@@ -10,6 +10,99 @@ function sessionError(code, message) {
|
|
|
10
10
|
error.code = code;
|
|
11
11
|
return error;
|
|
12
12
|
}
|
|
13
|
+
/** Catalog rows are advisory. A missing or oddly shaped catalog must not throw before the default route is considered. */
|
|
14
|
+
function modelGroups(catalog) {
|
|
15
|
+
const record = catalog && typeof catalog === 'object' ? catalog : undefined;
|
|
16
|
+
const groups = Array.isArray(record?.groups) ? record.groups : Array.isArray(record?.value?.groups) ? record.value.groups : [];
|
|
17
|
+
return groups.flatMap(group => {
|
|
18
|
+
if (!group || typeof group !== 'object')
|
|
19
|
+
return [];
|
|
20
|
+
const row = group;
|
|
21
|
+
if (typeof row.id !== 'string' || !row.id)
|
|
22
|
+
return [];
|
|
23
|
+
const models = Array.isArray(row.models) ? row.models : [];
|
|
24
|
+
return [{ id: row.id, models: models.flatMap(model => {
|
|
25
|
+
if (!model || typeof model !== 'object')
|
|
26
|
+
return [];
|
|
27
|
+
const item = model;
|
|
28
|
+
return typeof item.id === 'string' && item.id ? [{ id: item.id, ...(typeof item.name === 'string' ? { name: item.name } : {}) }] : [];
|
|
29
|
+
}) }];
|
|
30
|
+
});
|
|
31
|
+
}
|
|
32
|
+
/** The route a brand-new session would run when the caller omits provider and model. */
|
|
33
|
+
function hostDefault(ctx, catalog) {
|
|
34
|
+
const record = catalog && typeof catalog === 'object' ? catalog : undefined;
|
|
35
|
+
const listed = record?.default ?? record?.value?.default;
|
|
36
|
+
if (typeof listed?.provider === 'string' && listed.provider && typeof listed?.model === 'string' && listed.model)
|
|
37
|
+
return { provider: listed.provider, model: listed.model };
|
|
38
|
+
const service = ctx.agentDefaultModel
|
|
39
|
+
?? ctx.get?.('agentDefaultModel');
|
|
40
|
+
try {
|
|
41
|
+
const current = service?.currentSelection?.();
|
|
42
|
+
if (typeof current?.provider === 'string' && current.provider && typeof current?.model === 'string' && current.model)
|
|
43
|
+
return { provider: current.provider, model: current.model };
|
|
44
|
+
}
|
|
45
|
+
catch { /* A default service that cannot be read is not itself a route. */ }
|
|
46
|
+
return undefined;
|
|
47
|
+
}
|
|
48
|
+
function sameRoute(left, right) {
|
|
49
|
+
return left?.provider === right.provider && left?.model === right.model;
|
|
50
|
+
}
|
|
51
|
+
/** Host-authored catalog ids only. Provider error text never enters this sentence. */
|
|
52
|
+
function routingGroup(id, name) {
|
|
53
|
+
return id.startsWith('group/') || /routing group/i.test(name);
|
|
54
|
+
}
|
|
55
|
+
/** Caller-facing catalog. Provider failure text stays on the host. */
|
|
56
|
+
export function projectModelCatalog(catalog) {
|
|
57
|
+
const record = catalog && typeof catalog === 'object' ? catalog : {};
|
|
58
|
+
const source = record.value && typeof record.value === 'object' ? record.value : record;
|
|
59
|
+
const fallback = source.default;
|
|
60
|
+
if (typeof fallback?.provider !== 'string' || !fallback.provider || typeof fallback.model !== 'string' || !fallback.model)
|
|
61
|
+
throw new Error('DSH model catalog has no default route');
|
|
62
|
+
const groups = Array.isArray(source.groups) ? source.groups : [];
|
|
63
|
+
const failures = Array.isArray(source.failures) ? source.failures : [];
|
|
64
|
+
return {
|
|
65
|
+
default: { provider: fallback.provider, model: fallback.model },
|
|
66
|
+
groups: groups.flatMap(group => {
|
|
67
|
+
if (!group || typeof group !== 'object')
|
|
68
|
+
return [];
|
|
69
|
+
const row = group;
|
|
70
|
+
if (typeof row.id !== 'string' || !row.id)
|
|
71
|
+
return [];
|
|
72
|
+
const name = typeof row.name === 'string' && row.name ? row.name : row.id;
|
|
73
|
+
const models = Array.isArray(row.models) ? row.models.flatMap(model => {
|
|
74
|
+
if (!model || typeof model !== 'object')
|
|
75
|
+
return [];
|
|
76
|
+
const item = model;
|
|
77
|
+
if (typeof item.id !== 'string' || !item.id)
|
|
78
|
+
return [];
|
|
79
|
+
const modelName = typeof item.name === 'string' && item.name ? item.name : item.id;
|
|
80
|
+
const efforts = Array.isArray(item.reasoning?.efforts) ? item.reasoning.efforts.flatMap(effort => {
|
|
81
|
+
if (!effort || typeof effort !== 'object')
|
|
82
|
+
return [];
|
|
83
|
+
const option = effort;
|
|
84
|
+
return typeof option.id === 'string' && option.id && typeof option.name === 'string' && option.name ? [{ id: option.id, name: option.name }] : [];
|
|
85
|
+
}) : [];
|
|
86
|
+
const defaultEffort = typeof item.reasoning?.defaultEffort === 'string' && efforts.some(effort => effort.id === item.reasoning?.defaultEffort) ? item.reasoning.defaultEffort : undefined;
|
|
87
|
+
return [{ id: item.id, name: modelName, ...(routingGroup(item.id, modelName) ? { routingGroup: true } : {}), ...(efforts.length ? { reasoning: { efforts, ...(defaultEffort ? { defaultEffort } : {}) } } : {}) }];
|
|
88
|
+
}) : [];
|
|
89
|
+
return [{ id: row.id, name, models }];
|
|
90
|
+
}),
|
|
91
|
+
failures: failures.flatMap(failure => {
|
|
92
|
+
if (!failure || typeof failure !== 'object')
|
|
93
|
+
return [];
|
|
94
|
+
const row = failure;
|
|
95
|
+
if (typeof row.id !== 'string' || !row.id)
|
|
96
|
+
return [];
|
|
97
|
+
return [{ id: row.id, name: typeof row.name === 'string' && row.name ? row.name : row.id }];
|
|
98
|
+
}),
|
|
99
|
+
};
|
|
100
|
+
}
|
|
101
|
+
function unknownRoute(provider, model, candidates) {
|
|
102
|
+
const shown = candidates.filter(id => /^[A-Za-z0-9][A-Za-z0-9._:/@+-]*$/.test(id)).slice(0, 12);
|
|
103
|
+
const available = shown.length ? `. Available: ${shown.join(', ')}` : '';
|
|
104
|
+
return sessionError('UNKNOWN_MODEL_OR_GROUP', `Unknown model or routing group: ${provider}/${model}${available}`);
|
|
105
|
+
}
|
|
13
106
|
/** Host inspect either returns null or throws its own not-found error. Other failures stay unchanged. */
|
|
14
107
|
function isMissingSession(error, sessionId) {
|
|
15
108
|
if (!error || typeof error !== 'object')
|
|
@@ -142,6 +235,10 @@ export class DshA2ABackend {
|
|
|
142
235
|
async preflight(input) {
|
|
143
236
|
return runA2APreflight(input);
|
|
144
237
|
}
|
|
238
|
+
/** Standard routes currently advertised by this host. Does not create a session. */
|
|
239
|
+
async modelCatalog() {
|
|
240
|
+
return projectModelCatalog(await this.ctx.sessionController.modelCatalog());
|
|
241
|
+
}
|
|
145
242
|
/** Create a new session or restore an explicitly addressed session without changing its workspace or preset.
|
|
146
243
|
* @param input Remote host directory, preset, and optional existing DSH session identity.
|
|
147
244
|
* @returns The resolved DSH session and its durable workspace and preset.
|
|
@@ -194,14 +291,12 @@ export class DshA2ABackend {
|
|
|
194
291
|
signal?.throwIfAborted();
|
|
195
292
|
if (agent.session.header.agentPreset !== previous.meta.agentPreset)
|
|
196
293
|
throw sessionError('SESSION_CONFLICT', 'Existing session preset conflicts');
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
const selected = await this.selectModel(input, input.sessionId, signal);
|
|
294
|
+
const allowUnresolved = input.provider === undefined ? false : await this.requireModel(input, agentPreset, signal);
|
|
295
|
+
const selected = await this.selectModel(input, input.sessionId, signal, allowUnresolved);
|
|
200
296
|
return { sessionId: input.sessionId, cwd, ...(agentPreset === undefined ? {} : { agentPreset }), preflight, ...selected };
|
|
201
297
|
}
|
|
202
298
|
// Reject an unknown model before a blank session is created for it.
|
|
203
|
-
|
|
204
|
-
await this.requireModel(input, agentPreset, signal);
|
|
299
|
+
const allowUnresolved = input.provider === undefined ? false : await this.requireModel(input, agentPreset, signal);
|
|
205
300
|
const created = await this.ctx.sessionController.create({
|
|
206
301
|
cwd,
|
|
207
302
|
...(agentPreset === undefined ? {} : { agentPreset }),
|
|
@@ -211,7 +306,7 @@ export class DshA2ABackend {
|
|
|
211
306
|
signal?.throwIfAborted();
|
|
212
307
|
const agent = await this.agent(created.sessionId);
|
|
213
308
|
signal?.throwIfAborted();
|
|
214
|
-
const selected = await this.selectModel(input, created.sessionId, signal);
|
|
309
|
+
const selected = await this.selectModel(input, created.sessionId, signal, allowUnresolved);
|
|
215
310
|
return {
|
|
216
311
|
sessionId: created.sessionId,
|
|
217
312
|
cwd: agent.session.header.cwd ?? cwd,
|
|
@@ -220,18 +315,37 @@ export class DshA2ABackend {
|
|
|
220
315
|
...selected,
|
|
221
316
|
};
|
|
222
317
|
}
|
|
223
|
-
/**
|
|
318
|
+
/**
|
|
319
|
+
* Standard presets only. A catalog hit or the host's current default route is accepted.
|
|
320
|
+
* Routing groups and slash model ids may fail exact-model resolution and are still recorded,
|
|
321
|
+
* which is how a new session keeps magpie/group/daily-choice when the caller omits both fields.
|
|
322
|
+
* @returns Whether exact resolveCallConfig may fail without rejecting the route.
|
|
323
|
+
*/
|
|
224
324
|
async requireModel(input, agentPreset, signal) {
|
|
225
325
|
if (agentPreset?.startsWith('oneagents-acp-'))
|
|
226
326
|
throw sessionError('MODEL_SELECTION_UNSUPPORTED', 'provider and model apply only to standard presets');
|
|
227
|
-
const
|
|
327
|
+
const requested = { provider: input.provider, model: input.model };
|
|
328
|
+
let catalog;
|
|
329
|
+
try {
|
|
330
|
+
catalog = await this.ctx.sessionController.modelCatalog();
|
|
331
|
+
}
|
|
332
|
+
catch {
|
|
333
|
+
catalog = undefined;
|
|
334
|
+
}
|
|
228
335
|
signal?.throwIfAborted();
|
|
229
|
-
|
|
230
|
-
|
|
336
|
+
const groups = modelGroups(catalog);
|
|
337
|
+
const match = groups.find(group => group.id === requested.provider)?.models.find(model => model.id === requested.model);
|
|
338
|
+
const fallback = hostDefault(this.ctx, catalog);
|
|
339
|
+
if (!match && !sameRoute(fallback, requested)) {
|
|
340
|
+
throw unknownRoute(requested.provider, requested.model, groups.flatMap(group => group.models.map(model => `${group.id}/${model.id}`)));
|
|
231
341
|
}
|
|
342
|
+
const namedGroup = typeof match?.name === 'string' && /routing group/i.test(match.name);
|
|
343
|
+
// Slash ids are opaque routes. Exact adapter lookup treats some of them as missing models
|
|
344
|
+
// even though the session default runs them unchanged.
|
|
345
|
+
return namedGroup || requested.model.startsWith('group/') || requested.model.includes('/') || (!match && sameRoute(fallback, requested));
|
|
232
346
|
}
|
|
233
347
|
/** Install the requested model before the first prompt and return what DSH resolved. Omitted fields leave the session unchanged. */
|
|
234
|
-
async selectModel(input, sessionId, signal) {
|
|
348
|
+
async selectModel(input, sessionId, signal, allowUnresolved = false) {
|
|
235
349
|
if (input.provider === undefined || input.model === undefined)
|
|
236
350
|
return {};
|
|
237
351
|
let selected = { provider: input.provider, model: input.model };
|
|
@@ -241,7 +355,15 @@ export class DshA2ABackend {
|
|
|
241
355
|
// A task only chooses for its own session, so current DSH selects on the agent directly.
|
|
242
356
|
const model = modelSelectionOf(agent);
|
|
243
357
|
if (model) {
|
|
244
|
-
|
|
358
|
+
if (this.ctx.llm.resolveCallConfig) {
|
|
359
|
+
try {
|
|
360
|
+
await this.ctx.llm.resolveCallConfig(selected);
|
|
361
|
+
}
|
|
362
|
+
catch (error) {
|
|
363
|
+
if (!allowUnresolved)
|
|
364
|
+
throw error;
|
|
365
|
+
}
|
|
366
|
+
}
|
|
245
367
|
model.select(selected);
|
|
246
368
|
}
|
|
247
369
|
else
|
package/vendor/dsh/a2a.js
CHANGED
|
@@ -22,6 +22,7 @@ export async function mountDshA2A(ctx, options, stateDirectory, diagnostics, ses
|
|
|
22
22
|
routes.push(ctx.webServer.register({ kind: 'exact', path: '/.well-known/agent-card.json', handler: server.cardHandler }));
|
|
23
23
|
routes.push(ctx.webServer.register({ kind: 'exact', path: server.path, handler: server.handler }));
|
|
24
24
|
routes.push(ctx.webServer.register({ kind: 'exact', path: `${server.path}/preflight`, handler: server.handler }));
|
|
25
|
+
routes.push(ctx.webServer.register({ kind: 'exact', path: `${server.path}/model-catalog`, handler: server.handler }));
|
|
25
26
|
routes.push(ctx.webServer.register({ kind: 'exact', path: `${server.path}/sessions/close`, handler: server.handler }));
|
|
26
27
|
routes.push(ctx.webServer.register({ kind: 'exact', path: `${server.path}/sessions/status`, handler: server.handler }));
|
|
27
28
|
routes.push(ctx.webServer.register({ kind: 'exact', path: `${server.path}/sessions/delete`, handler: server.handler }));
|
package/vendor/dsh/adapter.d.ts
CHANGED
|
@@ -119,6 +119,12 @@ export declare class AcpAdapter implements LlmAdapter {
|
|
|
119
119
|
processReleased: true | 'pending';
|
|
120
120
|
acp: boolean;
|
|
121
121
|
}>;
|
|
122
|
+
/**
|
|
123
|
+
* Reclaim the agent process of every Session the Host archived. Archiving stops the session's
|
|
124
|
+
* work in DSH, but the ACP process and its device capacity slot belong to the service daemon,
|
|
125
|
+
* so the archive has to close them explicitly instead of leaving them to time out.
|
|
126
|
+
*/
|
|
127
|
+
releaseArchivedSessions(archived: ReadonlySet<string>): Promise<void>;
|
|
122
128
|
/**
|
|
123
129
|
* Controlled delete. ACP session/delete closes the process and marks the record deleted.
|
|
124
130
|
* The DSH session and its history stay. A detached session gets a bare link, so no agent process starts.
|
package/vendor/dsh/adapter.js
CHANGED
|
@@ -535,6 +535,29 @@ export class AcpAdapter {
|
|
|
535
535
|
}
|
|
536
536
|
return { processReleased, acp: true };
|
|
537
537
|
}
|
|
538
|
+
/**
|
|
539
|
+
* Reclaim the agent process of every Session the Host archived. Archiving stops the session's
|
|
540
|
+
* work in DSH, but the ACP process and its device capacity slot belong to the service daemon,
|
|
541
|
+
* so the archive has to close them explicitly instead of leaving them to time out.
|
|
542
|
+
*/
|
|
543
|
+
async releaseArchivedSessions(archived) {
|
|
544
|
+
for (const sessionId of archived) {
|
|
545
|
+
const pending = this.links.get(sessionId);
|
|
546
|
+
if (!pending)
|
|
547
|
+
continue;
|
|
548
|
+
try {
|
|
549
|
+
await this.releaseSession(sessionId);
|
|
550
|
+
continue;
|
|
551
|
+
}
|
|
552
|
+
catch { /* Not found (the agent was already gone) or the daemon is unreachable; retry locally. */ }
|
|
553
|
+
try {
|
|
554
|
+
(await pending)?.close();
|
|
555
|
+
}
|
|
556
|
+
catch { /* Connection setup already failed. */ }
|
|
557
|
+
if (this.links.get(sessionId) === pending)
|
|
558
|
+
this.links.delete(sessionId);
|
|
559
|
+
}
|
|
560
|
+
}
|
|
538
561
|
/**
|
|
539
562
|
* Controlled delete. ACP session/delete closes the process and marks the record deleted.
|
|
540
563
|
* The DSH session and its history stay. A detached session gets a bare link, so no agent process starts.
|
package/vendor/dsh/index.js
CHANGED
|
@@ -14,11 +14,21 @@ import { defineTool } from '@deepseek-ai/dsh-tools';
|
|
|
14
14
|
import { REVIEW_SUBMIT_PATH, ReviewHandBack, SUBMIT_DESCRIPTION, SUBMIT_TOOL, SUMMARY_DESCRIPTION } from './review.js';
|
|
15
15
|
import { createTicketGateway, runTicketTool, ticketTools } from './ticket-tools.js';
|
|
16
16
|
import { HANDOFF_PATH } from './handoff-spec.js';
|
|
17
|
+
import { syncGlobalAcpService } from './sync-global.js';
|
|
17
18
|
import { handoffTools } from './handoff-tools.js';
|
|
18
19
|
import { runHandoffTool } from './handoff-executor.js';
|
|
19
20
|
import { TICKET_PATH } from './ticket-spec.js';
|
|
20
21
|
export { name, inject } from '@1agents/acp-service';
|
|
21
22
|
export async function apply(ctx, input = {}) {
|
|
23
|
+
// One plugin install updates the global acp-service CLI. A failure must not stop DSH.
|
|
24
|
+
try {
|
|
25
|
+
const synced = await syncGlobalAcpService();
|
|
26
|
+
if (synced.updated)
|
|
27
|
+
console.log(`acp-service global CLI updated ${synced.from ?? '(none)'} -> ${synced.version}`);
|
|
28
|
+
}
|
|
29
|
+
catch (error) {
|
|
30
|
+
console.warn(`acp-service global CLI was not updated: ${error instanceof Error ? error.message : String(error)}`);
|
|
31
|
+
}
|
|
22
32
|
const homePath = ctx.get('dshHomePath');
|
|
23
33
|
const home = homePath ? homePath() : process.env.DSH_HOME || join(homedir(), '.dsh');
|
|
24
34
|
const service = resolveServiceOptions(input);
|
|
@@ -45,6 +55,25 @@ export async function apply(ctx, input = {}) {
|
|
|
45
55
|
const processRequests = input.a2a?.workbench ? createWorkbenchProcessClient(input.a2a.workbench) : undefined;
|
|
46
56
|
const adapter = new AcpAdapter(ctx, config, diagnostics, processRequests);
|
|
47
57
|
ctx.effect(() => ctx.llm.registerAdapter(['1agents-acp'], adapter));
|
|
58
|
+
// Archiving a Session in DSH stops its work but never reaches the service daemon, where the
|
|
59
|
+
// ACP process and its device capacity slot live. Sweep the Host's archive set so an archived
|
|
60
|
+
// session gives its slot back at once instead of holding it until the daemon restarts.
|
|
61
|
+
ctx.effect(() => {
|
|
62
|
+
const interval = Number(process.env.DSH_ACP_ARCHIVE_SWEEP_MS);
|
|
63
|
+
const every = Number.isFinite(interval) && interval >= 0 ? interval : 2000;
|
|
64
|
+
if (every === 0)
|
|
65
|
+
return () => undefined;
|
|
66
|
+
const timer = setInterval(() => {
|
|
67
|
+
// Read the live archive set rather than a captured copy; the registry mutates it in place.
|
|
68
|
+
const registry = ctx.get('workspaceRegistry');
|
|
69
|
+
const archived = registry?.archivedSessionIds ?? [];
|
|
70
|
+
if (archived.length === 0)
|
|
71
|
+
return;
|
|
72
|
+
void adapter.releaseArchivedSessions(new Set(archived.map(String)));
|
|
73
|
+
}, every);
|
|
74
|
+
timer.unref?.();
|
|
75
|
+
return () => clearInterval(timer);
|
|
76
|
+
});
|
|
48
77
|
// A Cordis listener is released with this plugin's fiber.
|
|
49
78
|
if (processRequests)
|
|
50
79
|
registerNativeApprovals(ctx, processRequests);
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
export interface SyncGlobalOptions {
|
|
2
|
+
packageDir?: string;
|
|
3
|
+
env?: NodeJS.ProcessEnv;
|
|
4
|
+
execFile?: (command: string, args: readonly string[], env: NodeJS.ProcessEnv) => Promise<{
|
|
5
|
+
stdout: string;
|
|
6
|
+
}>;
|
|
7
|
+
}
|
|
8
|
+
export interface SyncGlobalResult {
|
|
9
|
+
updated: boolean;
|
|
10
|
+
version: string;
|
|
11
|
+
from?: string;
|
|
12
|
+
reason?: string;
|
|
13
|
+
}
|
|
14
|
+
/** The installed @1agents/acp-service directory that contains this module. */
|
|
15
|
+
export declare function packageDirectory(moduleUrl?: string): string;
|
|
16
|
+
/** DSH profile installs only. A workspace checkout and the global install itself do not recurse. */
|
|
17
|
+
export declare function shouldSyncGlobal(packageDir: string, env?: NodeJS.ProcessEnv): boolean;
|
|
18
|
+
/** Install this exact package over the global CLI when its version differs. */
|
|
19
|
+
export declare function syncGlobalAcpService(options?: SyncGlobalOptions): Promise<SyncGlobalResult>;
|
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
/** Keep the global acp-service CLI on the same version as this DSH plugin install. */
|
|
2
|
+
import { execFile } from 'node:child_process';
|
|
3
|
+
import { existsSync, readFileSync } from 'node:fs';
|
|
4
|
+
import { dirname, join } from 'node:path';
|
|
5
|
+
import { fileURLToPath } from 'node:url';
|
|
6
|
+
import { promisify } from 'node:util';
|
|
7
|
+
const exec = promisify(execFile);
|
|
8
|
+
const PACKAGE = '@1agents/acp-service';
|
|
9
|
+
/** The installed @1agents/acp-service directory that contains this module. */
|
|
10
|
+
export function packageDirectory(moduleUrl = import.meta.url) {
|
|
11
|
+
let dir = dirname(fileURLToPath(moduleUrl));
|
|
12
|
+
for (let depth = 0; depth < 6; depth += 1) {
|
|
13
|
+
const manifestPath = join(dir, 'package.json');
|
|
14
|
+
if (existsSync(manifestPath)) {
|
|
15
|
+
try {
|
|
16
|
+
const manifest = JSON.parse(readFileSync(manifestPath, 'utf8'));
|
|
17
|
+
if (manifest.name === PACKAGE)
|
|
18
|
+
return dir;
|
|
19
|
+
}
|
|
20
|
+
catch { /* A broken manifest is not this package. */ }
|
|
21
|
+
}
|
|
22
|
+
const parent = dirname(dir);
|
|
23
|
+
if (parent === dir)
|
|
24
|
+
break;
|
|
25
|
+
dir = parent;
|
|
26
|
+
}
|
|
27
|
+
throw new Error(`${PACKAGE} package root was not found`);
|
|
28
|
+
}
|
|
29
|
+
function readVersion(directory) {
|
|
30
|
+
try {
|
|
31
|
+
const manifest = JSON.parse(readFileSync(join(directory, 'package.json'), 'utf8'));
|
|
32
|
+
if (manifest.name !== PACKAGE || typeof manifest.version !== 'string' || !manifest.version)
|
|
33
|
+
return undefined;
|
|
34
|
+
return manifest.version;
|
|
35
|
+
}
|
|
36
|
+
catch {
|
|
37
|
+
return undefined;
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
/** DSH profile installs only. A workspace checkout and the global install itself do not recurse. */
|
|
41
|
+
export function shouldSyncGlobal(packageDir, env = process.env) {
|
|
42
|
+
if (env.ACP_SERVICE_SKIP_GLOBAL_SYNC === '1' || env.ACP_SERVICE_SYNC_GLOBAL === '0')
|
|
43
|
+
return false;
|
|
44
|
+
if (env.ACP_SERVICE_SYNC_GLOBAL === '1')
|
|
45
|
+
return true;
|
|
46
|
+
return /[/\\]\.dsh[/\\]profiles[/\\]/.test(packageDir);
|
|
47
|
+
}
|
|
48
|
+
/** Install this exact package over the global CLI when its version differs. */
|
|
49
|
+
export async function syncGlobalAcpService(options = {}) {
|
|
50
|
+
const env = options.env ?? process.env;
|
|
51
|
+
const packageDir = options.packageDir ?? packageDirectory();
|
|
52
|
+
const version = readVersion(packageDir);
|
|
53
|
+
if (!version)
|
|
54
|
+
throw new Error(`${PACKAGE} version was not found`);
|
|
55
|
+
if (!shouldSyncGlobal(packageDir, env))
|
|
56
|
+
return { updated: false, version, reason: 'not-a-dsh-profile-install' };
|
|
57
|
+
const run = options.execFile ?? (async (command, args, commandEnv) => {
|
|
58
|
+
const result = await exec(command, args, { env: commandEnv, timeout: 120_000, maxBuffer: 1024 * 1024 });
|
|
59
|
+
return { stdout: result.stdout };
|
|
60
|
+
});
|
|
61
|
+
const root = (await run('npm', ['root', '-g'], env)).stdout.trim();
|
|
62
|
+
if (!root)
|
|
63
|
+
throw new Error('npm root -g returned an empty path');
|
|
64
|
+
const from = readVersion(join(root, PACKAGE));
|
|
65
|
+
if (from === version)
|
|
66
|
+
return { updated: false, version, from, reason: 'already-current' };
|
|
67
|
+
await run('npm', ['install', '-g', packageDir, '--no-fund', '--no-audit'], { ...env, ACP_SERVICE_SKIP_GLOBAL_SYNC: '1' });
|
|
68
|
+
return { updated: true, version, ...(from ? { from } : {}) };
|
|
69
|
+
}
|
|
70
|
+
const invokedDirectly = process.argv[1] && fileURLToPath(import.meta.url) === process.argv[1];
|
|
71
|
+
if (invokedDirectly) {
|
|
72
|
+
syncGlobalAcpService().then(result => {
|
|
73
|
+
if (result.updated)
|
|
74
|
+
console.log(`acp-service global CLI updated ${result.from ?? '(none)'} -> ${result.version}`);
|
|
75
|
+
else
|
|
76
|
+
console.log(`acp-service global CLI unchanged (${result.reason ?? result.version})`);
|
|
77
|
+
}).catch(error => {
|
|
78
|
+
console.warn(`acp-service global CLI was not updated: ${error instanceof Error ? error.message : String(error)}`);
|
|
79
|
+
process.exitCode = 0;
|
|
80
|
+
});
|
|
81
|
+
}
|