@1agents/acp-service 0.8.2 → 0.9.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 (76) hide show
  1. package/README.md +6 -0
  2. package/dist/bin/a2a.js +10 -2
  3. package/dist/bin/acp-service.js +6 -0
  4. package/dist/bin/roles.d.ts +1 -0
  5. package/dist/bin/roles.js +24 -0
  6. package/dist/src/a2a/executor.d.ts +16 -1
  7. package/dist/src/a2a/executor.js +205 -19
  8. package/dist/src/a2a/gateway.d.ts +77 -0
  9. package/dist/src/a2a/gateway.js +349 -27
  10. package/dist/src/a2a/index.d.ts +7 -1
  11. package/dist/src/a2a/index.js +4 -0
  12. package/dist/src/a2a/result-metadata.d.ts +3 -0
  13. package/dist/src/a2a/result-metadata.js +2 -1
  14. package/dist/src/a2a/server.js +2 -1
  15. package/dist/src/a2a/store.js +7 -1
  16. package/dist/src/a2a/types.d.ts +32 -1
  17. package/dist/src/a2a/types.js +11 -1
  18. package/dist/src/acp-connection.js +93 -12
  19. package/dist/src/bridge.js +127 -4
  20. package/dist/src/capacity-lifecycle.d.ts +5 -0
  21. package/dist/src/capacity-lifecycle.js +57 -0
  22. package/dist/src/capacity-queue.d.ts +23 -0
  23. package/dist/src/capacity-queue.js +251 -0
  24. package/dist/src/capacity.d.ts +76 -0
  25. package/dist/src/capacity.js +377 -0
  26. package/dist/src/execution/human-review.d.ts +103 -0
  27. package/dist/src/execution/human-review.js +87 -0
  28. package/dist/src/execution/ledger.d.ts +5 -0
  29. package/dist/src/execution/ledger.js +39 -8
  30. package/dist/src/execution/ppt-delivery.d.ts +36 -3
  31. package/dist/src/execution/ppt-delivery.js +243 -53
  32. package/dist/src/execution/project-discovery.d.ts +56 -0
  33. package/dist/src/execution/project-discovery.js +429 -0
  34. package/dist/src/execution/report-review.d.ts +60 -0
  35. package/dist/src/execution/report-review.js +173 -0
  36. package/dist/src/execution/targets.d.ts +5 -0
  37. package/dist/src/execution/targets.js +1 -0
  38. package/dist/src/execution/workbench.d.ts +131 -0
  39. package/dist/src/execution/workbench.js +265 -0
  40. package/dist/src/index.d.ts +4 -0
  41. package/dist/src/index.js +3 -0
  42. package/dist/src/roles/index.d.ts +1 -0
  43. package/dist/src/roles/index.js +1 -0
  44. package/dist/src/roles/skills.d.ts +71 -0
  45. package/dist/src/roles/skills.js +427 -0
  46. package/package.json +5 -1
  47. package/skills/acp-service/SKILL.md +21 -7
  48. package/skills/acp-service/references/a2a.md +9 -5
  49. package/skills/acp-service/references/async-caller.md +48 -0
  50. package/skills/acp-service/references/roles-and-tasks.md +120 -0
  51. package/skills/acp-service/scripts/a2a-caller.py +242 -0
  52. package/vendor/dsh/README.md +2 -0
  53. package/vendor/dsh/a2a-executor.d.ts +4 -1
  54. package/vendor/dsh/a2a-executor.js +46 -2
  55. package/vendor/dsh/adapter.d.ts +10 -0
  56. package/vendor/dsh/adapter.js +67 -3
  57. package/vendor/dsh/client.js +84 -24
  58. package/vendor/dsh/index.js +2 -1
  59. package/vendor/runtime/dist/{cli-DeOpE2Xz.js → cli-DXmYwv3U.js} +4 -4
  60. package/vendor/runtime/dist/{cli-DeOpE2Xz.js.map → cli-DXmYwv3U.js.map} +1 -1
  61. package/vendor/runtime/dist/cli.js +7 -7
  62. package/vendor/runtime/dist/client-VQsqcIOJ.d.ts.map +1 -1
  63. package/vendor/runtime/dist/docs-site/runtime-process-lifecycle.html +1 -0
  64. package/vendor/runtime/dist/{flows-oaBGn31w.js → flows-DJ17ajbw.js} +3 -3
  65. package/vendor/runtime/dist/{flows-oaBGn31w.js.map → flows-DJ17ajbw.js.map} +1 -1
  66. package/vendor/runtime/dist/flows.js +1 -1
  67. package/vendor/runtime/dist/{invocation-options-CUDEE8vW.js → invocation-options-PBfCgrdi.js} +3 -3
  68. package/vendor/runtime/dist/{invocation-options-CUDEE8vW.js.map → invocation-options-PBfCgrdi.js.map} +1 -1
  69. package/vendor/runtime/dist/{output-CFv3jcOQ.js → output-B3MDn7kv.js} +2 -2
  70. package/vendor/runtime/dist/{output-CFv3jcOQ.js.map → output-B3MDn7kv.js.map} +1 -1
  71. package/vendor/runtime/dist/{queue-owner-runtime-DvMJiGbP.js → queue-owner-runtime-DXCVngwU.js} +15 -8
  72. package/vendor/runtime/dist/queue-owner-runtime-DXCVngwU.js.map +1 -0
  73. package/vendor/runtime/dist/runtime.js +1 -1
  74. package/vendor/runtime/dist/{session-watch-Di-wIdCH.js → session-watch-DURyCw31.js} +2 -2
  75. package/vendor/runtime/dist/{session-watch-Di-wIdCH.js.map → session-watch-DURyCw31.js.map} +1 -1
  76. package/vendor/runtime/dist/queue-owner-runtime-DvMJiGbP.js.map +0 -1
package/README.md CHANGED
@@ -73,6 +73,8 @@ pnpm start:service serve --host 127.0.0.1 --port 36812 --no-report
73
73
 
74
74
  The default port is 36812. Without `--no-report`, the service reports to the local DreamMate node. Agent executables and their authentication must be available to the service process. `ACP_STATE_DIR` overrides the default `~/.1agents/acpx-state` directory for runtime records, turn journals and ACP replay data.
75
75
 
