@nelsonlongxiang/dsh-open-a2a-net 0.7.0 → 0.8.1-preview.1
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/LICENSE +21 -0
- package/README.md +109 -94
- package/README_zh.md +64 -66
- package/THIRD_PARTY_NOTICES.md +12 -0
- package/assets/nexusDist/assets/index-BuidhKVr.css +1 -0
- package/assets/nexusDist/assets/index-YtYrkDJi.js +9 -0
- package/assets/nexusDist/index.html +2 -2
- package/cli/a2a.mjs +349 -20
- package/cordis.patch.yml +167 -0
- package/docs/licenses/dsh-superagent-MIT.txt +21 -0
- package/lib/a2a-client.js +12 -4
- package/lib/card.js +2 -0
- package/lib/cli-deposit.js +75 -4
- package/lib/config.js +1 -2
- package/lib/direct-forward.js +23 -1
- package/lib/faces/admin.js +31 -48
- package/lib/faces/wire.js +110 -71
- package/lib/followup-admission.js +47 -0
- package/lib/followup-delivery.js +19 -2
- package/lib/index.js +618 -389
- package/lib/node-self.js +1 -1
- package/lib/outbound-scope.js +10 -0
- package/lib/peer-directory.js +3 -1
- package/lib/queue-guard.js +1 -1
- package/lib/receipt.js +24 -2
- package/lib/skill/SKILL.md +1 -0
- package/lib/skill/references/cli.md +193 -21
- package/lib/skill/references/collaboration.md +3 -2
- package/lib/skill/references/superagent.md +106 -0
- package/lib/superagent/a2a-watch.js +587 -0
- package/lib/superagent/contract.js +1 -0
- package/lib/superagent/host/a2a-source.js +251 -0
- package/lib/superagent/host/executor.js +520 -0
- package/lib/superagent/host/index.js +1107 -0
- package/lib/superagent/host/policy.js +308 -0
- package/lib/superagent/host/pr-follow.js +158 -0
- package/lib/superagent/host/review-requests.js +77 -0
- package/lib/superagent/host/role-tools.js +137 -0
- package/lib/superagent/host/store.js +136 -0
- package/lib/superagent/host/tools.js +297 -0
- package/lib/superagent/source-types.js +22 -0
- package/lib/superagent/upstream/dsh-superagent/src/core/assignments.js +160 -0
- package/lib/superagent/upstream/dsh-superagent/src/core/engine.js +244 -0
- package/lib/superagent/upstream/dsh-superagent/src/core/errors.js +63 -0
- package/lib/superagent/upstream/dsh-superagent/src/core/evals.js +381 -0
- package/lib/superagent/upstream/dsh-superagent/src/core/ids.js +5 -0
- package/lib/superagent/upstream/dsh-superagent/src/core/index.js +9 -0
- package/lib/superagent/upstream/dsh-superagent/src/core/intake.js +68 -0
- package/lib/superagent/upstream/dsh-superagent/src/core/memory.js +51 -0
- package/lib/superagent/upstream/dsh-superagent/src/core/model.js +79 -0
- package/lib/superagent/upstream/dsh-superagent/src/core/part.js +71 -0
- package/lib/superagent/upstream/dsh-superagent/src/core/ports.js +1 -0
- package/lib/superagent/upstream/dsh-superagent/src/core/reasons.js +35 -0
- package/lib/superagent/upstream/dsh-superagent/src/core/replies.js +94 -0
- package/lib/superagent/upstream/dsh-superagent/src/core/stage.js +27 -0
- package/lib/superagent/upstream/dsh-superagent/src/core/tickets.js +487 -0
- package/lib/superagent/upstream/snapshot-8c32a9d.js +62 -0
- package/lib/task-auth.js +21 -0
- package/lib/task-ledger-rows.js +4 -0
- package/lib/task-ledger.js +69 -3
- package/lib/tools/info.js +13 -7
- package/lib/types/a2a-client.d.ts +0 -7
- package/lib/types/cli-deposit.d.ts +65 -1
- package/lib/types/config.d.ts +6 -20
- package/lib/types/direct-forward.d.ts +14 -0
- package/lib/types/faces/admin.d.ts +5 -0
- package/lib/types/faces/wire.d.ts +20 -57
- package/lib/types/followup-admission.d.ts +13 -0
- package/lib/types/followup-delivery.d.ts +1 -1
- package/lib/types/index.d.ts +0 -2
- package/lib/types/outbound-scope.d.ts +1 -0
- package/lib/types/queue-guard.d.ts +2 -0
- package/lib/types/receipt.d.ts +21 -1
- package/lib/types/superagent/a2a-watch.d.ts +227 -0
- package/lib/types/superagent/contract.d.ts +36 -0
- package/lib/types/superagent/host/a2a-source.d.ts +90 -0
- package/lib/types/superagent/host/executor.d.ts +132 -0
- package/lib/types/superagent/host/index.d.ts +340 -0
- package/lib/types/superagent/host/policy.d.ts +128 -0
- package/lib/types/superagent/host/pr-follow.d.ts +51 -0
- package/lib/types/superagent/host/review-requests.d.ts +36 -0
- package/lib/types/superagent/host/role-tools.d.ts +85 -0
- package/lib/types/superagent/host/store.d.ts +61 -0
- package/lib/types/superagent/host/tools.d.ts +32 -0
- package/lib/types/superagent/source-types.d.ts +218 -0
- package/lib/types/superagent/upstream/dsh-superagent/src/core/assignments.d.ts +53 -0
- package/lib/types/superagent/upstream/dsh-superagent/src/core/engine.d.ts +191 -0
- package/lib/types/superagent/upstream/dsh-superagent/src/core/errors.d.ts +58 -0
- package/lib/types/superagent/upstream/dsh-superagent/src/core/evals.d.ts +99 -0
- package/lib/types/superagent/upstream/dsh-superagent/src/core/ids.d.ts +1 -0
- package/lib/types/superagent/upstream/dsh-superagent/src/core/index.d.ts +9 -0
- package/lib/types/superagent/upstream/dsh-superagent/src/core/intake.d.ts +15 -0
- package/lib/types/superagent/upstream/dsh-superagent/src/core/memory.d.ts +40 -0
- package/lib/types/superagent/upstream/dsh-superagent/src/core/model.d.ts +432 -0
- package/lib/types/superagent/upstream/dsh-superagent/src/core/part.d.ts +49 -0
- package/lib/types/superagent/upstream/dsh-superagent/src/core/ports.d.ts +217 -0
- package/lib/types/superagent/upstream/dsh-superagent/src/core/reasons.d.ts +36 -0
- package/lib/types/superagent/upstream/dsh-superagent/src/core/replies.d.ts +55 -0
- package/lib/types/superagent/upstream/dsh-superagent/src/core/stage.d.ts +18 -0
- package/lib/types/superagent/upstream/dsh-superagent/src/core/tickets.d.ts +151 -0
- package/lib/types/superagent/upstream/snapshot-8c32a9d.d.ts +317 -0
- package/lib/types/task-auth.d.ts +9 -0
- package/lib/types/task-ledger-rows.d.ts +21 -4
- package/lib/types/task-ledger.d.ts +9 -0
- package/lib/types/types.d.ts +7 -4
- package/nexus-stage/scripts/mockhost.py +2 -2
- package/nexus-stage/src/main.ts +27 -0
- package/nexus-stage/src/planning-card-text.ts +1 -1
- package/nexus-stage/src/planning-team-roles.ts +80 -0
- package/nexus-stage/src/planning-types.ts +2 -0
- package/nexus-stage/src/planning-view.ts +1 -0
- package/nexus-stage/src/planning.css +29 -9
- package/nexus-stage/src/wb-superagent.ts +518 -0
- package/nexus-stage/src/workbench.css +32 -0
- package/nexus-stage/src/workbench.ts +25 -3
- package/nexus-stage/src/world.ts +1 -1
- package/package.json +8 -2
- package/assets/nexusDist/assets/index-C7HagaGy.css +0 -1
- package/assets/nexusDist/assets/index-CA_YZTWG.js +0 -9
- package/assets/stageDist/assets/index-Bj7S2pA1.css +0 -1
- package/assets/stageDist/assets/index-C-28k_o5.js +0 -974
- package/assets/stageDist/assets/interiors-CQGBjffT.png +0 -0
- package/assets/stageDist/assets/office-tileset-CHQT-uYL.png +0 -0
- package/assets/stageDist/index.html +0 -13
- package/lib/legacy/teams-bridge-inbound.js +0 -156
- package/lib/teams-bridge.js +0 -18
- package/lib/types/legacy/teams-bridge-inbound.d.ts +0 -94
- package/lib/types/teams-bridge.d.ts +0 -112
|
@@ -0,0 +1,587 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* superagent a2a Source (plan nodes p2a-source-code and p3-source-explicit; designs: docs/design/superagent-a2a-p2-source-design.md,
|
|
3
|
+
* docs/design/superagent-a2a-watch.md).
|
|
4
|
+
*
|
|
5
|
+
* Reads one dedicated a2a-net CLI identity's mailbox through `a2a-net inbox --after` and turns each message into a superagent
|
|
6
|
+
* Trigger. `observe` (the default) never replies; `reply` answers the caller that sent the message: one formal receipt per
|
|
7
|
+
* task, later messages as new tasks in the same context, each after the home host rechecks the caller's link. It is a
|
|
8
|
+
* standalone export (`./a2a-watch`) that nothing in this plugin loads; superagent loads it only where an operator enables it.
|
|
9
|
+
*
|
|
10
|
+
* Trust comes from structured mailbox fields only (`proof`, `receipt_for`, `dup`, `task_id`); the message text and
|
|
11
|
+
* every meta field are data, never parsed for decisions.
|
|
12
|
+
*/
|
|
13
|
+
import { health, key, threadKey } from "./source-types.js";
|
|
14
|
+
export const KIND = 'a2a';
|
|
15
|
+
/** The program superagent's Commands runs; the deployment puts the a2a-net CLI on PATH with this identity's home. */
|
|
16
|
+
export const PROGRAM = 'a2a-net';
|
|
17
|
+
/**
|
|
18
|
+
* D4 as revised by S36: a host-verified origin, this host's own process, or a CLI identity deposited on this host makes an
|
|
19
|
+
* actor — and only together with a link (LINK_RULES below).
|
|
20
|
+
*/
|
|
21
|
+
export const TRUSTED_PROOFS = new Set(['origin-claim', 'in-process', 'cli-identity']);
|
|
22
|
+
/**
|
|
23
|
+
* The host admission rules that are an operator's link (S36; p3 design Q1): a canvas both share, a pinned remote ref, or a
|
|
24
|
+
* CLI identity deposited through this host's control route. roster-shared is not one — members join a roster themselves.
|
|
25
|
+
*/
|
|
26
|
+
export const LINK_RULES = new Set(['canvas-shared', 'remote-ref-samezone', 'remote-ref-foreign', 'remote-ref-cli', 'cli-deposit']);
|
|
27
|
+
/** S27 L1: task ids this Source sends start with this; a row carrying one is never taken in (filtered as loop). */
|
|
28
|
+
export const LOOP_PREFIX = 'a2a-';
|
|
29
|
+
export const HEALTH = { read: 'a2a', deposit: 'a2a-deposit', reply: 'a2a-reply' };
|
|
30
|
+
/** Source-scoped KV records (superagent keys are plain strings). */
|
|
31
|
+
export const KV = {
|
|
32
|
+
cursor: 'a2a-cursor', renewedAt: 'a2a-renewed-at', rows: 'a2a-rows', pages: 'a2a-pages', healthLog: 'a2a-health-log',
|
|
33
|
+
heartbeat: 'a2a-heartbeat', answered: 'a2a-answered', sendFailed: 'a2a-send-failed',
|
|
34
|
+
};
|
|
35
|
+
/**
|
|
36
|
+
* Records kept for the shadow acceptance (D1, D2): the newest ROW_RECORD_CAP row outcomes, PAGE_RECORD_CAP page headers
|
|
37
|
+
* (one per read) and HEALTH_RECORD_CAP health errors. Older ones roll off; none ever holds message text.
|
|
38
|
+
*/
|
|
39
|
+
export const ROW_RECORD_CAP = 1000;
|
|
40
|
+
export const PAGE_RECORD_CAP = 1000;
|
|
41
|
+
export const HEALTH_RECORD_CAP = 200;
|
|
42
|
+
/** Plan P (v5.1 A15): one heartbeat page per hour at most, carrying the rounds and the row records since the previous one. */
|
|
43
|
+
export const HEARTBEAT_MS = 3_600_000;
|
|
44
|
+
/** P3-8: the reply bookkeeping is bounded; both maps drop entries older than KV_TTL_DAYS and keep the newest CAP. */
|
|
45
|
+
export const ANSWERED_RECORD_CAP = 2000;
|
|
46
|
+
export const SEND_FAILED_RECORD_CAP = 1000;
|
|
47
|
+
export const KV_TTL_DAYS = 7;
|
|
48
|
+
/** S25 O5: a message still unsent this long after its first failure is gone. */
|
|
49
|
+
export const GONE_AFTER_MS = 24 * 3_600_000;
|
|
50
|
+
/** The host's admission vocabulary (src/cli-deposit.ts MAIL_ADMISSIONS): a row record keeps an admission only from this set. */
|
|
51
|
+
export const ADMISSION_VALUES = new Set(['scope-off', 'host-face', 'local-exempt', 'roster-shared', 'canvas-shared', 'remote-ref-samezone', 'remote-ref-foreign', 'remote-ref-cli', 'peer-org', 'node-fact', 'cli-deposit']);
|
|
52
|
+
/** The host's proof vocabulary (src/task-auth.ts AuthProof): a row record keeps a proof only from this closed set. */
|
|
53
|
+
const PROOF_VALUES = new Set(['origin-claim', 'claim-mismatch', 'legacy-window', 'unbound', 'cli-identity', 'in-process', 'none']);
|
|
54
|
+
/** The structured health values a health record may keep; free text (such as a CLI error) stays in the live report only. */
|
|
55
|
+
const LOG_VALUE_KEYS = new Set(['count', 'lost', 'after', 'epochChanged', 'task']);
|
|
56
|
+
/** The mailbox's duplicate markers a row record may keep. */
|
|
57
|
+
const DUP_VALUES = new Set(['sync-answered']);
|
|
58
|
+
/**
|
|
59
|
+
* Append rows by their stable key epoch:seq (a replay records nothing twice), keeping the newest ROW_RECORD_CAP. Every
|
|
60
|
+
* appended record also counts toward the next heartbeat, in the same write, so an interrupted round leaves the counts true.
|
|
61
|
+
*/
|
|
62
|
+
export function recordRows(ctx, rows) {
|
|
63
|
+
if (rows.length === 0)
|
|
64
|
+
return 0;
|
|
65
|
+
let appended = 0;
|
|
66
|
+
const kept = ctx.state.get(KV.rows) ?? [];
|
|
67
|
+
const seen = new Set(kept.map(r => `${r.epoch}:${String(r.seq)}`));
|
|
68
|
+
for (const row of rows) {
|
|
69
|
+
const key = `${row.epoch}:${String(row.seq)}`;
|
|
70
|
+
if (row.seq !== null && seen.has(key))
|
|
71
|
+
continue;
|
|
72
|
+
seen.add(key);
|
|
73
|
+
kept.push(row);
|
|
74
|
+
appended += 1;
|
|
75
|
+
}
|
|
76
|
+
ctx.state.set(KV.rows, kept.slice(-ROW_RECORD_CAP));
|
|
77
|
+
if (appended > 0) {
|
|
78
|
+
const hb = heartbeatState(ctx);
|
|
79
|
+
ctx.state.set(KV.heartbeat, { ...hb, rows: hb.rows + appended });
|
|
80
|
+
}
|
|
81
|
+
return appended;
|
|
82
|
+
}
|
|
83
|
+
function heartbeatState(ctx) {
|
|
84
|
+
const hb = ctx.state.get(KV.heartbeat);
|
|
85
|
+
return hb !== undefined && typeof hb.rounds === 'number' && typeof hb.rows === 'number' ? hb : { last: null, rounds: 0, rows: 0 };
|
|
86
|
+
}
|
|
87
|
+
/**
|
|
88
|
+
* Count one finished round and write the heartbeat page when one is due: `force` (the first round after a start), no
|
|
89
|
+
* heartbeat yet, or HEARTBEAT_MS since the last one. The page carries the counts since the previous heartbeat, this round included.
|
|
90
|
+
*/
|
|
91
|
+
export function noteRound(ctx, page, force) {
|
|
92
|
+
const hb = heartbeatState(ctx);
|
|
93
|
+
const rounds = hb.rounds + 1;
|
|
94
|
+
const due = force || hb.last === null || Date.parse(page.at) - Date.parse(hb.last) >= HEARTBEAT_MS;
|
|
95
|
+
if (!due) {
|
|
96
|
+
ctx.state.set(KV.heartbeat, { ...hb, rounds });
|
|
97
|
+
return false;
|
|
98
|
+
}
|
|
99
|
+
recordPage(ctx, { ...page, heartbeat: true, rounds, rows: hb.rows });
|
|
100
|
+
ctx.state.set(KV.heartbeat, { last: page.at, rounds: 0, rows: 0 });
|
|
101
|
+
return true;
|
|
102
|
+
}
|
|
103
|
+
/** Keep one read's page header, newest PAGE_RECORD_CAP. */
|
|
104
|
+
export function recordPage(ctx, page) {
|
|
105
|
+
const kept = ctx.state.get(KV.pages) ?? [];
|
|
106
|
+
kept.push(page);
|
|
107
|
+
ctx.state.set(KV.pages, kept.slice(-PAGE_RECORD_CAP));
|
|
108
|
+
}
|
|
109
|
+
/** Report a health error and keep its record (A7: every loss round leaves a record, whatever the current value says). */
|
|
110
|
+
export function reportError(ctx, entry, h, now = () => new Date()) {
|
|
111
|
+
const log = ctx.state.get(KV.healthLog) ?? [];
|
|
112
|
+
const values = h.values === undefined ? undefined : Object.fromEntries(Object.entries(h.values).filter(([name]) => LOG_VALUE_KEYS.has(name)));
|
|
113
|
+
log.push({ at: h.at ?? now().toISOString(), entry, state: h.state, ...(h.code !== undefined ? { code: h.code } : {}), ...(values !== undefined ? { values } : {}) });
|
|
114
|
+
ctx.state.set(KV.healthLog, log.slice(-HEALTH_RECORD_CAP));
|
|
115
|
+
ctx.report(entry, h);
|
|
116
|
+
}
|
|
117
|
+
const DEFAULTS = { mode: 'observe', pollSeconds: 30, renewMinutes: 60 };
|
|
118
|
+
const isRecord = (value) => value !== null && typeof value === 'object' && !Array.isArray(value);
|
|
119
|
+
const intIn = (value, min, max) => typeof value === 'number' && Number.isInteger(value) && value >= min && value <= max;
|
|
120
|
+
/** A strict schema without zod (superagent only calls parse / safeParse on it): unknown keys and unknown modes fail closed. */
|
|
121
|
+
function strictSchema(check) {
|
|
122
|
+
const safeParse = (value) => {
|
|
123
|
+
const data = isRecord(value) ? check(value) : undefined;
|
|
124
|
+
return data === undefined ? { success: false } : { success: true, data };
|
|
125
|
+
};
|
|
126
|
+
return {
|
|
127
|
+
safeParse,
|
|
128
|
+
parse(value) {
|
|
129
|
+
const result = safeParse(value);
|
|
130
|
+
if (!result.success)
|
|
131
|
+
throw new Error('a2a Source: invalid configuration');
|
|
132
|
+
return result.data;
|
|
133
|
+
},
|
|
134
|
+
};
|
|
135
|
+
}
|
|
136
|
+
export const configSchema = strictSchema(value => {
|
|
137
|
+
if (Object.keys(value).some(name => !(name in DEFAULTS)))
|
|
138
|
+
return undefined;
|
|
139
|
+
const mode = value.mode ?? DEFAULTS.mode;
|
|
140
|
+
const pollSeconds = value.pollSeconds ?? DEFAULTS.pollSeconds;
|
|
141
|
+
// The deposit lives 4h on its home host; renewing at least every 230 minutes keeps it live.
|
|
142
|
+
const renewMinutes = value.renewMinutes ?? DEFAULTS.renewMinutes;
|
|
143
|
+
if ((mode !== 'observe' && mode !== 'reply') || !intIn(pollSeconds, 10, 3600) || !intIn(renewMinutes, 10, 230))
|
|
144
|
+
return undefined;
|
|
145
|
+
return { mode, pollSeconds, renewMinutes };
|
|
146
|
+
});
|
|
147
|
+
function senderRows(value) {
|
|
148
|
+
if (!Array.isArray(value))
|
|
149
|
+
return undefined;
|
|
150
|
+
const rows = [];
|
|
151
|
+
for (const row of value) {
|
|
152
|
+
if (!isRecord(row) || typeof row.id !== 'string' || row.id === '' || Object.keys(row).some(name => name !== 'id' && name !== 'name'))
|
|
153
|
+
return undefined;
|
|
154
|
+
if (row.name !== undefined && typeof row.name !== 'string')
|
|
155
|
+
return undefined;
|
|
156
|
+
rows.push({ id: row.id, ...(row.name !== undefined ? { name: row.name } : {}) });
|
|
157
|
+
}
|
|
158
|
+
return rows;
|
|
159
|
+
}
|
|
160
|
+
/**
|
|
161
|
+
* The a2a Policy part. A2A callers are agents (D7), so superagent admits them only through the Source's bot list
|
|
162
|
+
* (policy.ts machineGate): `bots` is the owner's list of callers whose requests may become inferred candidates — on top of
|
|
163
|
+
* the host link the scope already requires (p3 design v1.2). `allowed` stays for the form; a2a never sends human Triggers.
|
|
164
|
+
*/
|
|
165
|
+
export const policySchema = strictSchema(value => {
|
|
166
|
+
if (Object.keys(value).some(name => name !== 'allowed' && name !== 'bots'))
|
|
167
|
+
return undefined;
|
|
168
|
+
const allowed = senderRows(value.allowed ?? []);
|
|
169
|
+
const bots = senderRows(value.bots ?? []);
|
|
170
|
+
if (allowed === undefined || bots === undefined)
|
|
171
|
+
return undefined;
|
|
172
|
+
return { allowed, bots };
|
|
173
|
+
});
|
|
174
|
+
/**
|
|
175
|
+
* Translate one mailbox row. The id is key('a2a', from, task_id): a task id is unique only inside the host's idempotency
|
|
176
|
+
* window, so the caller is part of it. Rows without a task id (an older host) are unreadable, never guessed; a
|
|
177
|
+
* `dup: 'sync-answered'` row is a copy of a reply the caller already got and makes no second Trigger.
|
|
178
|
+
*/
|
|
179
|
+
export function translate(row, epoch) {
|
|
180
|
+
if (!isRecord(row))
|
|
181
|
+
return { kind: 'unreadable' };
|
|
182
|
+
const mail = row;
|
|
183
|
+
if (typeof mail.from !== 'string' || mail.from === '' || typeof mail.text !== 'string' || typeof mail.at !== 'number' || !Number.isInteger(mail.seq))
|
|
184
|
+
return { kind: 'unreadable' };
|
|
185
|
+
if (typeof mail.task_id !== 'string' || mail.task_id === '')
|
|
186
|
+
return { kind: 'unreadable' };
|
|
187
|
+
if (mail.dup === 'sync-answered')
|
|
188
|
+
return { kind: 'duplicateCopy' };
|
|
189
|
+
const thread = typeof mail.context_id === 'string' && mail.context_id !== '' ? mail.context_id : mail.task_id;
|
|
190
|
+
const proof = typeof mail.proof === 'string' ? mail.proof : undefined;
|
|
191
|
+
const receiptFor = typeof mail.receipt_for === 'string' && mail.receipt_for !== '' ? mail.receipt_for : undefined;
|
|
192
|
+
const admission = typeof mail.admission === 'string' && ADMISSION_VALUES.has(mail.admission) ? mail.admission : undefined;
|
|
193
|
+
// A reply rechecks the caller on the face it came in by: this host's own sessions on the local face, the rest on the wire.
|
|
194
|
+
const ingress = proof === 'in-process' ? { ingress: 'local' } : {};
|
|
195
|
+
return {
|
|
196
|
+
kind: 'trigger',
|
|
197
|
+
trigger: {
|
|
198
|
+
id: key(KIND, mail.from, mail.task_id),
|
|
199
|
+
source: KIND,
|
|
200
|
+
threads: [{ source: KIND, id: thread }],
|
|
201
|
+
actor: { source: KIND, id: mail.from },
|
|
202
|
+
// D7 (global review of PR #385): an A2A caller is an agent, so a bot by fact; p3 settles S13 ② against this.
|
|
203
|
+
human: false,
|
|
204
|
+
addressed: 'direct',
|
|
205
|
+
at: new Date(mail.at).toISOString(),
|
|
206
|
+
text: mail.text,
|
|
207
|
+
channel: { source: KIND, thread: `${KIND}:${thread}`, address: { caller: mail.from, task: mail.task_id, ...(thread !== mail.task_id ? { context: thread } : {}), ...ingress } },
|
|
208
|
+
meta: {
|
|
209
|
+
taskId: mail.task_id,
|
|
210
|
+
...(thread !== mail.task_id ? { contextId: thread } : {}),
|
|
211
|
+
seq: mail.seq,
|
|
212
|
+
epoch,
|
|
213
|
+
...(proof !== undefined ? { proof } : {}),
|
|
214
|
+
...(receiptFor !== undefined ? { receiptFor } : {}),
|
|
215
|
+
...(admission !== undefined ? { admission } : {}),
|
|
216
|
+
// Observation only: what S13 ② would have given a verified caller. S21 replaced it with the rule-based inferred
|
|
217
|
+
// path; it rides along for the audit and nothing reads it for a decision.
|
|
218
|
+
...(proof !== undefined && TRUSTED_PROOFS.has(proof) ? { s13Strength: 'explicit-if-allowed' } : {}),
|
|
219
|
+
},
|
|
220
|
+
},
|
|
221
|
+
};
|
|
222
|
+
}
|
|
223
|
+
/**
|
|
224
|
+
* Receiving scope from the stored meta alone (p3 design P3-3), first failure wins and everything fails closed: an untrusted
|
|
225
|
+
* proof (unverified), no operator link (unlinked — a row from a host before p1-mail-admission has no admission and lands
|
|
226
|
+
* here), one of this Source's own task ids (loop, S27 L1), a receipt. Only then the mailbox row.
|
|
227
|
+
*/
|
|
228
|
+
export function scope(input) {
|
|
229
|
+
const proof = input.meta.proof;
|
|
230
|
+
if (typeof proof !== 'string' || !TRUSTED_PROOFS.has(proof))
|
|
231
|
+
return { listened: false, reason: 'unverified' };
|
|
232
|
+
const admission = input.meta.admission;
|
|
233
|
+
if (typeof admission !== 'string' || !LINK_RULES.has(admission))
|
|
234
|
+
return { listened: false, reason: 'unlinked' };
|
|
235
|
+
if (typeof input.meta.taskId === 'string' && input.meta.taskId.startsWith(LOOP_PREFIX))
|
|
236
|
+
return { listened: false, reason: 'loop' };
|
|
237
|
+
if (typeof input.meta.receiptFor === 'string')
|
|
238
|
+
return { listened: false, reason: 'receipt' };
|
|
239
|
+
return { listened: true, observed: false, row: 'mailbox' };
|
|
240
|
+
}
|
|
241
|
+
function parsePage(output) {
|
|
242
|
+
const page = JSON.parse(output);
|
|
243
|
+
if (!isRecord(page) || typeof page.epoch !== 'string' || typeof page.next !== 'string' || !Array.isArray(page.mail) ||
|
|
244
|
+
!(page.lost === null || (typeof page.lost === 'number' && Number.isInteger(page.lost))) || typeof page.epochChanged !== 'boolean') {
|
|
245
|
+
throw new Error('a2a-net inbox --after printed an unexpected page');
|
|
246
|
+
}
|
|
247
|
+
return page;
|
|
248
|
+
}
|
|
249
|
+
/** A loss the read must surface (S2): never hidden, always with its numbers. */
|
|
250
|
+
export function lossHealth(page, after, at) {
|
|
251
|
+
const values = { lost: String(page.lost), after, epochChanged: String(page.epochChanged) };
|
|
252
|
+
if (page.epochChanged || page.lost === null) {
|
|
253
|
+
return { state: 'error', at, values, detail: `The home host's mailbox store restarted (new epoch); mail during the restart may be lost (lost=${String(page.lost)}, epochChanged=${String(page.epochChanged)}, cursor ${after})` };
|
|
254
|
+
}
|
|
255
|
+
if (page.cursorAhead === true)
|
|
256
|
+
return { state: 'error', at, values, detail: `The stored cursor ${after} is ahead of the home host; it was not issued there (lost unknown)` };
|
|
257
|
+
if (page.lost > 0)
|
|
258
|
+
return { state: 'error', at, values, detail: `${String(page.lost)} message(s) were pushed out of the mailbox before this read; they cannot be recovered` };
|
|
259
|
+
return undefined;
|
|
260
|
+
}
|
|
261
|
+
/**
|
|
262
|
+
* Read the mailbox after the stored cursor, take in each row, then move the cursor. An interrupted round leaves the cursor
|
|
263
|
+
* where it was; the stable Trigger ids make the replay a duplicate, never a second Trigger.
|
|
264
|
+
*/
|
|
265
|
+
export async function pollMailbox(ctx, signal, now = () => new Date(), firstRound = false) {
|
|
266
|
+
const after = ctx.state.get(KV.cursor) ?? 'start';
|
|
267
|
+
const page = parsePage(await ctx.commands.withSignal(signal).run(PROGRAM, ['inbox', '--after', after]));
|
|
268
|
+
const at = now().toISOString();
|
|
269
|
+
const header = { at, after, next: page.next, epoch: page.epoch, lost: page.lost, epochChanged: page.epochChanged, cursorAhead: page.cursorAhead === true };
|
|
270
|
+
const loss = lossHealth(page, after, at);
|
|
271
|
+
// Plan P: a read with rows or a reported loss is recorded, before any row is judged, so a missed loss still shows.
|
|
272
|
+
if (page.mail.length > 0 || loss !== undefined)
|
|
273
|
+
recordPage(ctx, header);
|
|
274
|
+
if (loss !== undefined)
|
|
275
|
+
reportError(ctx, HEALTH.read, loss, now);
|
|
276
|
+
const summary = { read: page.mail.length, triggers: 0, duplicateCopies: 0, unreadable: 0, next: page.next, ...(loss !== undefined ? { loss } : {}) };
|
|
277
|
+
// Each row's record is written as soon as the row is through, so an interrupted round keeps what it did; the cursor
|
|
278
|
+
// moves only after every row of the round has its record (D1).
|
|
279
|
+
for (const row of page.mail) {
|
|
280
|
+
if (signal.aborted)
|
|
281
|
+
throw new Error('The a2a Source stopped during the read');
|
|
282
|
+
const result = translate(row, page.epoch);
|
|
283
|
+
const raw = isRecord(row) ? row : {};
|
|
284
|
+
const base = { epoch: page.epoch, seq: Number.isInteger(raw.seq) ? raw.seq : null,
|
|
285
|
+
task_id: typeof raw.task_id === 'string' && raw.task_id !== '' ? raw.task_id : null, from: typeof raw.from === 'string' && raw.from !== '' ? raw.from : null, at,
|
|
286
|
+
proof: typeof raw.proof === 'string' && PROOF_VALUES.has(raw.proof) ? raw.proof : null,
|
|
287
|
+
receipt_for: typeof raw.receipt_for === 'string' && raw.receipt_for !== '' ? raw.receipt_for : null,
|
|
288
|
+
dup: typeof raw.dup === 'string' && DUP_VALUES.has(raw.dup) ? raw.dup : null,
|
|
289
|
+
admission: typeof raw.admission === 'string' && ADMISSION_VALUES.has(raw.admission) ? raw.admission : null };
|
|
290
|
+
if (result.kind === 'duplicateCopy') {
|
|
291
|
+
summary.duplicateCopies += 1;
|
|
292
|
+
recordRows(ctx, [{ ...base, outcome: 'duplicateCopy' }]);
|
|
293
|
+
continue;
|
|
294
|
+
}
|
|
295
|
+
if (result.kind === 'unreadable') {
|
|
296
|
+
summary.unreadable += 1;
|
|
297
|
+
recordRows(ctx, [{ ...base, outcome: 'unreadable' }]);
|
|
298
|
+
continue;
|
|
299
|
+
}
|
|
300
|
+
const received = await ctx.receive(result.trigger);
|
|
301
|
+
summary.triggers += 1;
|
|
302
|
+
// The Engine says whether it filtered the Trigger; this kind's own scope says why.
|
|
303
|
+
const verdict = scope(result.trigger);
|
|
304
|
+
const outcome = received !== 'filtered' ? received : filteredOutcome(verdict);
|
|
305
|
+
recordRows(ctx, [{ ...base, outcome }]);
|
|
306
|
+
ctx.threads.describe(threadKey(result.trigger.threads[0]), { label: `A2A ${result.trigger.actor.id}` });
|
|
307
|
+
}
|
|
308
|
+
ctx.state.set(KV.cursor, page.next);
|
|
309
|
+
noteRound(ctx, header, firstRound);
|
|
310
|
+
return summary;
|
|
311
|
+
}
|
|
312
|
+
/** The row outcome for a Trigger the Engine filtered: this kind's scope says why (unverified when it gives no reason it knows). */
|
|
313
|
+
function filteredOutcome(verdict) {
|
|
314
|
+
const reason = verdict.listened ? undefined : verdict.reason;
|
|
315
|
+
return reason === 'unlinked' ? 'filtered:unlinked' : reason === 'loop' ? 'filtered:loop' : reason === 'receipt' ? 'filtered:receipt' : 'filtered:unverified';
|
|
316
|
+
}
|
|
317
|
+
/** Re-publish the deposit when `renewMinutes` passed since the last success; returns whether it published. */
|
|
318
|
+
export async function renewDeposit(ctx, config, signal, now = Date.now) {
|
|
319
|
+
const last = ctx.state.get(KV.renewedAt);
|
|
320
|
+
if (typeof last === 'number' && now() - last < config.renewMinutes * 60_000)
|
|
321
|
+
return false;
|
|
322
|
+
// P3-9 (S33): in reply mode the deposit declares that its mailbox owes receipts; observe withdraws it on the next renewal.
|
|
323
|
+
await ctx.commands.withSignal(signal).run(PROGRAM, config.mode === 'reply' ? ['publish', '--owes'] : ['publish']);
|
|
324
|
+
ctx.state.set(KV.renewedAt, now());
|
|
325
|
+
return true;
|
|
326
|
+
}
|
|
327
|
+
/**
|
|
328
|
+
* P3-6 (S26; Q2: closed is abandoned): how the ticket behind a message ended, as the receipt says it. A ticket that has not
|
|
329
|
+
* ended yet (a result sent on a ready report) is completed — the delivery is what the caller's receipt answers.
|
|
330
|
+
*/
|
|
331
|
+
export function receiptOutcome(ticket) {
|
|
332
|
+
const ended = ticket?.ended;
|
|
333
|
+
if (ended === undefined)
|
|
334
|
+
return 'completed';
|
|
335
|
+
switch (ended.outcome) {
|
|
336
|
+
case 'completed':
|
|
337
|
+
case 'merged': return 'completed';
|
|
338
|
+
case 'dropped': return 'rejected';
|
|
339
|
+
case 'closed': return 'abandoned';
|
|
340
|
+
case 'stopped': return ended.by === 'human' ? 'abandoned' : 'failed';
|
|
341
|
+
}
|
|
342
|
+
}
|
|
343
|
+
/** --exit-class codes (P3-7): 4 the class is gone, 5 the task already carries a different receipt. */
|
|
344
|
+
export const EXIT_GONE = 4;
|
|
345
|
+
export const EXIT_RECEIPT_CONFLICT = 5;
|
|
346
|
+
const exitCodeOf = (error) => isRecord(error) && typeof error.exitCode === 'number' ? error.exitCode : undefined;
|
|
347
|
+
/** The task ids the CLI takes (cli/a2a.mjs taskFlag and receipt): a receipt rides receipt-<id>, at most 80 characters. */
|
|
348
|
+
const RECEIPT_TASK = /^[A-Za-z0-9][A-Za-z0-9._:-]*$/;
|
|
349
|
+
const receiptable = (task) => RECEIPT_TASK.test(task) && `receipt-${task}`.length <= 80;
|
|
350
|
+
/** A bounded id → ISO-time map: entries older than KV_TTL_DAYS go, then the oldest beyond `cap`. */
|
|
351
|
+
function pruneStamps(stamps, cap, nowMs) {
|
|
352
|
+
const live = Object.entries(stamps).filter(([, at]) => nowMs - Date.parse(at) <= KV_TTL_DAYS * 86_400_000);
|
|
353
|
+
live.sort((a, b) => a[1].localeCompare(b[1]));
|
|
354
|
+
return Object.fromEntries(live.slice(-cap));
|
|
355
|
+
}
|
|
356
|
+
function stamps(ctx, record) {
|
|
357
|
+
const value = ctx.state.get(record);
|
|
358
|
+
return isRecord(value) ? value : {};
|
|
359
|
+
}
|
|
360
|
+
function setStamp(ctx, record, id, at, cap, nowMs) {
|
|
361
|
+
const next = { ...stamps(ctx, record) };
|
|
362
|
+
if (at === undefined)
|
|
363
|
+
delete next[id];
|
|
364
|
+
else
|
|
365
|
+
next[id] = at;
|
|
366
|
+
ctx.state.set(record, pruneStamps(next, cap, nowMs));
|
|
367
|
+
}
|
|
368
|
+
/** The reply channel accepts an address that names a real caller and its task (not the in-process "unknown"). */
|
|
369
|
+
export function replyAllowed(address, config) {
|
|
370
|
+
return config.mode === 'reply' && typeof address.caller === 'string' && address.caller !== '' && address.caller !== 'unknown' &&
|
|
371
|
+
typeof address.task === 'string' && address.task !== '';
|
|
372
|
+
}
|
|
373
|
+
/**
|
|
374
|
+
* Send one outbound message (p3 design P3-5 to P3-8). Before anything leaves, the home host rechecks the caller against its
|
|
375
|
+
* current links (O1): no link, no message. The task's first message is its one formal receipt; later ones are new tasks
|
|
376
|
+
* in the same context with an a2a- task id (O2, L1). A class of gone, a vanished link, or 24 hours of failures since the
|
|
377
|
+
* first one end the message as gone with a health record; any other failure throws so the Outbox retries.
|
|
378
|
+
*/
|
|
379
|
+
export async function sendReply(ctx, commands, message, now = () => new Date(), options = {}) {
|
|
380
|
+
const at = now();
|
|
381
|
+
const nowMs = at.getTime();
|
|
382
|
+
const { caller, task, context, ingress } = message.channel.address;
|
|
383
|
+
const gone = (detail) => {
|
|
384
|
+
setStamp(ctx, KV.sendFailed, message.id, undefined, SEND_FAILED_RECORD_CAP, nowMs);
|
|
385
|
+
reportError(ctx, HEALTH.reply, { state: 'error', detail, at: at.toISOString(), values: { task: String(task ?? '') } }, now);
|
|
386
|
+
return 'gone';
|
|
387
|
+
};
|
|
388
|
+
if (caller === undefined || task === undefined || !replyAllowed(message.channel.address, { mode: 'reply' }))
|
|
389
|
+
return gone('The reply has no caller to go to');
|
|
390
|
+
try {
|
|
391
|
+
if (ctx.config(KIND)?.mode !== 'reply')
|
|
392
|
+
throw new Error('The a2a Source is not in reply mode');
|
|
393
|
+
const check = JSON.parse(await commands.run(PROGRAM, ['admission', caller, ...(ingress === 'local' ? ['--local'] : []), '--json']));
|
|
394
|
+
const rule = isRecord(check) && check.admitted === true && typeof check.rule === 'string' ? check.rule : undefined;
|
|
395
|
+
if (rule === undefined || !LINK_RULES.has(rule))
|
|
396
|
+
return gone(`${caller} is no longer linked to this identity; the reply was not sent`);
|
|
397
|
+
// A held receipt (the host's call: an acknowledged request whose ticket has no result yet) leaves the task's one
|
|
398
|
+
// formal receipt for the result; this message goes out as a follow-up in the same context.
|
|
399
|
+
const first = options.holdReceipt !== true && stamps(ctx, KV.answered)[task] === undefined;
|
|
400
|
+
const text = message.text.trim() === '' ? '(no text)' : message.text;
|
|
401
|
+
if (first && !receiptable(task))
|
|
402
|
+
return gone(`Task ${task} cannot carry a receipt (its id is not a CLI task id); the reply was not sent`);
|
|
403
|
+
// The engine's reply to a ticket's question carries the id key('attention-reply', <attention id>) — hashed, so
|
|
404
|
+
// it is recognised by recomputing that id from the ticket's open question, never by a prefix.
|
|
405
|
+
const ticket = message.ticketId !== undefined ? ctx.tickets.get(message.ticketId) : undefined;
|
|
406
|
+
const attention = ticket?.attention !== undefined && message.id === key('attention-reply', ticket.attention.id);
|
|
407
|
+
const args = first
|
|
408
|
+
? ['receipt', task, '--to', caller, ...(attention ? ['--attention'] : ['--outcome', options.outcome ?? receiptOutcome(ticket)]), '--json', '--exit-class', '--', text]
|
|
409
|
+
: ['route', caller, '--task', `${LOOP_PREFIX}${key(message.id)}`, '--context', context ?? task, '--json', '--exit-class', '--', text];
|
|
410
|
+
try {
|
|
411
|
+
await commands.run(PROGRAM, args);
|
|
412
|
+
}
|
|
413
|
+
catch (error) {
|
|
414
|
+
const code = exitCodeOf(error);
|
|
415
|
+
if (code === EXIT_GONE)
|
|
416
|
+
return gone(`The host says ${caller} can no longer receive task ${task}'s reply`);
|
|
417
|
+
// The receipt is already there (a crash after the CLI succeeded, before the record): it counts as sent.
|
|
418
|
+
if (!(first && code === EXIT_RECEIPT_CONFLICT))
|
|
419
|
+
throw error;
|
|
420
|
+
}
|
|
421
|
+
if (first)
|
|
422
|
+
setStamp(ctx, KV.answered, task, at.toISOString(), ANSWERED_RECORD_CAP, nowMs);
|
|
423
|
+
setStamp(ctx, KV.sendFailed, message.id, undefined, SEND_FAILED_RECORD_CAP, nowMs);
|
|
424
|
+
return 'sent';
|
|
425
|
+
}
|
|
426
|
+
catch (error) {
|
|
427
|
+
const firstFailure = stamps(ctx, KV.sendFailed)[message.id];
|
|
428
|
+
if (firstFailure !== undefined && nowMs - Date.parse(firstFailure) >= GONE_AFTER_MS)
|
|
429
|
+
return gone(`Task ${task}'s reply stayed unsent for 24 hours; last: ${String(error)}`);
|
|
430
|
+
if (firstFailure === undefined)
|
|
431
|
+
setStamp(ctx, KV.sendFailed, message.id, at.toISOString(), SEND_FAILED_RECORD_CAP, nowMs);
|
|
432
|
+
throw error;
|
|
433
|
+
}
|
|
434
|
+
}
|
|
435
|
+
const fields = [
|
|
436
|
+
{ key: 'mode', type: 'select', label: { zh: '模式', en: 'Mode' }, options: [
|
|
437
|
+
{ value: 'observe', label: { zh: '影子(只登记,不回发)', en: 'Shadow (records only, never replies)' } },
|
|
438
|
+
{ value: 'reply', label: { zh: '回发(回执与后续消息只回原调用方)', en: 'Reply (receipts and follow-ups go to the original caller only)' } }
|
|
439
|
+
] },
|
|
440
|
+
{ key: 'pollSeconds', type: 'number', advanced: true, min: 10, max: 3600, label: { zh: '轮询间隔 / 秒', en: 'Polling interval / seconds' } },
|
|
441
|
+
{ key: 'renewMinutes', type: 'number', advanced: true, min: 10, max: 230, label: { zh: '户口续期间隔 / 分钟', en: 'Deposit renewal / minutes' } },
|
|
442
|
+
];
|
|
443
|
+
/**
|
|
444
|
+
* The kind. Its Channel needs the kind's own SourceContext (KV records, tickets), which superagent hands out only for a
|
|
445
|
+
* registered kind, so the plugin entry builds it with a getter it fills right after registering (P3-6).
|
|
446
|
+
*/
|
|
447
|
+
export function createA2aKind(context, now = () => new Date()) {
|
|
448
|
+
return {
|
|
449
|
+
kind: KIND,
|
|
450
|
+
title: { zh: 'A2A 信箱', en: 'A2A mailbox' },
|
|
451
|
+
description: { zh: '接收一个专用 a2a-net CLI 身份信箱里的消息;影子模式只登记,回发模式只回原调用方。', en: "Receives the messages in a dedicated a2a-net CLI identity's mailbox; shadow mode only records, reply mode answers the original caller only." },
|
|
452
|
+
schema: configSchema,
|
|
453
|
+
fields,
|
|
454
|
+
health: [HEALTH.read, HEALTH.deposit, HEALTH.reply],
|
|
455
|
+
scope: (input, _config) => scope(input),
|
|
456
|
+
channel: {
|
|
457
|
+
// Observe mode: no address may receive a reply, whatever the Engine produces; Outbox keeps such messages as ignored.
|
|
458
|
+
allowed: (address, config) => replyAllowed(address, config),
|
|
459
|
+
send(host, message) {
|
|
460
|
+
const ctx = context();
|
|
461
|
+
if (ctx === undefined)
|
|
462
|
+
return Promise.reject(new Error('The a2a Source is not running yet; the reply waits'));
|
|
463
|
+
return sendReply(ctx, host.commands, message, now);
|
|
464
|
+
},
|
|
465
|
+
link: address => ({ url: '', label: { zh: `A2A 调用方 ${address.caller ?? ''}`, en: `A2A caller ${address.caller ?? ''}` } }),
|
|
466
|
+
},
|
|
467
|
+
threadContext: {
|
|
468
|
+
messageId: trigger => String(trigger.meta.taskId ?? ''),
|
|
469
|
+
// An A2A exchange is flat: the thread, its root and the parent all read the same pages of `a2a-net thread`.
|
|
470
|
+
async read(commands, trigger, _part, cursor) {
|
|
471
|
+
const context = typeof trigger.meta.contextId === 'string' ? trigger.meta.contextId : typeof trigger.meta.taskId === 'string' ? trigger.meta.taskId : '';
|
|
472
|
+
if (context === '')
|
|
473
|
+
return { messages: [], body: { messages: [] } };
|
|
474
|
+
const page = JSON.parse(await commands.run(PROGRAM, ['thread', context, '--limit', '20', ...(cursor !== undefined ? ['--before', cursor] : [])]));
|
|
475
|
+
const messages = (page.entries ?? []).map(entry => ({
|
|
476
|
+
id: entry.task_id ?? `${entry.dir}:${String(entry.seq ?? entry.at)}`,
|
|
477
|
+
from: entry.dir === 'in' ? entry.from ?? '' : page.handle ?? '',
|
|
478
|
+
at: new Date(entry.at).toISOString(),
|
|
479
|
+
text: entry.text,
|
|
480
|
+
bot: true,
|
|
481
|
+
}));
|
|
482
|
+
return { messages, ...(typeof page.next_before === 'string' ? { next: page.next_before } : {}), body: { messages } };
|
|
483
|
+
},
|
|
484
|
+
},
|
|
485
|
+
policy: {
|
|
486
|
+
schema: policySchema,
|
|
487
|
+
fields: [
|
|
488
|
+
{ key: 'allowed', type: 'rows', label: { zh: '能发起工作的调用方(A2A 调用方都是 agent,此栏不生效)', en: 'Callers who may originate work (A2A callers are agents; unused)' }, columns: [
|
|
489
|
+
{ key: 'id', type: 'text', label: { zh: '调用方句柄', en: 'Caller handle' } },
|
|
490
|
+
{ key: 'name', type: 'text', label: { zh: '名字', en: 'Name' }, optional: true }
|
|
491
|
+
] },
|
|
492
|
+
{ key: 'bots', type: 'rows', label: { zh: '可接单的 A2A 调用方(还须在宿主链接集内)', en: 'A2A callers whose requests may be taken (they must also be linked on the host)' }, columns: [
|
|
493
|
+
{ key: 'id', type: 'text', label: { zh: '调用方句柄', en: 'Caller handle' } },
|
|
494
|
+
{ key: 'name', type: 'text', label: { zh: '名字', en: 'Name' }, optional: true }
|
|
495
|
+
] }
|
|
496
|
+
],
|
|
497
|
+
explicit: { zh: '名单里的调用方经宿主校验后路由到本身份。', en: 'A listed caller, verified by the host, routes to this identity.' },
|
|
498
|
+
// One receiving scope, every cell closed: an A2A caller is a bot (D7), admitted only through the bots list.
|
|
499
|
+
rows: () => [{ id: 'mailbox', label: 'mailbox', note: { zh: 'A2A 信箱', en: 'A2A mailbox' }, cells: { listedUnaddressed: false, unlistedAddressed: false, unlistedUnaddressed: false } }],
|
|
500
|
+
},
|
|
501
|
+
environment: {
|
|
502
|
+
variables: [
|
|
503
|
+
{ key: 'DSH_SUPERAGENT_A2A_CALLER', description: { zh: '发起工单的 A2A 调用方句柄;工单不是从本来源来的时为空', en: 'The A2A caller that started the ticket; empty when it did not start on this Source' } },
|
|
504
|
+
{ key: 'DSH_SUPERAGENT_A2A_CONTEXT', description: { zh: '该工单的 A2A context id;工单不是从本来源来的时为空', en: "The ticket's A2A context id; empty when it did not start on this Source" } },
|
|
505
|
+
],
|
|
506
|
+
values: ({ trigger }) => ({
|
|
507
|
+
DSH_SUPERAGENT_A2A_CALLER: trigger?.source === KIND ? trigger.actor.id : '',
|
|
508
|
+
DSH_SUPERAGENT_A2A_CONTEXT: trigger?.source === KIND ? String(trigger.meta.contextId ?? trigger.meta.taskId ?? '') : '',
|
|
509
|
+
}),
|
|
510
|
+
},
|
|
511
|
+
};
|
|
512
|
+
}
|
|
513
|
+
/** The kind without a running context (its Channel can only make the Outbox retry); the plugin entry builds its own. */
|
|
514
|
+
export const a2aKind = createA2aKind(() => undefined);
|
|
515
|
+
const delay = (ms, signal) => new Promise(resolve => {
|
|
516
|
+
if (signal.aborted) {
|
|
517
|
+
resolve();
|
|
518
|
+
return;
|
|
519
|
+
}
|
|
520
|
+
const timer = setTimeout(() => { signal.removeEventListener('abort', done); resolve(); }, ms);
|
|
521
|
+
const done = () => { clearTimeout(timer); resolve(); };
|
|
522
|
+
signal.addEventListener('abort', done, { once: true });
|
|
523
|
+
});
|
|
524
|
+
/** The polling loop: waits for setup (observe mode reads while setup is pending), follows the switch, renews the deposit, reads, and reports health. */
|
|
525
|
+
export async function watch(ctx, signal, now = () => new Date()) {
|
|
526
|
+
await ctx.ready;
|
|
527
|
+
let readFailures = 0;
|
|
528
|
+
let depositFailures = 0;
|
|
529
|
+
// The first finished round after a start writes a heartbeat at once (v5.1 A15).
|
|
530
|
+
let firstRound = true;
|
|
531
|
+
while (!signal.aborted) {
|
|
532
|
+
const config = ctx.config(KIND);
|
|
533
|
+
// Setup restarts dsh-superagent once it resolves the accounts (superagent docs/008-cookbook.md, step 9), so a Source
|
|
534
|
+
// that is not configured yet normally reads nothing and returns. Observe mode deliberately reads anyway: while setup is
|
|
535
|
+
// pending superagent still records what Sources receive and only holds evaluation, dispatch and sending (runtime.ts
|
|
536
|
+
// paused(): "sources still record incoming triggers"; passes.ts pump()), which is exactly a shadow run. Any other mode
|
|
537
|
+
// keeps waiting for setup.
|
|
538
|
+
if (!ctx.configured() && config?.mode !== 'observe') {
|
|
539
|
+
ctx.report(HEALTH.read, health('paused', 'setupPending'));
|
|
540
|
+
return;
|
|
541
|
+
}
|
|
542
|
+
if (config === undefined)
|
|
543
|
+
ctx.report(HEALTH.read, health('paused', 'sourceOff'));
|
|
544
|
+
else {
|
|
545
|
+
try {
|
|
546
|
+
if (await renewDeposit(ctx, config, signal, () => now().getTime()))
|
|
547
|
+
ctx.report(HEALTH.deposit, { state: 'ready', detail: 'deposit renewed', at: now().toISOString() });
|
|
548
|
+
depositFailures = 0;
|
|
549
|
+
}
|
|
550
|
+
catch (error) {
|
|
551
|
+
depositFailures += 1;
|
|
552
|
+
if (!signal.aborted && depositFailures >= 3)
|
|
553
|
+
reportError(ctx, HEALTH.deposit, { state: 'error', detail: `${String(depositFailures)} consecutive failed deposit renewals; last: ${String(error)}`, at: now().toISOString(), values: { count: String(depositFailures) } }, now);
|
|
554
|
+
}
|
|
555
|
+
try {
|
|
556
|
+
const round = await pollMailbox(ctx, signal, now, firstRound);
|
|
557
|
+
firstRound = false;
|
|
558
|
+
readFailures = 0;
|
|
559
|
+
// A round that lost mail ends on its error (S2: never hidden). The next clean round reports ready again: the
|
|
560
|
+
// loss stays visible for at least one poll interval, and the round summary in each ready says what was read.
|
|
561
|
+
if (round.loss === undefined)
|
|
562
|
+
ctx.report(HEALTH.read, { state: 'ready', detail: `${String(round.read)} read, ${String(round.triggers)} taken in, ${String(round.duplicateCopies)} duplicate copies, ${String(round.unreadable)} unreadable`, at: now().toISOString() });
|
|
563
|
+
}
|
|
564
|
+
catch (error) {
|
|
565
|
+
readFailures += 1;
|
|
566
|
+
if (!signal.aborted && readFailures >= 3)
|
|
567
|
+
reportError(ctx, HEALTH.read, { ...health('error', 'pollFailures', { count: String(readFailures), error: String(error) }), at: now().toISOString() }, now);
|
|
568
|
+
}
|
|
569
|
+
}
|
|
570
|
+
await delay((config?.pollSeconds ?? DEFAULTS.pollSeconds) * 1000, signal);
|
|
571
|
+
}
|
|
572
|
+
}
|
|
573
|
+
export const name = 'dsh-superagent-a2a';
|
|
574
|
+
export const inject = ['orchestrator'];
|
|
575
|
+
export function apply(ctx) {
|
|
576
|
+
let running;
|
|
577
|
+
const kind = createA2aKind(() => running);
|
|
578
|
+
ctx.effect(() => ctx.orchestrator.sources.register(kind), 'a2a: source kind');
|
|
579
|
+
ctx.effect(() => {
|
|
580
|
+
const source = ctx.orchestrator.context(kind);
|
|
581
|
+
running = source;
|
|
582
|
+
const controller = new AbortController();
|
|
583
|
+
// A failure that escapes the loop becomes the Source's health instead of an unhandled rejection.
|
|
584
|
+
const loop = watch(source, controller.signal).catch((error) => { reportError(source, HEALTH.read, { state: 'error', detail: String(error) }); });
|
|
585
|
+
return async () => { controller.abort(); await loop; running = undefined; };
|
|
586
|
+
}, 'a2a: mailbox loop');
|
|
587
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|