@1agents/acp-service 0.10.10 → 0.10.12

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 (44) hide show
  1. package/README.md +26 -0
  2. package/dist/bin/acp-service.js +6 -0
  3. package/dist/bin/dsh.d.ts +21 -0
  4. package/dist/bin/dsh.js +171 -0
  5. package/dist/src/a2a/gateway.d.ts +12 -0
  6. package/dist/src/a2a/gateway.js +192 -10
  7. package/dist/src/catalog-descriptors.js +10 -0
  8. package/dist/src/dsh-archive.d.ts +123 -0
  9. package/dist/src/dsh-archive.js +99 -0
  10. package/dist/src/dsh-host-client.d.ts +97 -0
  11. package/dist/src/dsh-host-client.js +275 -0
  12. package/dist/src/dsh-registry-file.d.ts +22 -0
  13. package/dist/src/dsh-registry-file.js +55 -0
  14. package/dist/src/dsh-session-files.d.ts +7 -0
  15. package/dist/src/dsh-session-files.js +63 -0
  16. package/package.json +1 -1
  17. package/skills/acp-service/SKILL.md +1 -1
  18. package/vendor/dsh/README.md +2 -0
  19. package/vendor/runtime/dist/{agent-registry-R7A3MSpr.js → agent-registry-DxcyXXqb.js} +5 -1
  20. package/vendor/runtime/dist/agent-registry-DxcyXXqb.js.map +1 -0
  21. package/vendor/runtime/dist/agent-registry.d.ts.map +1 -1
  22. package/vendor/runtime/dist/agent-registry.js +1 -1
  23. package/vendor/runtime/dist/{cli-BwanDcOo.js → cli-BKmMxgix.js} +4 -4
  24. package/vendor/runtime/dist/{cli-BwanDcOo.js.map → cli-BKmMxgix.js.map} +1 -1
  25. package/vendor/runtime/dist/cli.js +9 -9
  26. package/vendor/runtime/dist/docs-site/agents.html +1 -1
  27. package/vendor/runtime/dist/{flows-CzLUHUTS.js → flows-VrII9VKZ.js} +5 -5
  28. package/vendor/runtime/dist/{flows-CzLUHUTS.js.map → flows-VrII9VKZ.js.map} +1 -1
  29. package/vendor/runtime/dist/flows.js +1 -1
  30. package/vendor/runtime/dist/{invocation-options-B6pIpdpR.js → invocation-options-DHMZ5Rrb.js} +5 -5
  31. package/vendor/runtime/dist/{invocation-options-B6pIpdpR.js.map → invocation-options-DHMZ5Rrb.js.map} +1 -1
  32. package/vendor/runtime/dist/{ipc-ivLtSAdL.js → ipc-CNNM5DP_.js} +2 -2
  33. package/vendor/runtime/dist/{ipc-ivLtSAdL.js.map → ipc-CNNM5DP_.js.map} +1 -1
  34. package/vendor/runtime/dist/{output-BqKnXXb0.js → output-DtzXtiBc.js} +3 -3
  35. package/vendor/runtime/dist/{output-BqKnXXb0.js.map → output-DtzXtiBc.js.map} +1 -1
  36. package/vendor/runtime/dist/{queue-owner-runtime-DXJND10J.js → queue-owner-runtime-ehuh3SQU.js} +3 -3
  37. package/vendor/runtime/dist/{queue-owner-runtime-DXJND10J.js.map → queue-owner-runtime-ehuh3SQU.js.map} +1 -1
  38. package/vendor/runtime/dist/runtime.js +4 -4
  39. package/vendor/runtime/dist/{session-watch-BHB3_PXm.js → session-watch-CbKfGRkZ.js} +4 -4
  40. package/vendor/runtime/dist/{session-watch-BHB3_PXm.js.map → session-watch-CbKfGRkZ.js.map} +1 -1
  41. package/vendor/runtime/dist/{watch-UjokHUfS.js → watch-BGt4kcE6.js} +2 -2
  42. package/vendor/runtime/dist/{watch-UjokHUfS.js.map → watch-BGt4kcE6.js.map} +1 -1
  43. package/vendor/runtime/skills/acpx/SKILL.md +1 -0
  44. package/vendor/runtime/dist/agent-registry-R7A3MSpr.js.map +0 -1
package/README.md CHANGED
@@ -42,6 +42,32 @@ acp-service serve --host 127.0.0.1 --port 36812 --no-report
42
42
 
43
43
  The service uses **ACP v1 JSON-RPC 2.0 over WebSocket**. DSH is unnecessary for the standalone entry points. A2A delegation is opt-in and disabled by default; its configuration is documented below. Waking a calling system's main Agent after task completion requires that system's receiving host adapter.
44
44
 