76
+ Automatic launches now share a device capacity ledger and FIFO queue. Admission checks current available memory immediately before startup, keeps a configurable reserve, and also enforces estimated soft/hard concurrency limits. A2A work stays `SUBMITTED` (Pending) while resources are unavailable, then starts in queue order; queued work can be canceled. ACP launches, probes and pre-warming use the same memory protection. Native user sessions outside this service continue independently. See [device capacity and queue policy](../../docs/device-capacity-queue-20261023.md) for defaults, environment variables, scope and restart behavior.
77
+
76
78
  For npm-backed agents, the service first uses an adapter package installed in its package search roots, then the runtime's adapter executable on PATH or in user-local binary directories. JavaScript adapters run with the service's Node interpreter. Only when an adapter is absent does launch fall back to npx; discovery itself never downloads packages. Installing the native `codex` CLI does not replace installing the `codex-acp` adapter.
77
79
 
78
80
  If startup reports npm `ENOTEMPTY` inside `_npx`, upgrade npm and move the affected cache directory aside once no installation is using it, then retry. The diagnostic preserves npm's failing path. This error concerns npm's cache directory replacement rather than macOS device permissions.
@@ -377,6 +379,10 @@ A2A 网关增加版本化执行目标目录和任务台账。父任务与子任
377
379
  - 可选 `binding.driver=ppt_delivery` 使用独立领域模块推进项目脚本、制作、确定性校验、独立事实/逐页视觉复核及有限返工。父任务等待时仍为 working;它不把阶段调度加入通用台账。
378
380
  - `execution_inbox/ack` 处理领域交付通知,`execution_review` 独立记录绑定具体轮次、结果版本与 digest 的业务接受。角色通知使用独立 `execution-notice:` 标识,不伪造远端 A2A Task。
379
381
 
382
+ 通用 A2A 结果完成后,账本自动生成执行轮次内的 `resultRevision`(`result-1`、`result-2`…)和 `resultDigest`,由 `execution_get` 与 `remote_agent_get` 返回。digest 是规范化 JSON 的 SHA256,覆盖结果正文、结构化回执引用、产物链接和宿主返回的文件大小/SHA256 清单 `resultArtifacts`,不包含查询时间。没有文件清单时只绑定已返回的结果与链接,不能据此声称校验了文件字节。PPT 交付保留其领域生成的版本与 digest。
383
+
384
+ 相同结果的重复读取与重启不会新增版本;结果变化保存新版本,`execution_get/list` 的 `resultHistory` 展示当前轮次的版本快照,历史轮次在 `attempts[].resultHistory` 中保留,版本变化事件携带版本和 digest。已存在的版本不可覆盖,也不可重新选用已被替代的版本。业务验收只接受当前已完成、结果可用的 `attemptId/resultRevision/resultDigest`;结果或执行轮次变化后不继承旧验收,原结论留在 `acceptanceHistory`。网关升级时从已保存的 A2A 完成回执补齐缺失版本,不重跑任务、不新增通知、不自动写业务接受。
385
+
380
386
  状态为 gateway.json v2,首次升级前备份。执行端和网关应使用同一冻结完整安装包;角色策略与人工目标配置保存在受保护部署目录,公共样例见 [PPT 交付说明](../../examples/ppt-beautifier/delivery-README.md)。网关周期向 Node 重报备,Node 暂时不可用不影响直接调用。
381
387
 
382
388
  本阶段不实现 AP 执行 Provider、AP 投影或通用 DAG 引擎;workflow 可登记但执行明确返回 unsupported。未知受理保持待核对;领域父任务 input_required 后本版本不自动恢复,需要明确处理,不能把超时当作远端已停止。目录策略是执行准入检查,不是操作系统沙箱。通知入队不等于主会话已实际唤醒,真实闭环需另存新轮次证据。
package/dist/bin/a2a.js CHANGED
@@ -18,7 +18,13 @@ invoke reads a JSON parameters object from stdin. Credentials stay in the
18
18
  gateway config file (chmod 600), outside tool arguments. Remote cwd is absolute.
19
19
  Methods: remote_agent_preflight, remote_agent_spawn, remote_agent_get, remote_agent_message,
20
20
  remote_agent_cancel, remote_agent_list, remote_agent_inbox, remote_agent_ack,
21
- session_bind, session_send, session_delivery_get, session_delivery_resolve`);
21
+ session_bind, session_send, session_delivery_get, session_delivery_resolve,
22
+ execution_project_scan, execution_project_list,
23
+ execution_discovery_config_get, execution_discovery_config_update
24
+
25
+ Project discovery requires trusted gateway projectDiscovery configuration.
26
+ It defaults to manual; scan/list only cache role candidates, without registering
27
+ execution targets or starting tasks. Optional interval mode runs in the gateway.`);
22
28
  return;
23
29
  }