45
+ ## Archiving silent DSH sessions
46
+
47
+ `acp-service dsh archive` archives DSH sessions that have been idle for a chosen number of days. It is a manual command: it installs no timer into DSH, changes no plugin configuration, and runs only when invoked. Archiving hides a session from the workspace grouping; it never deletes the session or its log, and the session can be restored from DSH's archived list.
48
+
49
+ ```sh
50
+ acp-service dsh archive --days 7 --dry-run # list what would be archived
51
+ acp-service dsh archive --days 7 # archive it
52
+ ```
53
+
54
+ | Option | Meaning |
55
+ |---|---|
56
+ | `--days <n>` | Idle threshold in days; default `7`. |
57
+ | `--url <origin>` | DSH Host origin. Repeatable, tried in order. Omitted, the command probes the machine's loopback listeners. |
58
+ | `--dry-run` | Print the plan and change nothing. |
59
+ | `--include-pinned` | Archive pinned sessions too. Pinned sessions are skipped by default. |
60
+ | `--stop-activity` | Allow stopping a session's running work. Running sessions are skipped by default. |
61
+ | `--json` | Machine-readable output. |
62
+
63
+ **How "idle" is measured.** Last activity is the later of the Host's own recency (session creation time or its last real user message) and the modification time of the session's durable log file. A cold session whose log was written recently — a tool result, a title rewrite, a compaction — therefore does not count as silent.
64
+
65
+ **Which sessions are skipped.** Already archived sessions, sessions with running work (unless `--stop-activity`), and pinned sessions (unless `--include-pinned`). A pin is the explicit "keep this visible" signal, so it stays a manual decision.
66
+
67
+ **How it talks to DSH.** The command calls the running Host's own `workspace` service over its Typert RPC (`/api/workspace/archiveSession`), so the archive stays the Host's durable state. It authenticates as the Host's owner with a browser-session cookie minted from the local credential store (`$DSH_HOME/.credentials.yaml`), which is the same principal the DSH UI acts as on the machine that owns the Host.
68
+
69
+ **Two Hosts, one DSH home.** A `dsh web` instance and the desktop app can share `$DSH_HOME`, and each holds the workspace registry in memory while rewriting the whole document on every change. Planning therefore reads the durable registry document, and the command **refuses to write** through a Host whose registry is missing entries the document records — that Host started before the newer archives were written, and its next write would drop them. Restart that instance so it reloads, then run the command again. Auto-discovery prefers a Host that already matches the document; an explicit `--url` is always honoured, and the safety check still applies to it.
70
+
45
71
  ## Bundled usage skill
46
72
 
47
73
  [ACP Service skill](skills/acp-service/SKILL.md) is distributed in this npm package and maintained with the source. It covers entry-point selection, ACP CLI/WebSocket sessions, DSH presets and native model controls, A2A delegation, task queries and the durable completion inbox. Detailed examples are included in its `references/` directory.
@@ -60,6 +60,7 @@ function printUnifiedHelp(binName) {
60
60
  ticket show|events|proposal --job <id> Read a job's task ticket and its events, or settle a proposal
61
61
  process list|answer --job <id> Read a job's process requests, or answer one as the coach or a person
62
62
  trail --job <id> One task's record: who asked, what ran, who approved, what came out, who read it
63
+ dsh archive --days <n> [--dry-run] Archive DSH sessions that have been silent for n days (manual; no timer)
63
64
  serve [options] Start DreamMate Network ACP runtime daemon (HTTP + WS)`;
64
65
  help = help.replace(/^Commands:/m, serverCommands);
65
66
  const serverOptions = `Options:
@@ -161,6 +162,11 @@ async function main() {
161
162
  await runRsiCli(rawArgs.slice(1));
162
163
  return;
163
164
  }
165
+ if (rawArgs[0] === 'dsh') {
166
+ const { runDshArchiveCli } = await import('./dsh.js');
167
+ await runDshArchiveCli(rawArgs.slice(1));
168
+ return;
169
+ }
164
170
  const isServe = rawArgs[0] === 'serve' || rawArgs[0] === 'run';
165
171
  const hasServerExplicitFlag = rawArgs[0] === '--port' ||
166
172
  rawArgs[0] === '-p' ||
@@ -0,0 +1,21 @@
1
+ /** Options the command accepts. */
2
+ interface ArchiveArgs {
3
+ days: number;
4
+ urls: string[];
5
+ dryRun: boolean;
6
+ includePinned: boolean;
7
+ stopActivity: boolean;
8
+ json: boolean;
9
+ }
10
+ /** Parse the command line, rejecting values that cannot mean anything. */
11
+ export declare function parseArchiveArgs(argv: string[]): ArchiveArgs;
12
+ /** The DSH home directory whose storage and credentials the command reads. */
13
+ export declare function resolveDshHome(env?: NodeJS.ProcessEnv): string;
14
+ /**
15
+ * Run the archive command.
16
+ *
17
+ * @param argv - the command's arguments, without the command name.
18
+ * @param env - the environment, for the DSH home directory.
19
+ */
20
+ export declare function runDshArchiveCli(argv: string[], env?: NodeJS.ProcessEnv): Promise<void>;
21
+ export {};
@@ -0,0 +1,171 @@
1
+ /**
2
+ * `acp-service dsh archive` — archive DSH sessions that have been silent.
3
+ *
4
+ * The command is manual by design: it runs when a person asks it to, against
5
+ * a DSH Host that is already running. It never installs a timer and never
6
+ * changes the Host's plugin configuration.
7
+ */
8
+ import { parseArgs } from 'node:util';
9
+ import { homedir } from 'node:os';
10
+ import { join } from 'node:path';
11
+ import { planArchive, runArchive, DAY_MS } from '../src/dsh-archive.js';
12
+ import { DshHostClient, DshRpcError, discoverHost, mintSessionCookie, readBrowserSessionSecret } from '../src/dsh-host-client.js';
13
+ import { readRegistryFile } from '../src/dsh-registry-file.js';
14
+ import { readSessionFileMtimes } from '../src/dsh-session-files.js';
15
+ const USAGE = `用法: acp-service dsh archive [选项]
16
+
17
+ 归档 DSH 中静默超过指定天数的会话。命令手动执行,不会安装定时器,也不改动 DSH 插件配置。
18
+ 归档只隐藏会话,不删除会话日志;可用 DSH 界面的归档列表随时恢复。
19
+
20
+ 选项:
21
+ --days <n> 静默天数阈值(默认: 7)
22
+ --url <origin> DSH Host 地址,可重复指定;省略时自动探测本机监听端口
23
+ --dry-run 只列出将要归档的会话,不做任何改动
24
+ --include-pinned 连置顶会话一起归档(默认跳过,置顶表示「保留可见」)
25
+ --stop-activity 允许停止正在运行的会话来完成归档(默认跳过运行中的会话)
26
+ --json 以 JSON 输出结果
27
+ -h, --help 显示帮助信息
28
+
29
+ 示例:
30
+ acp-service dsh archive --days 7 --dry-run
31
+ acp-service dsh archive --days 14 --url http://127.0.0.1:51971
32
+ `;
33
+ /** Parse the command line, rejecting values that cannot mean anything. */
34
+ export function parseArchiveArgs(argv) {
35
+ const { values } = parseArgs({
36
+ args: argv,
37
+ strict: true,
38
+ allowPositionals: false,
39
+ options: {
40
+ days: { type: 'string', default: '7' },
41
+ url: { type: 'string', multiple: true, default: [] },
42
+ 'dry-run': { type: 'boolean', default: false },
43
+ 'include-pinned': { type: 'boolean', default: false },
44
+ 'stop-activity': { type: 'boolean', default: false },
45
+ json: { type: 'boolean', default: false },
46
+ },
47
+ });
48
+ const days = Number(values.days);
49
+ if (!Number.isFinite(days) || days <= 0)
50
+ throw new Error(`--days must be a positive number of days, got ${String(values.days)}`);
51
+ for (const url of values.url) {
52
+ let parsed;
53
+ try {
54
+ parsed = new URL(url);
55
+ }
56
+ catch {
57
+ throw new Error(`--url must be an absolute origin, got ${url}`);
58
+ }
59
+ if (!['http:', 'https:'].includes(parsed.protocol))
60
+ throw new Error(`--url must use http or https, got ${url}`);
61
+ }
62
+ return {
63
+ days,
64
+ urls: values.url,
65
+ dryRun: values['dry-run'],
66
+ includePinned: values['include-pinned'],
67
+ stopActivity: values['stop-activity'],
68
+ json: values.json,
69
+ };
70
+ }
71
+ /** The DSH home directory whose storage and credentials the command reads. */
72
+ export function resolveDshHome(env = process.env) {
73
+ return env.DSH_HOME ?? join(homedir(), '.dsh');
74
+ }
75
+ function formatCandidate(candidate) {
76
+ const title = candidate.title ? candidate.title.replace(/\s+/g, ' ').slice(0, 60) : '(无标题)';
77
+ const cwd = candidate.cwd ? ` ${candidate.cwd}` : '';
78
+ return `- ${candidate.sessionId} 静默 ${candidate.idleDays} 天 ${title}${cwd}`;
79
+ }
80
+ function formatSkip(skip) {
81
+ const label = skip.reason === 'pinned' ? '置顶' : skip.reason === 'running' ? '运行中' : '已归档';
82
+ const title = skip.title ? ` ${skip.title.replace(/\s+/g, ' ').slice(0, 60)}` : '';
83
+ return `- ${skip.sessionId} 跳过(${label})${title}`;
84
+ }
85
+ /**
86
+ * Run the archive command.
87
+ *
88
+ * @param argv - the command's arguments, without the command name.
89
+ * @param env - the environment, for the DSH home directory.
90
+ */
91
+ export async function runDshArchiveCli(argv, env = process.env) {
92
+ try {
93
+ await archiveCommand(argv, env);
94
+ }
95
+ catch (error) {
96
+ // Expected failures (no Host, a stale registry, a bad option) print one
97
+ // line; an unexpected crash keeps its stack for diagnosis.
98
+ if (error instanceof DshRpcError || /^(no reachable|none of the given|cannot read|--days|--url)/.test(String(error instanceof Error ? error.message : error))) {
99
+ console.error(`acp-service dsh archive: ${error instanceof Error ? error.message : String(error)}`);
100
+ process.exitCode = 1;
101
+ return;
102
+ }
103
+ throw error;
104
+ }
105
+ }
106
+ async function archiveCommand(argv, env) {
107
+ // `acp-service dsh archive` passes the subcommand name through; drop it.
108
+ const args = argv[0] === 'archive' ? argv.slice(1) : argv;
109
+ if (args.includes('--help') || args.includes('-h')) {
110
+ console.log(USAGE);
111
+ return;
112
+ }
113
+ const options = parseArchiveArgs(args);
114
+ const home = resolveDshHome(env);
115
+ const secret = readBrowserSessionSecret(join(home, '.credentials.yaml'));
116
+ // The durable document is read before discovery so an out-of-date Host is
117
+ // not chosen when an up-to-date one is running.
118
+ const document = await readRegistryFile(home);
119
+ const endpoint = await discoverHost(options.urls, secret, document.found ? document.archivedSessionIds : undefined);
120
+ const client = new DshHostClient(endpoint, mintSessionCookie(secret, endpoint.authority));
121
+ const mtimes = await readSessionFileMtimes(join(home, 'sessions'));
122
+ // Plan against the durable document, not the Host's in-memory copy: when two
123
+ // Hosts share one DSH home the older one's copy can be behind. The Host is
124
+ // only asked for the session list here, and its own registry is compared
125
+ // against the document before the first write.
126
+ const hostArchive = (await client.readRegistry()).archivedSessionIds;
127
+ const planSource = {
128
+ listSessions: () => client.listSessions(),
129
+ readRegistry: async () => ({
130
+ archivedSessionIds: document.found ? document.archivedSessionIds : hostArchive,
131
+ pinnedSessionIds: document.found ? document.pinnedSessionIds : (await client.readRegistry()).pinnedSessionIds,
132
+ }),
133
+ archiveSession: (sessionId, archiveOptions) => client.archiveSession(sessionId, archiveOptions),
134
+ };
135
+ const plan = await planArchive(planSource, {
136
+ inactivityMs: Math.round(options.days * DAY_MS),
137
+ now: Date.now(),
138
+ includePinned: options.includePinned,
139
+ fileMtimes: mtimes,
140
+ });
141
+ if (options.dryRun) {
142
+ if (options.json) {
143
+ console.log(JSON.stringify({ dryRun: true, endpoint: endpoint.origin, ...plan }, null, 2));
144
+ return;
145
+ }
146
+ console.log(`DSH: ${endpoint.origin}`);
147
+ console.log(`会话总数 ${plan.totalSessions},已归档 ${plan.alreadyArchived},静默超过 ${options.days} 天的待归档 ${plan.candidates.length}`);
148
+ for (const candidate of plan.candidates)
149
+ console.log(formatCandidate(candidate));
150
+ for (const skip of plan.skipped)
151
+ console.log(formatSkip(skip));
152
+ console.log('(预演模式,未做任何改动)');
153
+ return;
154
+ }
155
+ // Refuse to write through a Host that started before the document was last
156
+ // written: its in-memory registry would drop those newer entries.
157
+ if (document.found)
158
+ await client.assertRegistryFresh(document.archivedSessionIds);
159
+ const result = await runArchive(client, plan, { stopActivity: options.stopActivity });
160
+ if (options.json) {
161
+ console.log(JSON.stringify({ dryRun: false, endpoint: endpoint.origin, ...result }, null, 2));
162
+ return;
163
+ }
164
+ console.log(`DSH: ${endpoint.origin}`);
165
+ console.log(`会话总数 ${plan.totalSessions},已归档 ${plan.alreadyArchived},候选 ${plan.candidates.length}`);
166
+ console.log(`已归档 ${result.archived.length},失败 ${result.failed.length},跳过 ${result.skipped.length}`);
167
+ for (const failure of result.failed)
168
+ console.error(`- ${failure.sessionId} 归档失败:${failure.error}`);
169
+ for (const skip of result.skipped)
170
+ console.log(formatSkip(skip));
171
+ }
@@ -110,6 +110,7 @@ declare const configSchema: z.ZodObject<{
110
110
  desktopNotifications: z.ZodDefault<z.ZodBoolean>;
111
111
  }, z.core.$strict>>;
112
112
  capacityDirectory: z.ZodOptional<z.ZodString>;
113
+ coldRetentionDays: z.ZodDefault<z.ZodNumber>;
113
114
  sessionLifecycle: z.ZodDefault<z.ZodObject<{
114
115
  persistentIdleTtlSeconds: z.ZodDefault<z.ZodNumber>;
115
116
  idleScanIntervalMs: z.ZodDefault<z.ZodNumber>;
@@ -1119,6 +1120,8 @@ export declare class RemoteAgentGateway {
1119
1120
  readonly ledger: JobLedger;
1120
1121
  private readonly lease;
1121
1122
  private readonly stateFile;
1123
+ private readonly archiveFile;
1124
+ private lastArchivedAt;
1122
1125
  private readonly snapshots;
1123
1126
  private readonly state;
1124
1127
  private readonly clients;
@@ -1171,6 +1174,14 @@ export declare class RemoteAgentGateway {
1171
1174
  private cancelExecution;
1172
1175
  private reconcileCancellation;
1173
1176
  private performCancellation;
1177
+ private writeArchive;
1178
+ archiveColdState(retentionDays?: number): {
1179
+ archivedJobs: number;
1180
+ archivedNotices: number;
1181
+ archivedCancellations: number;
1182
+ archivedPptRuns: number;
1183
+ archivedReportRuns: number;
1184
+ };
1174
1185
  private probeTarget;
1175
1186
  private client;
1176
1187
  private auth;
@@ -1198,6 +1209,7 @@ export declare class RemoteAgentGateway {
1198
1209
  mediaType?: string;
1199
1210
  }>;
1200
1211
  private checkDispatch;
1212
+ private findArchivedJob;
1201
1213
  private job;
1202
1214
  private view;
1203
1215
  private resultObservation;
@@ -1,6 +1,6 @@
1
1
  /** Main-agent tools backed by standard A2A, with a durable completion inbox. */
2
2
  import { createHash, randomUUID, timingSafeEqual } from 'node:crypto';
3
- import { closeSync, fsyncSync, mkdirSync, openSync, readFileSync, realpathSync, renameSync, writeFileSync } from 'node:fs';
3
+ import { closeSync, existsSync, fsyncSync, mkdirSync, openSync, readFileSync, realpathSync, renameSync, writeFileSync } from 'node:fs';
4
4
  import { readFile } from 'node:fs/promises';
5
5
  import http from 'node:http';
6
6
  import path from 'node:path';
@@ -73,6 +73,8 @@ const configSchema = z.object({
73
73
  /** Same-machine ACP ledger. Omitted callers do not read the default home directory. */
74
74
  capacityDirectory: z.string().min(1).optional(),
75
75
  /** P3 idle close for persistent ACP sessions. idleTtlSeconds on a job overrides persistentIdleTtlSeconds. */
76
+ /** Retention days for active gateway state. Terminal tasks and completed records older than this are archived. Default 7 days. */
77
+ coldRetentionDays: z.number().int().min(1).max(365).default(7),
76
78
  sessionLifecycle: z.object({
77
79
  persistentIdleTtlSeconds: z.number().int().min(0).max(30 * 24 * 60 * 60).default(600),
78
80
  idleScanIntervalMs: z.number().int().min(50).max(10 * 60_000).default(60_000),
@@ -227,6 +229,8 @@ export class RemoteAgentGateway {
227
229
  ledger;
228
230
  lease;
229
231
  stateFile;
232
+ archiveFile;
233
+ lastArchivedAt = Number.NEGATIVE_INFINITY;
230
234
  snapshots;
231
235
  state;
232
236
  clients = new Map();
@@ -259,6 +263,7 @@ export class RemoteAgentGateway {
259
263
  // directory: local restarts must never mark remote executions failed.
260
264
  this.lease = new FileA2AStore(path.join(this.config.stateDirectory, 'lease'));
261
265
  this.stateFile = path.join(this.config.stateDirectory, 'gateway.json');
266
+ this.archiveFile = path.join(this.config.stateDirectory, 'gateway-archive.json');
262
267
  this.snapshots = new SnapshotStore(path.join(this.config.stateDirectory, 'handoff-snapshots'));
263
268
  try {
264
269
  this.state = JSON.parse(readFileSync(this.stateFile, 'utf8'));
@@ -327,6 +332,7 @@ export class RemoteAgentGateway {
327
332
  }
328
333
  }
329
334
  this.save();
335
+ this.archiveColdState();
330
336
  if (this.config.automation)
331
337
  this.automation = new A2AAutomation(this, this.config.automation);
332
338
  if (this.config.projectDiscovery) {
@@ -919,13 +925,150 @@ export class RemoteAgentGateway {
919
925
  this.save();
920
926
  this.updateReport(run);
921
927
  }
928
+ const previousStatus = record.status;
929
+ const previousTargets = JSON.stringify(record.targets);
922
930
  record.status = unresolved.length ? 'blocked' : 'completed';
923
931
  record.targets = ids.flatMap(id => this.ledger.get(origin, id).attempts).map(attempt => ({ jobId: attempt.jobId, attemptId: attempt.attemptId,
924
932
  executionStatus: attempt.executionStatus, submissionStatus: attempt.submissionStatus }));
925
933
  record.checkedAt = new Date().toISOString();
926
- if (record.status === 'completed')
934
+ if (record.status === 'completed' && !record.completedAt)
927
935
  record.completedAt = record.checkedAt;
928
- this.save();
936
+ if (previousStatus !== record.status || previousTargets !== JSON.stringify(record.targets)) {
937
+ this.save();
938
+ }
939
+ }
940
+ writeArchive(data) {
941
+ let existing = {
942
+ version: 1,
943
+ jobs: [],
944
+ notices: [],
945
+ cancellations: {},
946
+ pptRuns: {},
947
+ reportRuns: {},
948
+ archivedAt: new Date(this.now()).toISOString(),
949
+ };
950
+ try {
951
+ if (existsSync(this.archiveFile)) {
952
+ existing = JSON.parse(readFileSync(this.archiveFile, "utf8"));
953
+ existing.jobs ??= [];
954
+ existing.notices ??= [];
955
+ existing.cancellations ??= {};
956
+ existing.pptRuns ??= {};
957
+ existing.reportRuns ??= {};
958
+ }
959
+ }
960
+ catch { }
961
+ const jobKeys = new Set(existing.jobs.map(j => `${j.remote}:${j.taskId}:${j.originSessionId}`));
962
+ for (const j of data.jobs) {
963
+ const key = `${j.remote}:${j.taskId}:${j.originSessionId}`;
964
+ if (!jobKeys.has(key)) {
965
+ existing.jobs.push(j);
966
+ jobKeys.add(key);
967
+ }
968
+ }
969
+ const noticeKeys = new Set(existing.notices.map(n => n.notice.noticeId));
970
+ for (const n of data.notices) {
971
+ if (!noticeKeys.has(n.notice.noticeId)) {
972
+ existing.notices.push(n);
973
+ noticeKeys.add(n.notice.noticeId);
974
+ }
975
+ }
976
+ Object.assign(existing.cancellations, data.cancellations);
977
+ Object.assign(existing.pptRuns, data.pptRuns);
978
+ Object.assign(existing.reportRuns, data.reportRuns);
979
+ existing.archivedAt = new Date(this.now()).toISOString();
980
+ atomicJson(this.archiveFile, existing);
981
+ }
982
+ archiveColdState(retentionDays = this.config.coldRetentionDays) {
983
+ this.lastArchivedAt = this.now();
984
+ const cutoff = this.now() - retentionDays * 24 * 60 * 60 * 1000;
985
+ const pendingNoticeTaskIds = new Set(this.state.notices
986
+ .filter(n => new Date(n.notice?.createdAt || 0).getTime() >= cutoff && !n.acknowledged && !n.delivered)
987
+ .map(n => n.notice.taskId));
988
+ const activeCancellationTaskIds = new Set(Object.values(this.state.executionCancellations ?? {})
989
+ .filter(c => c.status !== "completed")
990
+ .flatMap(c => c.targets.map(t => t.jobId)));
991
+ const remainingJobs = [];
992
+ const coldJobs = [];
993
+ for (const job of this.state.jobs) {
994
+ const isTerminal = terminal.has(taskState(job));
995
+ const jobTime = new Date(job.closedAt || job.checkedAt || 0).getTime();
996
+ const isCold = isTerminal && jobTime < cutoff;
997
+ const hasActiveRef = pendingNoticeTaskIds.has(job.taskId) || activeCancellationTaskIds.has(job.taskId) || activeCancellationTaskIds.has(job.ledgerJobId ?? "");
998
+ if (isCold && !hasActiveRef) {
999
+ coldJobs.push(job);
1000
+ }
1001
+ else {
1002
+ remainingJobs.push(job);
1003
+ }
1004
+ }
1005
+ const remainingNotices = [];
1006
+ const coldNotices = [];
1007
+ for (const notice of this.state.notices) {
1008
+ const noticeTime = new Date(notice.notice?.createdAt || 0).getTime();
1009
+ if (noticeTime < cutoff) {
1010
+ coldNotices.push(notice);
1011
+ }
1012
+ else {
1013
+ remainingNotices.push(notice);
1014
+ }
1015
+ }
1016
+ const remainingCancellations = {};
1017
+ const coldCancellations = {};
1018
+ for (const [id, c] of Object.entries(this.state.executionCancellations ?? {})) {
1019
+ const reqTime = new Date(c.completedAt || c.requestedAt || 0).getTime();
1020
+ if (c.status === "completed" && reqTime < cutoff) {
1021
+ coldCancellations[id] = c;
1022
+ }
1023
+ else if (c.status === "blocked" && reqTime < cutoff) {
1024
+ coldCancellations[id] = { ...c, status: "completed", completedAt: new Date(this.now()).toISOString(), diagnostics: [...c.diagnostics, "Auto-closed after cold retention timeout"] };
1025
+ }
1026
+ else {
1027
+ remainingCancellations[id] = c;
1028
+ }
1029
+ }
1030
+ const remainingPptRuns = {};
1031
+ const coldPptRuns = {};
1032
+ for (const [id, run] of Object.entries((this.state.pptDeliveries?.runs ?? {}))) {
1033
+ const isTerminal = ["completed", "failed", "canceled"].includes(run.executionStatus) && !run.parentUpdatePending;
1034
+ const runTime = new Date(run.updatedAt || run.createdAt || 0).getTime();
1035
+ if (isTerminal && runTime < cutoff) {
1036
+ coldPptRuns[id] = run;
1037
+ }
1038
+ else {
1039
+ remainingPptRuns[id] = run;
1040
+ }
1041
+ }
1042
+ const remainingReportRuns = {};
1043
+ const coldReportRuns = {};
1044
+ for (const [id, run] of Object.entries(this.state.reportReviews ?? {})) {
1045
+ const isTerminal = ["completed", "failed", "canceled"].includes(run.executionStatus);
1046
+ const runTime = new Date(run.updatedAt || run.createdAt || 0).getTime();
1047
+ if (isTerminal && runTime < cutoff) {
1048
+ coldReportRuns[id] = run;
1049
+ }
1050
+ else {
1051
+ remainingReportRuns[id] = run;
1052
+ }
1053
+ }
1054
+ const archivedCount = {
1055
+ archivedJobs: coldJobs.length,
1056
+ archivedNotices: coldNotices.length,
1057
+ archivedCancellations: Object.keys(coldCancellations).length,
1058
+ archivedPptRuns: Object.keys(coldPptRuns).length,
1059
+ archivedReportRuns: Object.keys(coldReportRuns).length,
1060
+ };
1061
+ if (coldJobs.length || coldNotices.length || Object.keys(coldCancellations).length || Object.keys(coldPptRuns).length || Object.keys(coldReportRuns).length) {
1062
+ this.writeArchive({ jobs: coldJobs, notices: coldNotices, cancellations: coldCancellations, pptRuns: coldPptRuns, reportRuns: coldReportRuns });
1063
+ this.state.jobs = remainingJobs;
1064
+ this.state.notices = remainingNotices;
1065
+ this.state.executionCancellations = remainingCancellations;
1066
+ if (this.state.pptDeliveries?.runs)
1067
+ this.state.pptDeliveries.runs = remainingPptRuns;
1068
+ this.state.reportReviews = remainingReportRuns;
1069
+ this.save();
1070
+ }
1071
+ return archivedCount;
929
1072
  }
930
1073
  async probeTarget(targetId) {
931
1074
  const target = this.targets.getTarget(targetId), connection = this.targets.getConnection(target.connectionId);
@@ -1137,8 +1280,21 @@ export class RemoteAgentGateway {
1137
1280
  if (!report.ok)
1138
1281
  throw new Error(`Remote preflight rejected dispatch: ${report.checks.filter(check => !check.ok).map(check => check.id).join(', ')}`);
1139
1282
  }
1283
+ findArchivedJob(params) {
1284
+ try {
1285
+ if (!existsSync(this.archiveFile))
1286
+ return undefined;
1287
+ const archive = JSON.parse(readFileSync(this.archiveFile, 'utf8'));
1288
+ if (Array.isArray(archive.jobs)) {
1289
+ return archive.jobs.find((value) => value.remote === params.remote && value.taskId === params.taskId && value.originSessionId === params.originSessionId);
1290
+ }
1291
+ }
1292
+ catch { }
1293
+ return undefined;
1294
+ }
1140
1295
  job(params) {
1141
- const job = this.state.jobs.find(value => value.remote === params.remote && value.taskId === params.taskId && value.originSessionId === params.originSessionId);
1296
+ const job = this.state.jobs.find(value => value.remote === params.remote && value.taskId === params.taskId && value.originSessionId === params.originSessionId)
1297
+ ?? this.findArchivedJob(params);
1142
1298
  if (!job)
1143
1299
  throw new Error('Task not found for this origin session');
1144
1300
  return job;
@@ -1279,13 +1435,20 @@ export class RemoteAgentGateway {
1279
1435
  break;
1280
1436
  if (this.state.executionCancellations?.[run.attemptId])
1281
1437
  continue;
1282
- if (run.executionStatus === 'working' || run.humanReviews.some(review => review.resume?.status === 'pending') || ['completed', 'failed', 'canceled'].includes(run.executionStatus)) {
1438
+ const terminalNoticeId = ['completed', 'failed', 'canceled'].includes(run.executionStatus)
1439
+ ? createHash('sha256').update(JSON.stringify([run.sourceId, run.jobId, run.attemptId, reportRevision(run), run.executionStatus])).digest('hex')
1440
+ : undefined;
1441
+ const needsTerminalNotice = terminalNoticeId && !this.state.executionNotices?.some(notice => notice.noticeId === terminalNoticeId);
1442
+ if (run.executionStatus === 'working' || run.humanReviews.some(review => review.resume?.status === 'pending') || needsTerminalNotice) {
1283
1443
  try {
1284
1444
  await this.advanceReport(run);
1285
1445
  }
1286
1446
  catch (error) {
1287
- run.resultSummary = `报告协调器等待处理:${error instanceof Error ? error.message : 'unknown error'}`;
1288
- this.save();
1447
+ const summary = `报告协调器等待处理:${error instanceof Error ? error.message : 'unknown error'}`;
1448
+ if (run.resultSummary !== summary) {
1449
+ run.resultSummary = summary;
1450
+ this.save();
1451
+ }
1289
1452
  }
1290
1453
  }
1291
1454
  }
@@ -1324,6 +1487,9 @@ export class RemoteAgentGateway {
1324
1487
  }
1325
1488
  await this.reconcileIdleSessions();
1326
1489
  await this.automation?.reconcileAcknowledgements();
1490
+ if (this.now() - this.lastArchivedAt >= 24 * 60 * 60 * 1000) {
1491
+ this.archiveColdState();
1492
+ }
1327
1493
  })();
1328
1494
  this.reconciling = pending;
1329
1495
  try {
@@ -2705,12 +2871,28 @@ export async function serveA2AGateway(input, options = {}) {
2705
2871
  if (registration && !registration.ok)
2706
2872
  console.error(`[a2a-gateway] DreamMate registration failed: ${registration.reason ?? 'unknown reason'}`);
2707
2873
  // Node's directory is ephemeral. Re-report after a Node restart; this never registers new execution targets.
2874
+ let lastDreamMateReason;
2708
2875
  const reporting = options.report === false ? undefined : setInterval(() => {
2709
2876
  void reportToAgent(entry).then(result => {
2710
- if (!result.ok)
2711
- console.error(`[a2a-gateway] DreamMate re-registration failed: ${result.reason ?? 'unknown reason'}`);
2877
+ if (!result.ok) {
2878
+ const reason = result.reason ?? 'unknown reason';
2879
+ if (reason !== lastDreamMateReason) {
2880
+ lastDreamMateReason = reason;
2881
+ console.error(`[a2a-gateway] ${new Date().toISOString()} DreamMate re-registration failed: ${reason}`);
2882
+ }
2883
+ }
2884
+ else {
2885
+ if (lastDreamMateReason !== undefined) {
2886
+ console.error(`[a2a-gateway] ${new Date().toISOString()} DreamMate re-registration recovered`);
2887
+ lastDreamMateReason = undefined;
2888
+ }
2889
+ }
2712
2890
  }).catch(error => {
2713
- console.error(`[a2a-gateway] DreamMate re-registration error: ${error instanceof Error ? error.message : String(error)}`);
2891
+ const msg = error instanceof Error ? error.message : String(error);
2892
+ if (msg !== lastDreamMateReason) {
2893
+ lastDreamMateReason = msg;
2894
+ console.error(`[a2a-gateway] ${new Date().toISOString()} DreamMate re-registration error: ${msg}`);
2895
+ }
2714
2896
  });
2715
2897
  }, 15_000);
2716
2898
  reporting?.unref();
@@ -30,6 +30,16 @@ export const catalogDescriptors = [
30
30
  "integrated": true,
31
31
  "install_command": "curl -fsSL https://x.ai/cli/install.sh | bash"
32
32
  },
33
+ {
34
+ "type": "codebuddy",
35
+ "label": "CodeBuddy Code",
36
+ "binary": "codebuddy",
37
+ "acp_capable": true,
38
+ "cli_capable": true,
39
+ "cc_transport": "cli-stream",
40
+ "integrated": true,
41
+ "install_command": "npm install -g @tencent-ai/codebuddy-code"
42
+ },
33
43
  {
34
44
  "type": "cursor",
35
45
  "label": "Cursor Agent",