24
30
  if (args[0] === 'gateway') {
@@ -30,7 +36,9 @@ Methods: remote_agent_preflight, remote_agent_spawn, remote_agent_get, remote_ag
30
36
  throw new Error('Gateway config contains credentials; set chmod 600');
31
37
  const config = JSON.parse(fs.readFileSync(file, 'utf8'));
32
38
  const host = await serveA2AGateway(config, { report: !args.includes('--no-report') });
33
- console.log(`a2a-gateway listening on http://127.0.0.1:${host.port}; registration=${host.registration?.ok ?? false}`);
39
+ const registration = host.registration?.ok ?? false;
40
+ const reason = host.registration && !host.registration.ok ? ` reason=${host.registration?.reason ?? 'unknown reason'}` : '';
41
+ console.log(`a2a-gateway listening on http://127.0.0.1:${host.port}; registration=${registration}${reason}`);
34
42
  if (host.automationPort !== undefined)
35
43
  console.log(`a2a automation listening on http://${host.gateway.config.automation.host}:${host.automationPort}`);
36
44
  const stop = () => { void host.close().then(() => { process.exitCode = 0; }); };
@@ -53,6 +53,7 @@ function printUnifiedHelp(binName) {
53
53
  .replace(/^Usage:\s+acpx/m, `Usage: ${binName}`)
54
54
  .replace(/Headless CLI client for the Agent Client Protocol/, 'Headless CLI client & DreamMate Network runtime service for the Agent Client Protocol (ACP)');
55
55
  const serverCommands = `Commands:
56
+ roles sync --profile <file> Resolve current network skills into a versioned task lock
56
57
  a2a gateway --config <file> Start persistent remote-agent tools and completion inbox
57
58
  a2a invoke <method> Invoke local remote-agent tools (JSON params on stdin)
58
59
  serve [options] Start DreamMate Network ACP runtime daemon (HTTP + WS)`;
@@ -117,6 +118,11 @@ async function runServer(options) {
117
118
  }
118
119
  }
119
120
  async function main() {
121
+ if (rawArgs[0] === 'roles') {
122
+ const { runRolesCli } = await import('./roles.js');
123
+ await runRolesCli(rawArgs.slice(1));
124
+ return;
125
+ }
120
126
  if (rawArgs.includes('--skill')) {
121
127
  const { maybeHandleSkillflag } = await import('skillflag');
122
128
  const packageRoot = path.dirname(require.resolve('@1agents/acp-service/package.json'));
@@ -0,0 +1 @@
1
+ export declare function runRolesCli(argv: string[]): Promise<void>;
@@ -0,0 +1,24 @@
1
+ /** Explicit cache administration; task execution uses the same resolver in its host. */
2
+ import { randomUUID } from 'node:crypto';
3
+ import { join, resolve } from 'node:path';
4
+ import { parseArgs } from 'node:util';
5
+ import { resolveRoleSkills } from '../src/roles/index.js';
6
+ export async function runRolesCli(argv) {
7
+ if (!argv.length || argv.includes('--help') || argv.includes('-h')) {
8
+ console.log('Usage: acp-service roles sync --profile FILE [--cache-root DIRECTORY] [--lock FILE]\n\nDefault cache: CWD/.1agents/cache/roles. A new lock resolves current revisions; an existing lock is verified and reused offline. No model is invoked.');
9
+ return;
10
+ }
11
+ if (argv[0] !== 'sync')
12
+ throw new Error('Unknown roles command; use roles sync --help');
13
+ const { values } = parseArgs({ args: argv.slice(1), options: {
14
+ profile: { type: 'string' }, 'cache-root': { type: 'string' }, lock: { type: 'string' },
15
+ }, strict: true });
16
+ if (!values.profile)
17
+ throw new Error('--profile is required');
18
+ const cacheRoot = resolve(values['cache-root'] ?? '.1agents/cache/roles');
19
+ const lockPath = resolve(values.lock ?? join(cacheRoot, 'locks', `manual-${randomUUID()}.json`));
20
+ const lock = await resolveRoleSkills({ profilePath: resolve(values.profile), cacheRoot, lockPath });
21
+ console.log(JSON.stringify({ roleId: lock.roleId, roleVersion: lock.roleVersion, lockPath,
22
+ roleDirectory: lock.roleDirectory, entryGuidePath: lock.entryGuidePath,
23
+ skills: lock.skills.map(({ key, skillId, sourceId, revision, directory }) => ({ key, skillId, sourceId, revision, directory })) }, null, 2));
24
+ }
@@ -1,13 +1,25 @@
1
1
  import { type SendMessageRequest } from '@a2a-js/sdk';
2
2
  import { type AgentExecutor, type ExecutionEventBus, type RequestContext } from '@a2a-js/sdk/server';
3
3
  import type { FileA2AStore } from './store.js';
4
- import type { A2ABackend, A2APrepareInput } from './types.js';
4
+ import { type A2ABackend, type A2APrepareInput } from './types.js';
5
5
  import { type A2AResultContract } from './result-metadata.js';
6
+ import { type CapacityOptions } from '../capacity.js';
6
7
  export interface A2AExecutionOptions {
8
+ /** Trusted host policy. All A2A executions are automatic; request metadata cannot override it. */
9
+ capacity?: CapacityOptions;
7
10
  defaultCwd?: string;
8
11
  defaultAgentPreset?: string;
9
12
  workspaces?: Record<string, string>;
13
+ /** Profiles and the writable cache root are controlled by the execution host. */
14
+ roleSkills?: {
15
+ cacheRoot: string;
16
+ profiles: Record<string, string>;
17
+ /** Optional compatibility binding for fresh fixed-preset contexts only. */
18
+ presetRoles?: Record<string, string>;
19
+ };
10
20
  }
21
+ /** Validate trusted host configuration before acquiring a state-directory lease. */
22
+ export declare function validateA2AExecutionOptions(options: A2AExecutionOptions): void;
11
23
  /** Validate application metadata before the SDK starts an execution. */
12
24
  export declare function parseA2AInput(request: SendMessageRequest, options: A2AExecutionOptions): {
13
25
  prompt: string;
@@ -19,11 +31,14 @@ export declare class A2ASessionExecutor implements AgentExecutor {
19
31
  private readonly backend;
20
32
  private readonly store;
21
33
  private readonly options;
34
+ private readonly capacity;
22
35
  private readonly active;
23
36
  private readonly awaitingInput;
24
37
  private readonly preparing;
25
38
  private stopped;
26
39
  constructor(backend: A2ABackend, store: FileA2AStore, options: A2AExecutionOptions);
40
+ private roleIdFor;
41
+ private roleFor;
27
42
  isRunning(taskId: string): boolean;
28
43
  execute(context: RequestContext, bus: ExecutionEventBus): Promise<void>;
29
44
  cancelTask(taskId: string, bus: ExecutionEventBus): Promise<void>;
@@ -1,12 +1,18 @@
1
1
  /** Official A2A executor with durable DSH context bindings and independent turns. */
2
- import { randomUUID } from 'node:crypto';
2
+ import { createHash, randomUUID } from 'node:crypto';
3
+ import { lstat, mkdir, readFile, realpath } from 'node:fs/promises';
4
+ import { isAbsolute, join, relative, sep } from 'node:path';
3
5
  import { Role, Task, TaskState, Message } from '@a2a-js/sdk';
4
6
  import { ContentTypeNotSupportedError, RequestMalformedError, UnsupportedOperationError } from '@a2a-js/sdk/errors';
5
7
  import { AgentEvent, resolveUserScope } from '@a2a-js/sdk/server';
6
8
  import { a2aRequestId } from './request-id.js';
7
9
  import { toSafeError } from '@1agents/acp-service/runtime';
10
+ import { a2aRoleSkillsSchema } from './types.js';
11
+ import { resolveRoleSkills } from '../roles/index.js';
8
12
  import { A2APreflightError, a2aPreflightRequirementsSchema } from './preflight.js';
9
13
  import { a2aResultContractSchema, A2AResultValidationError, createA2AResultMetadata, saveA2AResultMetadata } from './result-metadata.js';
14
+ import { CapacityGovernor, CapacityError } from '../capacity.js';
15
+ import { CapacityQueue } from '../capacity-queue.js';
10
16
  const FAILURE_MESSAGES = {
11
17
  'missing-final-answer': 'DSH completed the task without a final answer; ACP final-answer metadata contained no final output',
12
18
  'max-tokens': 'DSH reached the model output token limit',
@@ -17,6 +23,39 @@ const FAILURE_MESSAGES = {
17
23
  aborted: 'DSH task execution was canceled',
18
24
  interrupted: 'DSH task execution was interrupted',
19
25
  };
26
+ /** Validate trusted host configuration before acquiring a state-directory lease. */
27
+ export function validateA2AExecutionOptions(options) {
28
+ new CapacityGovernor(options.capacity);
29
+ const roles = options.roleSkills;
30
+ if (roles === undefined)
31
+ return;
32
+ if (!roles || typeof roles !== 'object' || typeof roles.cacheRoot !== 'string' || !isAbsolute(roles.cacheRoot) || roles.cacheRoot.includes('\0')
33
+ || !roles.profiles || typeof roles.profiles !== 'object' || Array.isArray(roles.profiles)
34
+ || Object.entries(roles.profiles).some(([id, path]) => !/^[A-Za-z0-9][A-Za-z0-9._:-]{0,255}$/.test(id)
35
+ || typeof path !== 'string' || !isAbsolute(path) || path.includes('\0')))
36
+ throw new Error('Role skills require host-owned absolute cache and profile paths');
37
+ if (roles.presetRoles !== undefined && (!roles.presetRoles || typeof roles.presetRoles !== 'object' || Array.isArray(roles.presetRoles)
38
+ || Object.entries(roles.presetRoles).some(([preset, roleId]) => !preset.trim() || preset.length > 256 || preset.includes('\0')
39
+ || typeof roleId !== 'string' || !Object.hasOwn(roles.profiles, roleId))))
40
+ throw new Error('Role preset bindings must reference registered host profiles');
41
+ }
42
+ class RoleSkillLoadingError extends Error {
43
+ constructor(cause) { super('Role skills could not be loaded or verified; the model was not started', { cause }); }
44
+ }
45
+ async function waitForPreparation(previous, signal) {
46
+ signal.throwIfAborted();
47
+ let abort;
48
+ const canceled = new Promise((_, reject) => {
49
+ abort = () => reject(signal.reason);
50
+ signal.addEventListener('abort', abort, { once: true });
51
+ });
52
+ try {
53
+ await Promise.race([previous, canceled]);
54
+ }
55
+ finally {
56
+ signal.removeEventListener('abort', abort);
57
+ }
58
+ }
20
59
  /** Validate application metadata before the SDK starts an execution. */
21
60
  export function parseA2AInput(request, options) {
22
61
  const message = request.message;
@@ -33,12 +72,18 @@ export function parseA2AInput(request, options) {
33
72
  throw new RequestMalformedError('metadata.1agents must be an object');
34
73
  const value = (metadata ?? {});
35
74
  for (const key of Object.keys(value))
36
- if (!['cwd', 'agentPreset', 'workspace', 'preflight', 'resultContract'].includes(key))
75
+ if (!['cwd', 'agentPreset', 'workspace', 'preflight', 'resultContract', 'roleId', 'roleLockPath'].includes(key))
37
76
  throw new RequestMalformedError(`Unknown metadata.1agents field: ${key}`);
38
- for (const key of ['cwd', 'agentPreset', 'workspace']) {
77
+ for (const key of ['cwd', 'agentPreset', 'workspace', 'roleId', 'roleLockPath']) {
39
78
  if (value[key] !== undefined && (typeof value[key] !== 'string' || !value[key].trim()))
40
79
  throw new RequestMalformedError(`${key} must be a nonempty string`);
41
80
  }
81
+ if (value.roleId !== undefined && (!/^[A-Za-z0-9][A-Za-z0-9._:-]{0,255}$/.test(value.roleId)
82
+ || !options.roleSkills || !Object.hasOwn(options.roleSkills.profiles, value.roleId)))
83
+ throw new RequestMalformedError('Unknown host role');
84
+ if (value.roleLockPath !== undefined && (!options.roleSkills || !isAbsolute(value.roleLockPath)
85
+ || value.roleLockPath.includes('\0')))
86
+ throw new RequestMalformedError('Invalid role lock path');
42
87
  if (value.cwd && value.workspace)
43
88
  throw new RequestMalformedError('Use cwd or workspace, not both');
44
89
  let cwd = value.cwd;
@@ -54,7 +99,9 @@ export function parseA2AInput(request, options) {
54
99
  if (resultContract && !resultContract.success)
55
100
  throw new RequestMalformedError('Invalid result contract');
56
101
  return { prompt, input: { cwd, agentPreset: value.agentPreset,
57
- ...(preflight?.success ? { preflight: preflight.data } : {}) },
102
+ ...(preflight?.success ? { preflight: preflight.data } : {}),
103
+ ...(value.roleId ? { roleId: value.roleId } : {}),
104
+ ...(value.roleLockPath ? { roleLockPath: value.roleLockPath } : {}) },
58
105
  ...(resultContract?.success ? { resultContract: resultContract.data } : {}) };
59
106
  }
60
107
  /** SDK owns the execution lifetime; an HTTP disconnect never aborts this signal. */
@@ -62,6 +109,7 @@ export class A2ASessionExecutor {
62
109
  backend;
63
110
  store;
64
111
  options;
112
+ capacity;
65
113
  active = new Map();
66
114
  awaitingInput = new Map();
67
115
  preparing = new Map();
@@ -70,6 +118,63 @@ export class A2ASessionExecutor {
70
118
  this.backend = backend;
71
119
  this.store = store;
72
120
  this.options = options;
121
+ validateA2AExecutionOptions(options);
122
+ this.capacity = new CapacityQueue(options.capacity);
123
+ }
124
+ roleIdFor(input, saved) {
125
+ if (input.roleId)
126
+ return input.roleId;
127
+ // Existing contexts keep their original typed or untyped identity even if
128
+ // the host later adds or changes preset-to-role compatibility bindings.
129
+ if (saved)
130
+ return saved.roleId;
131
+ const preset = input.agentPreset ?? this.options.defaultAgentPreset, bindings = this.options.roleSkills?.presetRoles;
132
+ return preset && bindings && Object.hasOwn(bindings, preset) ? bindings[preset] : undefined;
133
+ }
134
+ async roleFor(input, saved, contextKey, signal) {
135
+ const roleId = this.roleIdFor(input, saved);
136
+ if (!roleId) {
137
+ if (input.roleLockPath)
138
+ throw new Error('A role lock requires a role identity');
139
+ return undefined;
140
+ }
141
+ if (saved && (!saved.roleSkills || saved.roleId !== roleId))
142
+ throw new Error('An existing context cannot change its role');
143
+ const configuration = this.options.roleSkills;
144
+ if (!configuration || !Object.hasOwn(configuration.profiles, roleId))
145
+ throw new Error('The saved role is no longer configured on this host');
146
+ await mkdir(join(configuration.cacheRoot, 'locks'), { recursive: true, mode: 0o700 });
147
+ const lockRootInfo = await lstat(join(configuration.cacheRoot, 'locks'));
148
+ if (!lockRootInfo.isDirectory() || lockRootInfo.isSymbolicLink())
149
+ throw new Error('The host role locks directory must be a real directory');
150
+ const lockRoot = await realpath(join(configuration.cacheRoot, 'locks'));
151
+ const existingPath = saved?.roleSkills?.lockPath ?? input.roleLockPath;
152
+ let lockPath;
153
+ if (existingPath) {
154
+ const info = await lstat(existingPath);
155
+ const actual = await realpath(existingPath), tail = relative(lockRoot, actual);
156
+ if (!info.isFile() || info.isSymbolicLink() || tail === '' || tail === '..' || tail.startsWith(`..${sep}`) || isAbsolute(tail))
157
+ throw new Error('Role lock must be an existing regular file inside the host locks directory');
158
+ // Preserve a saved summary byte-for-byte when a migrated cache retains
159
+ // the old root as a compatible alias. Fresh contexts use canonical paths.
160
+ lockPath = saved?.roleSkills?.lockPath ?? actual;
161
+ if (saved?.roleSkills && input.roleLockPath && await realpath(input.roleLockPath) !== actual)
162
+ throw new Error('An existing context cannot change its role lock');
163
+ }
164
+ else {
165
+ lockPath = join(lockRoot, `a2a-${createHash('sha256').update(contextKey).digest('hex')}.json`);
166
+ }
167
+ const lock = await resolveRoleSkills({ profilePath: configuration.profiles[roleId], cacheRoot: configuration.cacheRoot, lockPath, signal });
168
+ const summary = a2aRoleSkillsSchema.parse({ roleId: lock.roleId, roleVersion: lock.roleVersion, lockPath,
169
+ roleDirectory: lock.roleDirectory, ...(lock.entryGuidePath ? { entryGuidePath: lock.entryGuidePath } : {}),
170
+ skills: lock.skills.map(({ key, skillId, sourceId, name, revision, directory, guidePath }) => ({ key, skillId, sourceId, name, revision, directory, guidePath })) });
171
+ if (saved?.roleSkills && JSON.stringify(saved.roleSkills) !== JSON.stringify(summary))
172
+ throw new Error('Saved role skill identity differs from its verified lock');
173
+ const instructions = lock.instructionsPath ? await readFile(lock.instructionsPath, 'utf8') : '';
174
+ if (Buffer.byteLength(instructions) > 65536)
175
+ throw new Error('Role instructions exceed the host prompt budget');
176
+ const guides = summary.skills.map(skill => `- ${skill.key}: ${skill.guidePath} (revision=${skill.revision})`).join('\n');
177
+ return { roleId, summary, promptPrefix: `宿主已加载角色 ${roleId},本任务技能锁:${lockPath}。仅使用此锁及下列缓存技能,不重新检索或切换版本;续派和恢复沿用同一锁。先读取适用指南及其配套资源。\n${guides}\n${instructions}\n\n上游任务:\n` };
73
178
  }
74
179
  isRunning(taskId) { return this.active.has(taskId); }
75
180
  async execute(context, bus) {
@@ -89,6 +194,8 @@ export class A2ASessionExecutor {
89
194
  const startedAt = new Date().toISOString();
90
195
  let resultContract;
91
196
  let resultMetadata;
197
+ let capacityLease;
198
+ let capacityFailure;
92
199
  // DSH deduplicates prompts by rpcId across the whole session. A Task can
93
200
  // have several input-required turns, each with its own message identity.
94
201
  const requestId = a2aRequestId(context.taskId, context.userMessage.messageId);
@@ -96,42 +203,112 @@ export class A2ASessionExecutor {
96
203
  bus.publish(AgentEvent.statusUpdate({ taskId: context.taskId, contextId: context.contextId,
97
204
  status: { state, timestamp: new Date().toISOString(), message: text ? Message.fromJSON({
98
205
  messageId: randomUUID(), role: 'ROLE_AGENT', contextId: context.contextId, taskId: context.taskId, parts: [{ text }],
99
- }) : undefined }, metadata: error || resultMetadata ? { '1agents': {
206
+ }) : undefined }, metadata: target || error || resultMetadata ? { '1agents': {
100
207
  ...target, ...(resultMetadata ? { result: resultMetadata } : {}), ...(error ? { error } : {}),
101
208
  } } : undefined }));
102
209
  };
210
+ const submitted = (text) => {
211
+ if (published)
212
+ return;
213
+ const task = Task.fromJSON({ ...Task.toJSON(context.task ?? Task.fromJSON({ id: context.taskId, contextId: context.contextId })),
214
+ status: { state: 'TASK_STATE_SUBMITTED', timestamp: new Date().toISOString(),
215
+ ...(text ? { message: { messageId: randomUUID(), role: 'ROLE_AGENT', contextId: context.contextId,
216
+ taskId: context.taskId, parts: [{ text }] } } : {}) },
217
+ metadata: { ...context.task?.metadata, '1agents': target ?? {} } });
218
+ bus.publish(AgentEvent.task(task));
219
+ published = true;
220
+ };
221
+ const pendingCapacity = () => {
222
+ const message = 'Pending: waiting in FIFO order for device memory and ACP capacity.';
223
+ submitted(message);
224
+ status(TaskState.TASK_STATE_SUBMITTED, message);
225
+ };
226
+ const acquireCapacity = (signal = controller.signal) => this.capacity.acquire({ kind: 'task', source: 'automatic', id: requestId }, {
227
+ signal, onPending: pendingCapacity,
228
+ });
229
+ const beforeStart = async (hostSignal) => {
230
+ const signal = hostSignal ? AbortSignal.any([controller.signal, hostSignal]) : controller.signal;
231
+ for (;;) {
232
+ signal.throwIfAborted();
233
+ try {
234
+ await capacityLease.recheck();
235
+ break;
236
+ }
237
+ catch (error) {
238
+ if (!(error instanceof CapacityError))
239
+ throw error;
240
+ await capacityLease.release();
241
+ capacityLease = undefined;
242
+ pendingCapacity();
243
+ capacityLease = await acquireCapacity(signal);
244
+ }
245
+ }
246
+ signal.throwIfAborted();
247
+ status(TaskState.TASK_STATE_WORKING);
248
+ };
103
249
  try {
104
250
  const parsed = parseA2AInput(context.request, this.options);
105
251
  const { prompt, input } = parsed;
106
252
  resultContract = parsed.resultContract;
253
+ // Only role loading needs early admission for potentially cold packages.
254
+ // Ordinary clients retain the first Task's prepared session metadata.
255
+ if (this.roleIdFor(input, this.store.loadTarget(context.contextId, context.context)))
256
+ submitted();
107
257
  const key = JSON.stringify([context.context.tenant ?? '', resolveUserScope(context.context), context.contextId]);
258
+ if (this.preparing.has(key)) {
259
+ const message = 'Pending: waiting for an earlier task to prepare this session.';
260
+ submitted(message);
261
+ status(TaskState.TASK_STATE_SUBMITTED, message);
262
+ }
108
263
  const previous = this.preparing.get(key) ?? Promise.resolve();
264
+ let promptPrefix = '';
109
265
  let unlock;
110
266
  const lock = new Promise(resolve => { unlock = resolve; });
111
- this.preparing.set(key, lock);
267
+ // A canceled waiter must not let later requests bypass its still-pending predecessor.
268
+ const tail = previous.then(() => lock);
269
+ this.preparing.set(key, tail);
270
+ void tail.then(() => { if (this.preparing.get(key) === tail)
271
+ this.preparing.delete(key); });
112
272
  try {
113
- await previous;
273
+ await waitForPreparation(previous, controller.signal);
114
274
  controller.signal.throwIfAborted();
115
275
  const saved = this.store.loadTarget(context.contextId, context.context);
276
+ if (saved?.roleSkills)
277
+ submitted();
278
+ let role;
279
+ try {
280
+ role = await this.roleFor(input, saved, key, controller.signal);
281
+ }
282
+ catch (error) {
283
+ throw new RoleSkillLoadingError(error);
284
+ }
285
+ controller.signal.throwIfAborted();
286
+ // ACP session preparation can itself wait in the process FIFO.
287
+ if ((input.agentPreset ?? saved?.agentPreset ?? this.options.defaultAgentPreset)?.startsWith('oneagents-acp-'))
288
+ pendingCapacity();
289
+ // Acquire only after context/role waits, immediately before session creation.
290
+ capacityLease = await acquireCapacity();
291
+ controller.signal.throwIfAborted();
116
292
  target = await this.backend.prepare({ sessionId: saved?.sessionId,
117
293
  cwd: input.cwd ?? saved?.cwd ?? this.options.defaultCwd,
118
294
  agentPreset: input.agentPreset ?? saved?.agentPreset ?? this.options.defaultAgentPreset,
119
- ...(input.preflight ? { preflight: input.preflight } : {}) });
295
+ ...(input.preflight ? { preflight: input.preflight } : {}) }, { signal: controller.signal });
296
+ if (role) {
297
+ target.roleId = role.roleId;
298
+ target.roleSkills = role.summary;
299
+ promptPrefix = role.promptPrefix;
300
+ }
120
301
  this.store.saveTarget(context.contextId, target, context.context);
121
302
  }
122
303
  finally {
123
304
  unlock();
124
- if (this.preparing.get(key) === lock)
125
- this.preparing.delete(key);
126
305
  }
127
- const task = Task.fromJSON({ ...Task.toJSON(context.task ?? Task.fromJSON({ id: context.taskId, contextId: context.contextId })),
128
- status: { state: 'TASK_STATE_SUBMITTED', timestamp: new Date().toISOString() },
129
- metadata: { ...context.task?.metadata, '1agents': target } });
130
- bus.publish(AgentEvent.task(task));
131
- published = true;
306
+ submitted();
132
307
  controller.signal.throwIfAborted();
133
- status(TaskState.TASK_STATE_WORKING);
134
- const result = await this.backend.run(target, prompt, { requestId, signal: controller.signal });
308
+ // Preparation can include I/O or a cold ACP handshake. Never start the
309
+ // model using a memory observation taken before that work.
310
+ await beforeStart();
311
+ const result = await this.backend.run(target, promptPrefix + prompt, { requestId, signal: controller.signal, beforeStart });
135
312
  returnedError = result.outcome === 'failed' && result.error !== undefined
136
313
  ? toSafeError(result.error, { origin: 'a2a', operationId: requestId }) : undefined;
137
314
  returnedFailureMessage = result.outcome === 'failed' && typeof result.failureReason === 'string' && Object.hasOwn(FAILURE_MESSAGES, result.failureReason)
@@ -164,6 +341,8 @@ export class A2ASessionExecutor {
164
341
  status(result.outcome === 'completed' ? TaskState.TASK_STATE_COMPLETED : result.outcome === 'input-required' ? TaskState.TASK_STATE_INPUT_REQUIRED : TaskState.TASK_STATE_FAILED, returnedFailureMessage ?? error?.message ?? result.detail, error);
165
342
  }
166
343
  catch (error) {
344
+ if (error instanceof CapacityError)
345
+ capacityFailure = error;
167
346
  if (!published)
168
347
  bus.publish(AgentEvent.task(Task.fromJSON({ id: context.taskId, contextId: context.contextId,
169
348
  status: { state: 'TASK_STATE_SUBMITTED', timestamp: new Date().toISOString() } })));
@@ -174,7 +353,7 @@ export class A2ASessionExecutor {
174
353
  });
175
354
  resultMetadata = await createA2AResultMetadata({ taskId: context.taskId, contextId: context.contextId,
176
355
  requestId, startedAt, outcome: controller.signal.aborted ? 'canceled' : 'failed', target, contract: resultContract,
177
- validationCode: error instanceof A2AResultValidationError ? error.code : undefined,
356
+ validationCode: capacityFailure?.code ?? (error instanceof A2AResultValidationError ? error.code : error instanceof RoleSkillLoadingError ? 'role-skills-unavailable' : undefined),
178
357
  ...(error instanceof A2APreflightError ? { preflight: error.report } : {}) });
179
358
  try {
180
359
  await saveA2AResultMetadata(resultMetadata, target);
@@ -183,9 +362,16 @@ export class A2ASessionExecutor {
183
362
  resultMetadata.validation = { status: 'failed', code: 'result-record-write-failed' };
184
363
  delete resultMetadata.recordPath;
185
364
  }
186
- status(controller.signal.aborted ? TaskState.TASK_STATE_CANCELED : TaskState.TASK_STATE_FAILED, returnedFailureMessage ?? safe.message, safe);
365
+ status(controller.signal.aborted ? TaskState.TASK_STATE_CANCELED : TaskState.TASK_STATE_FAILED, capacityFailure?.message ?? returnedFailureMessage ?? safe.message, safe);
187
366
  }
188
367
  finally {
368
+ // Release failures retain the durable reservation and cannot strand close().
369
+ try {
370
+ await capacityLease?.release();
371
+ }
372
+ catch {
373
+ console.warn('ACP task capacity reservation could not be released');
374
+ }
189
375
  this.active.delete(context.taskId);
190
376
  finish();
191
377
  }
@@ -2,7 +2,9 @@ import { z } from 'zod';
2
2
  import { A2AAutomation } from './automation.js';
3
3
  import { SessionDelivery } from './session-delivery.js';
4
4
  import { TargetDirectory } from '../execution/targets.js';
5
+ import { ProjectRoleDiscovery } from '../execution/project-discovery.js';
5
6
  import { JobLedger } from '../execution/ledger.js';
7
+ import { type WorkbenchListQuery } from '../execution/workbench.js';
6
8
  export type { RemoteAgentNotice } from './notices.js';
7
9
  declare const configSchema: z.ZodObject<{
8
10
  stateDirectory: z.ZodString;
@@ -46,6 +48,13 @@ declare const configSchema: z.ZodObject<{
46
48
  }, z.core.$strict>>;
47
49
  processingLeaseMs: z.ZodDefault<z.ZodNumber>;
48
50
  }, z.core.$strict>>;
51
+ projectDiscovery: z.ZodOptional<z.ZodObject<{
52
+ readerExecutable: z.ZodDefault<z.ZodString>;
53
+ allowedRoots: z.ZodArray<z.ZodString>;
54
+ explicitRoots: z.ZodDefault<z.ZodArray<z.ZodString>>;
55
+ timeoutMs: z.ZodDefault<z.ZodNumber>;
56
+ maxProjects: z.ZodDefault<z.ZodNumber>;
57
+ }, z.core.$strict>>;
49
58
  pollIntervalMs: z.ZodDefault<z.ZodNumber>;
50
59
  pptDelivery: z.ZodOptional<z.ZodObject<{
51
60
  version: z.ZodDefault<z.ZodString>;
@@ -66,13 +75,31 @@ declare const configSchema: z.ZodObject<{
66
75
  runtimeDocument: z.ZodString;
67
76
  designSkill: z.ZodString;
68
77
  pythonExecutable: z.ZodString;
78
+ roleSkills: z.ZodOptional<z.ZodObject<{
79
+ profilePath: z.ZodString;
80
+ cacheRoot: z.ZodString;
81
+ }, z.core.$strict>>;
69
82
  nodeExecutable: z.ZodOptional<z.ZodString>;
70
83
  nodeModuleRoot: z.ZodOptional<z.ZodString>;
71
84
  maxRevisionRounds: z.ZodDefault<z.ZodNumber>;
72
85
  maxExecutionRetries: z.ZodDefault<z.ZodNumber>;
73
86
  maxDurationMs: z.ZodDefault<z.ZodNumber>;
87
+ requireHumanReview: z.ZodDefault<z.ZodBoolean>;
88
+ humanReviewerId: z.ZodDefault<z.ZodString>;
74
89
  httpTimeoutMs: z.ZodDefault<z.ZodNumber>;
75
90
  }, z.core.$strict>>;
91
+ reportReview: z.ZodOptional<z.ZodObject<{
92
+ workspaceRoot: z.ZodString;
93
+ allowedProjectRoots: z.ZodArray<z.ZodString>;
94
+ allowedRemotes: z.ZodArray<z.ZodString>;
95
+ }, z.core.$strict>>;
96
+ workbench: z.ZodOptional<z.ZodObject<{
97
+ token: z.ZodString;
98
+ reviewerId: z.ZodDefault<z.ZodString>;
99
+ reviewerName: z.ZodOptional<z.ZodString>;
100
+ publicBaseUrl: z.ZodOptional<z.ZodString>;
101
+ allowedOrigins: z.ZodOptional<z.ZodArray<z.ZodString>>;
102
+ }, z.core.$strict>>;
76
103
  }, z.core.$strict>;
77
104
  export type A2AGatewayConfig = z.input<typeof configSchema>;
78
105
  type Config = z.output<typeof configSchema>;
@@ -106,6 +133,8 @@ export declare const REMOTE_AGENT_METHODS: {
106
133
  agentPreset: z.ZodOptional<z.ZodString>;
107
134
  notificationTarget: z.ZodOptional<z.ZodString>;
108
135
  title: z.ZodOptional<z.ZodString>;
136
+ roleId: z.ZodOptional<z.ZodString>;
137
+ roleLockPath: z.ZodOptional<z.ZodString>;
109
138
  preflight: z.ZodOptional<z.ZodObject<{
110
139
  allowedDirectories: z.ZodOptional<z.ZodArray<z.ZodString>>;
111
140
  jobDirectory: z.ZodOptional<z.ZodString>;
@@ -152,6 +181,8 @@ export declare const REMOTE_AGENT_METHODS: {
152
181
  parameters: z.core.ZodStandardJSONSchemaPayload<z.ZodObject<{
153
182
  prompt: z.ZodString;
154
183
  clientRequestId: z.ZodOptional<z.ZodString>;
184
+ roleId: z.ZodOptional<z.ZodString>;
185
+ roleLockPath: z.ZodOptional<z.ZodString>;
155
186
  preflight: z.ZodOptional<z.ZodObject<{
156
187
  allowedDirectories: z.ZodOptional<z.ZodArray<z.ZodString>>;
157
188
  jobDirectory: z.ZodOptional<z.ZodString>;
@@ -323,6 +354,28 @@ export declare const REMOTE_AGENT_METHODS: {
323
354
  originSessionId: z.ZodString;
324
355
  }, z.core.$strict>>;
325
356
  };
357
+ execution_project_scan: {
358
+ description: string;
359
+ parameters: z.core.ZodStandardJSONSchemaPayload<z.ZodObject<{}, z.core.$strict>>;
360
+ };
361
+ execution_project_list: {
362
+ description: string;
363
+ parameters: z.core.ZodStandardJSONSchemaPayload<z.ZodObject<{}, z.core.$strict>>;
364
+ };
365
+ execution_discovery_config_get: {
366
+ description: string;
367
+ parameters: z.core.ZodStandardJSONSchemaPayload<z.ZodObject<{}, z.core.$strict>>;
368
+ };
369
+ execution_discovery_config_update: {
370
+ description: string;
371
+ parameters: z.core.ZodStandardJSONSchemaPayload<z.ZodObject<{
372
+ mode: z.ZodEnum<{
373
+ manual: "manual";
374
+ interval: "interval";
375
+ }>;
376
+ intervalMs: z.ZodOptional<z.ZodNumber>;
377
+ }, z.core.$strict>>;
378
+ };
326
379
  execution_connection_list: {
327
380
  description: string;
328
381
  parameters: z.core.ZodStandardJSONSchemaPayload<z.ZodObject<{}, z.core.$strict>>;
@@ -414,6 +467,7 @@ export declare const REMOTE_AGENT_METHODS: {
414
467
  agentPreset: z.ZodOptional<z.ZodString>;
415
468
  roleId: z.ZodOptional<z.ZodString>;
416
469
  skillRefs: z.ZodOptional<z.ZodArray<z.ZodString>>;
470
+ skillPolicy: z.ZodOptional<z.ZodLiteral<"network_pinned">>;
417
471
  allowedDirectories: z.ZodOptional<z.ZodArray<z.ZodString>>;
418
472
  allowedPresets: z.ZodOptional<z.ZodArray<z.ZodString>>;
419
473
  flowId: z.ZodOptional<z.ZodString>;
@@ -451,6 +505,7 @@ export declare const REMOTE_AGENT_METHODS: {
451
505
  agentPreset: z.ZodOptional<z.ZodString>;
452
506
  roleId: z.ZodOptional<z.ZodString>;
453
507
  skillRefs: z.ZodOptional<z.ZodArray<z.ZodString>>;
508
+ skillPolicy: z.ZodOptional<z.ZodLiteral<"network_pinned">>;
454
509
  allowedDirectories: z.ZodOptional<z.ZodArray<z.ZodString>>;
455
510
  allowedPresets: z.ZodOptional<z.ZodArray<z.ZodString>>;
456
511
  flowId: z.ZodOptional<z.ZodString>;
@@ -479,6 +534,7 @@ export declare class RemoteAgentGateway {
479
534
  readonly automation?: A2AAutomation;
480
535
  readonly sessions: SessionDelivery;
481
536
  readonly targets: TargetDirectory;
537
+ readonly projectDiscovery?: ProjectRoleDiscovery;
482
538
  readonly ledger: JobLedger;
483
539
  private readonly lease;
484
540
  private readonly stateFile;
@@ -493,6 +549,7 @@ export declare class RemoteAgentGateway {
493
549
  private readonly advancingDeliveries;
494
550
  private readonly canceling;
495
551
  private reconciling?;
552
+ private workbenchQueue;
496
553
  private readonly timer;
497
554
  private closed;
498
555
  constructor(input: A2AGatewayConfig);
@@ -506,6 +563,9 @@ export declare class RemoteAgentGateway {
506
563
  private advanceDelivery;
507
564
  private advanceDeliveryOnce;
508
565
  private executionNotice;
566
+ private advanceReport;
567
+ private updateReport;
568
+ private decideReportReview;
509
569
  private cancellationJobs;
510
570
  private assertDispatchOpen;
511
571
  private cancelExecution;
@@ -518,6 +578,7 @@ export declare class RemoteAgentGateway {
518
578
  private checkDispatch;
519
579
  private job;
520
580
  private view;
581
+ private resultObservation;
521
582
  private accept;
522
583
  private update;
523
584
  private refresh;
@@ -527,6 +588,22 @@ export declare class RemoteAgentGateway {
527
588
  private invokeMethod;
528
589
  /** Push events are hints. GetTask remains authoritative, including after missed callbacks. */
529
590
  receivePush(event: unknown): Promise<void>;
591
+ private workbenchProjection;
592
+ workbenchList(query?: WorkbenchListQuery): {
593
+ items: import("../execution/workbench.js").AcpTaskSummary[];
594
+ total: number;
595
+ counts: {
596
+ all: number;
597
+ pending: number;
598
+ working: number;
599
+ failed: number;
600
+ };
601
+ offset: number;
602
+ limit: number;
603
+ };
604
+ workbenchTask(jobId: string): import("../execution/workbench.js").AcpTaskDetail;
605
+ /** Only the dedicated HTTP workbench calls this; it is deliberately absent from the agent tool catalogue. */
606
+ decideWorkbenchReview(jobId: string, reviewId: string, input: unknown): Promise<import("../execution/workbench.js").AcpTaskDetail>;
530
607
  close(): Promise<void>;
531
608
  }
532
609
  export declare function serveA2AGateway(input: A2AGatewayConfig, options?: {