@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
package/lib/faces/wire.js
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { FollowupAcceptanceUnknown, ACCEPTANCE_UNKNOWN_NOTE, ACCEPTANCE_INSERTED_NOTE } from "../followup-admission.js";
|
|
1
2
|
import { isRemoteMemberRef, validRemoteMemberRef } from "../canvas-store.js";
|
|
2
3
|
import { splitCanvasOwner } from "../canvas-id.js";
|
|
3
4
|
import { CLI_HANDLE_RE } from "../cli-deposit.js";
|
|
@@ -94,7 +95,7 @@ export class SyncAnswered {
|
|
|
94
95
|
}
|
|
95
96
|
}
|
|
96
97
|
export function registerWireFaces(webServer, d) {
|
|
97
|
-
const { ctx, logger, config, cliDeposits, canvasStore, canvasNameReserved, sessionNodes, joinedSessions, idempotencyStore, verifyOriginClaim, remoteCliProof, callerLinkedToThisHost, recordActivity, peerKeyAdmits, a2aCallerRefusal, a2aCallerAdmission, allowlistVersionNow, observeAuthorization, scanSessionLogList, readSessionLogTail, taskLedger, refuseIfFlooded, refuseIfQueueFull, settleAndAnnounce, waitForForwardBirth, session, resolveAgentForTeam, parseCanvasTeamName, canvasLiveAgent, wakeColdTeam, probeConsumption, sessionTeamOf, localSessionOfHandle, steerRelay, followupRelay, cancelQueuedTask, fromClause, sanitizeFromClause, armReceiptAutosend, eventCountOf, receiptExpectationOf, armAsyncNudge, liveAgent, callerIsAgent, selfRouteText, noWakeFaceText, archivedColdMatchText, noColdMatchText,
|
|
98
|
+
const { ctx, logger, config, cliDeposits, canvasStore, canvasNameReserved, sessionNodes, joinedSessions, idempotencyStore, verifyOriginClaim, remoteCliProof, callerLinkedToThisHost, recordActivity, peerKeyAdmits, a2aCallerRefusal, a2aCallerAdmission, allowlistVersionNow, observeAuthorization, scanSessionLogList, readSessionLogTail, taskLedger, refuseIfFlooded, refuseIfQueueFull, settleAndAnnounce, waitForForwardBirth, session, resolveAgentForTeam, parseCanvasTeamName, canvasLiveAgent, wakeColdTeam, probeConsumption, sessionTeamOf, localSessionOfHandle, steerRelay, followupRelay, cancelQueuedTask, fromClause, sanitizeFromClause, armReceiptAutosend, eventCountOf, receiptExpectationOf, armAsyncNudge, liveAgent, callerIsAgent, selfRouteText, noWakeFaceText, archivedColdMatchText, noColdMatchText, routeIntoAgent, } = d;
|
|
98
99
|
const syncAnswered = new SyncAnswered();
|
|
99
100
|
// gh#45 CLI 户口卡面 (peer face, unsigned card serve): the deposited
|
|
100
101
|
// CLI's SIGNED card is served verbatim under its own base URL — an
|
|
@@ -183,6 +184,11 @@ export function registerWireFaces(webServer, d) {
|
|
|
183
184
|
const op = body.op;
|
|
184
185
|
const name = typeof body.name === 'string' ? body.name : '';
|
|
185
186
|
const rawId = typeof body.id === 'string' ? body.id : '';
|
|
187
|
+
if (d.teamCanvasBound?.(name) === true) {
|
|
188
|
+
recordActivity('in', 'fleet-canvas', claim.caller, false);
|
|
189
|
+
send(200, JSON.stringify({ ok: false, error: '[superagent-team-canvas] a superagent team is changed only by its own host\'s owner' }));
|
|
190
|
+
return;
|
|
191
|
+
}
|
|
186
192
|
// gh#131: a peer names our sessions by handle — the session it names, for removal.
|
|
187
193
|
// A bare handle may still infer for routing, never for deleting another stored slot.
|
|
188
194
|
const provenOwn = rawId.endsWith('@' + d.ownCanvasFingerprint);
|
|
@@ -206,8 +212,11 @@ export function registerWireFaces(webServer, d) {
|
|
|
206
212
|
payload = { ok: false, error: 'CLI home pins may only be set by this host local control route' };
|
|
207
213
|
else {
|
|
208
214
|
const proof = await d.canvasMemberForWrite(rawId, undefined, claim.card);
|
|
215
|
+
const teamRefusal = proof.ok ? d.teamCanvasRefusal?.(name, proof.member) : undefined;
|
|
209
216
|
if (!proof.ok)
|
|
210
217
|
payload = proof;
|
|
218
|
+
else if (teamRefusal !== undefined)
|
|
219
|
+
payload = { ok: false, error: teamRefusal };
|
|
211
220
|
else {
|
|
212
221
|
canvasStore.create(name);
|
|
213
222
|
payload = { ok: canvasStore.addMember(name, proof.member, undefined, { ownerKey: proof.ownerKey }), members: canvasStore.membersOf(name) };
|
|
@@ -483,6 +492,10 @@ export function registerWireFaces(webServer, d) {
|
|
|
483
492
|
const ownerQualified = splitCanvasOwner(typeof body.team === 'string' ? body.team : '');
|
|
484
493
|
const team = ownerQualified.owner !== undefined && ownerQualified.owner === d.ownCanvasFingerprint ? ownerQualified.team : typeof body.team === 'string' ? body.team : '';
|
|
485
494
|
const message = typeof body.message === 'string' ? body.message : '';
|
|
495
|
+
// Design v5 (D2): a route to the bound team canvas is admitted and mailed as one to the team's address; the
|
|
496
|
+
// requester's own spelling is what the team answers on behalf of (review R1).
|
|
497
|
+
const mailTeam = d.teamMailboxOf?.(team) ?? team;
|
|
498
|
+
const addressed = mailTeam !== team && typeof body.team === 'string' ? body.team : team;
|
|
486
499
|
const caller = typeof body.caller_session === 'string' ? body.caller_session : '';
|
|
487
500
|
// P2 receipt-callback: where THIS node's receipt should route on
|
|
488
501
|
// the caller's side — the caller knows its routable address best
|
|
@@ -530,7 +543,7 @@ export function registerWireFaces(webServer, d) {
|
|
|
530
543
|
const envelopePresent = hasOriginClaimFields(req);
|
|
531
544
|
const earlyClaim = envelopePresent ? await completeInboundVerification(() => verifyOriginClaim(req, { cli: true, rawBody })) : { ok: false, reason: 'absent' };
|
|
532
545
|
const memberClaim = /^[^/\s]+\/[0-9a-f]{8}(?:@[0-9a-f]{8})?$/.test(caller) || caller === config.team || caller.startsWith(config.team + '/') || canvasStore.list().some(name => canvasStore.rawMembersOf(name).some(ref => ref === caller || ref.startsWith(caller + '@'))) || String(req.headers['x-a2a-caller'] ?? '') === config.team;
|
|
533
|
-
const gate = verifiedInboundAdmission(earlyClaim, envelopePresent, memberClaim, key => a2aCallerAdmission(caller,
|
|
546
|
+
const gate = verifiedInboundAdmission(earlyClaim, envelopePresent, memberClaim, key => a2aCallerAdmission(caller, mailTeam, undefined, key));
|
|
534
547
|
if (!gate.ok) {
|
|
535
548
|
recordActivity('in', team, caller, false);
|
|
536
549
|
const payload = JSON.stringify({ error: 'untrusted-origin: OriginClaim verification failed (' + gate.reason + ')', code: WIRE_ERROR_INBOUND_VERIFICATION, reason: gate.reason, team, task_status: 'TASK_STATE_FAILED', delivered: false });
|
|
@@ -547,7 +560,7 @@ export function registerWireFaces(webServer, d) {
|
|
|
547
560
|
return;
|
|
548
561
|
}
|
|
549
562
|
const cliProof = foreignCli && earlyClaim?.ok ? await remoteCliProof(caller, earlyClaim).catch(() => undefined) : undefined;
|
|
550
|
-
let admission = foreignCli ? a2aCallerAdmission(caller,
|
|
563
|
+
let admission = foreignCli ? a2aCallerAdmission(caller, mailTeam, cliProof, earlyClaim?.ok ? earlyClaim.card.publicKey : undefined) : gate.admission;
|
|
551
564
|
// #282 S3 (same team authorizes): a receipt for this host's own forward, to the CLI that sent it, from a
|
|
552
565
|
// receiver frozen at birth on the selected peer's key — the owner's signed canvas is the return path.
|
|
553
566
|
const echoed = !admission.ok && cliDeposits.get(team) !== undefined ? parseReceipt(message) : null;
|
|
@@ -561,6 +574,14 @@ export function registerWireFaces(webServer, d) {
|
|
|
561
574
|
if (basis !== undefined)
|
|
562
575
|
admission = { ok: true, via: 'peer-org', rule: 'peer-org', basis: [basis] };
|
|
563
576
|
}
|
|
577
|
+
// Design v5 (v5-B2): a superagent team answers this host's own request from its process face, on its canvas's
|
|
578
|
+
// behalf — admitted for that request's receipt alone (teamReceiptBasis), whatever the target session's links.
|
|
579
|
+
const teamAnswer = !admission.ok && echoed === null && earlyClaim.ok ? parseReceipt(message) : null;
|
|
580
|
+
if (teamAnswer !== null && earlyClaim.ok) {
|
|
581
|
+
const basis = d.teamReceiptBasis?.(teamAnswer.taskId, caller, team, teamAnswer.envelope?.onBehalfOf, earlyClaim);
|
|
582
|
+
if (basis !== undefined)
|
|
583
|
+
admission = { ok: true, via: 'peer-org', rule: 'peer-org', basis: [basis] };
|
|
584
|
+
}
|
|
564
585
|
const callerRefusal = refusalOf(admission);
|
|
565
586
|
if (callerRefusal !== undefined || !admission.ok) {
|
|
566
587
|
recordActivity('in', team, caller === '' ? 'anonymous' : caller, false);
|
|
@@ -570,6 +591,14 @@ export function registerWireFaces(webServer, d) {
|
|
|
570
591
|
res.end(payload);
|
|
571
592
|
return;
|
|
572
593
|
}
|
|
594
|
+
const routerRefusal = d.superagentInbound(team) ?? d.teamAddressRefusal?.(team, message);
|
|
595
|
+
if (routerRefusal !== undefined) {
|
|
596
|
+
recordActivity('in', team, caller, false);
|
|
597
|
+
const payload = JSON.stringify({ error: routerRefusal, code: -32000, team, task_status: 'TASK_STATE_FAILED' });
|
|
598
|
+
res.writeHead(200, { 'Content-Type': 'application/json', 'Content-Length': Buffer.byteLength(payload) });
|
|
599
|
+
res.end(payload);
|
|
600
|
+
return;
|
|
601
|
+
}
|
|
573
602
|
// #114 S6: a version an inbound record is born under is always in the history.
|
|
574
603
|
observeAuthorization('lazy');
|
|
575
604
|
// #114 S2: the version is read at admission time, beside the decision it explains.
|
|
@@ -618,9 +647,26 @@ export function registerWireFaces(webServer, d) {
|
|
|
618
647
|
res.end(payload);
|
|
619
648
|
return;
|
|
620
649
|
}
|
|
650
|
+
if (priorDelivery?.state === 'reserved' && priorDelivery.callerKey === (claim.ok ? claim.card.publicKey : undefined) && idempotencyStore.query(taskId, idemFingerprint).found) {
|
|
651
|
+
const payload = JSON.stringify({ error: ACCEPTANCE_UNKNOWN_NOTE, acceptance: 'unknown', task_id: taskId, task_status: 'TASK_STATE_FAILED', code: -32000 });
|
|
652
|
+
res.writeHead(200, { 'Content-Type': 'application/json', 'Content-Length': Buffer.byteLength(payload) });
|
|
653
|
+
res.end(payload);
|
|
654
|
+
return;
|
|
655
|
+
}
|
|
621
656
|
const idemVerdict = idempotencyStore.claim(taskId, idemFingerprint);
|
|
622
657
|
if (idemVerdict !== 'fresh') {
|
|
623
658
|
const replay = idemVerdict === 'replay';
|
|
659
|
+
// p1-mailbox-owes (S33, b): the original caller's same-payload resend of a task an owing deposit still owes
|
|
660
|
+
// reads as the first answer did — delivered, with the mailbox marker — so a caller whose first answer was lost
|
|
661
|
+
// books the debt now. Nothing is written again: no second mailbox row, no second inbound row, no second slot.
|
|
662
|
+
// Anyone else gets the ordinary 409 (the fingerprint binds the caller too; this check holds should that change).
|
|
663
|
+
const stillOwed = replay && cliDeposits.owes(mailTeam) ? taskLedger.find(taskId) : undefined;
|
|
664
|
+
if (stillOwed !== undefined && stillOwed.direction === 'inbound' && stillOwed.status === 'pending' && stillOwed.team === addressed && stillOwed.peer === `local:${caller}`) {
|
|
665
|
+
const payload = JSON.stringify({ routed: true, delivered: true, receipt: 'mailbox', team, task_id: taskId, context_id: stillOwed.contextId ?? contextId, task_status: 'TASK_STATE_DELIVERED', note: `delivered to the mailbox of ${team} — it owes a receipt` });
|
|
666
|
+
res.writeHead(200, { 'Content-Type': 'application/json', 'Content-Length': Buffer.byteLength(payload) });
|
|
667
|
+
res.end(payload);
|
|
668
|
+
return;
|
|
669
|
+
}
|
|
624
670
|
// Conflicts warn (caller key reuse bugs); harmless replays stay silent.
|
|
625
671
|
if (!replay)
|
|
626
672
|
logger.warn(`a2a: idempotency CONFLICT on task ${taskId.slice(0, 80)} — same key reused with a different payload (caller bug; never auto-retry)`);
|
|
@@ -660,7 +706,8 @@ export function registerWireFaces(webServer, d) {
|
|
|
660
706
|
}
|
|
661
707
|
if (refuseIfFlooded(caller, message, team, taskId, res))
|
|
662
708
|
return;
|
|
663
|
-
|
|
709
|
+
// p1-mailbox-owes (S33): a deposit whose card declares it owes receipts is under the per-target cap like a session.
|
|
710
|
+
if (refuseIfQueueFull(caller, message, team, taskId, (cliDeposits.get(mailTeam) !== undefined && !cliDeposits.owes(mailTeam)) || d.superagentIntake(mailTeam), res))
|
|
664
711
|
return;
|
|
665
712
|
// The caller-side receipt correlation: a message shaped as a
|
|
666
713
|
// receipt resolves the task it echoes, whichever wait semantics
|
|
@@ -692,21 +739,44 @@ export function registerWireFaces(webServer, d) {
|
|
|
692
739
|
// CLI handle never resolves a session and never wakes — it lands
|
|
693
740
|
// in the deposit's mailbox and answers delivered. Placement here
|
|
694
741
|
// keeps the idempotency claim (above) exactly as for sessions.
|
|
695
|
-
const cliRow = cliDeposits.get(
|
|
742
|
+
const cliRow = cliDeposits.get(mailTeam);
|
|
696
743
|
if (cliRow !== undefined) {
|
|
697
744
|
const answered = parseReceipt(message);
|
|
698
745
|
// #298: only the answering member's own, unrefused receipt is the duplicate of a sync answer.
|
|
699
|
-
const duplicate = answered !== null && refusedSettlement === undefined && syncAnswered.take(answered.taskId,
|
|
700
|
-
cliDeposits.mail(
|
|
746
|
+
const duplicate = answered !== null && refusedSettlement === undefined && syncAnswered.take(answered.taskId, mailTeam, caller);
|
|
747
|
+
const evicted = cliDeposits.mail(mailTeam, caller, `${directHeader(caller)}\n\n${message}`, duplicate ? 'sync-answered' : undefined, { taskId, contextId, proof: callerProof, ...(answered !== null ? { receiptFor: answered.taskId } : {}), ...(answered?.envelope?.disposition !== undefined ? { disposition: answered.envelope.disposition } : {}),
|
|
748
|
+
// p1-mail-admission: the rule this host matched when it took the delivery, as it already computed it.
|
|
749
|
+
...(admission.ok ? { admission: admission.rule } : {}) });
|
|
750
|
+
// p1-mailbox-owes (D-5): a row the cap pushed out takes its owed inbound row with it (slot freed, counted as evicted).
|
|
751
|
+
for (const gone of evicted)
|
|
752
|
+
if (gone.task_id !== undefined)
|
|
753
|
+
taskLedger.evictInbound(gone.task_id, taskLedger.find(gone.task_id)?.team ?? mailTeam);
|
|
701
754
|
recordActivity('in', team, caller, true);
|
|
702
|
-
logger.info(`a2a: cli mailbox delivery for ${
|
|
755
|
+
logger.info(`a2a: cli mailbox delivery for ${mailTeam} (from ${caller}${mailTeam !== team ? `, addressed to ${addressed}` : ''})`);
|
|
756
|
+
if (answered === null && cliDeposits.owes(mailTeam)) {
|
|
757
|
+
// p1-mailbox-owes (S33, D-2): delivered, not final — the caller books a debt, this host keeps the owed
|
|
758
|
+
// inbound row (the per-target cap counts it) and records no outcome, so a resend reads pending.
|
|
759
|
+
taskLedger.trackInbound(taskId, addressed, caller, contextId === '' ? undefined : contextId, true, briefOf(message));
|
|
760
|
+
// Design v5 (R5): a sync route to the team answers at once — the team works asynchronously.
|
|
761
|
+
if (mailTeam !== team) {
|
|
762
|
+
const teamPayload = JSON.stringify({ routed: true, delivered: true, receipt: 'mailbox', team, task_id: taskId, context_id: contextId, task_status: 'TASK_STATE_DELIVERED', note: `delivered to the superagent team ${addressed} — it works asynchronously; its result arrives as this task's receipt` });
|
|
763
|
+
res.writeHead(200, { 'Content-Type': 'application/json', 'Content-Length': Buffer.byteLength(teamPayload) });
|
|
764
|
+
res.end(teamPayload);
|
|
765
|
+
return;
|
|
766
|
+
}
|
|
767
|
+
const payload = JSON.stringify({ routed: true, delivered: true, receipt: 'mailbox', team, task_id: taskId, context_id: contextId, task_status: 'TASK_STATE_DELIVERED', note: `delivered to the mailbox of ${team} — it owes a receipt` });
|
|
768
|
+
res.writeHead(200, { 'Content-Type': 'application/json', 'Content-Length': Buffer.byteLength(payload) });
|
|
769
|
+
res.end(payload);
|
|
770
|
+
return;
|
|
771
|
+
}
|
|
703
772
|
const note = `delivered to the mailbox of ${team} — the CLI polls while online`;
|
|
704
773
|
// gh#112 review: a mailbox delivery is final from this host's
|
|
705
774
|
// side, so a resend of this id reads `completed`. A receipt the
|
|
706
775
|
// CLI routes back later still reaches its caller, but does not
|
|
707
776
|
// replace this outcome (recordOutcome is first-writer-wins).
|
|
708
777
|
idempotencyStore.recordOutcome(taskId, { status: 'completed', reply: note });
|
|
709
|
-
|
|
778
|
+
// p1-context-read: name the conversation the row was mailed under, as every other taken reply does.
|
|
779
|
+
const payload = JSON.stringify({ routed: true, delivered: true, receipt: 'mailbox', team, task_id: taskId, context_id: contextId, task_status: 'TASK_STATE_COMPLETED', note });
|
|
710
780
|
res.writeHead(200, { 'Content-Type': 'application/json', 'Content-Length': Buffer.byteLength(payload) });
|
|
711
781
|
res.end(payload);
|
|
712
782
|
return;
|
|
@@ -719,12 +789,12 @@ export function registerWireFaces(webServer, d) {
|
|
|
719
789
|
const result = await d.forwardDirect({ team: typeof body.team === 'string' && ownerQualified.owner !== undefined ? body.team : team, message, caller, taskId, contextId, noWait,
|
|
720
790
|
auth: buildAuthorization(admission, { caller, proof: callerProof, ...(claim.ok ? { claim: { caller: claim.caller, origin: originOf(claim.callerUrl) } } : {}), ingress: 'wire', allowlistVersion: admittedAt.version, target: team, receiptTarget: caller, receivedAt: admittedAt.at }),
|
|
721
791
|
localCliProof: claim.ok && claim.cli === true && claim.bound && claim.caller === caller, guarded: req.headers['x-a2a-guard'] !== undefined }).catch((error) => ({ ok: false, error: `forwarding unavailable: ${String(error)}`, code: -32000, task_id: taskId }));
|
|
722
|
-
const failure = result.ok ? '' : await d.diagnoseCanvas(team, original + ' — ' + result.error, claim.ok && claim.cli === true && claim.bound && claim.caller === caller ? caller : undefined);
|
|
723
|
-
if (!result.ok && result.code !== -32005)
|
|
792
|
+
const failure = result.ok ? '' : result.acceptance === 'unknown' ? ACCEPTANCE_UNKNOWN_NOTE : await d.diagnoseCanvas(team, original + ' — ' + result.error, claim.ok && claim.cli === true && claim.bound && claim.caller === caller ? caller : undefined);
|
|
793
|
+
if (!result.ok && result.code !== -32005 && result.acceptance !== 'unknown')
|
|
724
794
|
idempotencyStore.recordOutcome(taskId, { status: 'failed', error: failure });
|
|
725
795
|
else if (result.ok && result.task_status === 'TASK_STATE_COMPLETED')
|
|
726
796
|
idempotencyStore.recordOutcome(taskId, { status: 'completed', reply: result.reply });
|
|
727
|
-
const payload = JSON.stringify(result.ok ? { routed: true, ...(result.task_status === 'TASK_STATE_DELIVERED' ? { delivered: true } : { result: { text: result.reply } }), team, task_id: taskId, context_id: contextId, task_status: result.task_status, consumed: result.consumed, bridge: result.bridge, receipt: result.receipt, ...(result.receiverBookkeeping === 'failed' ? { receiverBookkeeping: 'failed', note: ADMITTED_BOOKKEEPING_NOTE } : {}), forwarded: true } : { error: failure, code: result.code ?? -32000, receipt: result.receipt, task_id: taskId, team, task_status: result.code === -32005 ? 'TASK_STATE_DELIVERED' : 'TASK_STATE_FAILED', ...(result.next !== undefined ? { next: result.next } : {}) });
|
|
797
|
+
const payload = JSON.stringify(result.ok ? { routed: true, ...(result.task_status === 'TASK_STATE_DELIVERED' ? { delivered: true } : { result: { text: result.reply } }), team, task_id: taskId, context_id: contextId, task_status: result.task_status, acceptance: result.acceptance, consumed: result.consumed, bridge: result.bridge, receipt: result.receipt, ...(result.receiverBookkeeping === 'failed' ? { receiverBookkeeping: 'failed', note: ADMITTED_BOOKKEEPING_NOTE } : {}), forwarded: true } : { acceptance: result.acceptance, error: failure, code: result.code ?? -32000, receipt: result.receipt, task_id: taskId, team, task_status: result.code === -32005 ? 'TASK_STATE_DELIVERED' : 'TASK_STATE_FAILED', ...(result.next !== undefined ? { next: result.next } : {}) });
|
|
728
798
|
// #298: only a reply the peer itself declares final (`reply_final`; never a host placeholder, review of
|
|
729
799
|
// #305 F3), handed to the CLI in full, marks that member's later receipt a duplicate — never a delivered,
|
|
730
800
|
// mailbox or bridge shape (F1), and never when the CLI gave up and closed the socket ('finish' does not fire).
|
|
@@ -789,7 +859,7 @@ export function registerWireFaces(webServer, d) {
|
|
|
789
859
|
const deliveredReceipt = parseReceipt(message) !== null;
|
|
790
860
|
// gh#141: a receipt is answered by nobody — its steer asks for no receipt back.
|
|
791
861
|
const receiptRequest = deliveredReceipt ? '' : `\n\n(When done, route your outcome back with one call — a2a_route { team: "${receiptTarget}", message: "[A2A receipt] task ${taskId} <one-line outcome>" }.)`;
|
|
792
|
-
followupRelay(target, `${directHeader(from)}\n\n${message}${receiptRequest}`, from === 'an unknown node' ? undefined : from, undefined, taskId, claim.ok ? claim.card.publicKey : undefined, !deliveredReceipt);
|
|
862
|
+
const acceptance = followupRelay(target, `${directHeader(from)}\n\n${message}${receiptRequest}`, from === 'an unknown node' ? undefined : from, undefined, taskId, claim.ok ? claim.card.publicKey : undefined, !deliveredReceipt);
|
|
793
863
|
steered = true;
|
|
794
864
|
if (deliveredReceipt && refusedSettlement === undefined)
|
|
795
865
|
idempotencyStore.recordOutcome(taskId, { status: 'completed', reply: 'receipt delivered' });
|
|
@@ -813,7 +883,7 @@ export function registerWireFaces(webServer, d) {
|
|
|
813
883
|
// zero ledger records for latched activations). Arming is
|
|
814
884
|
// unconditional now; settlement evidence disarms in the
|
|
815
885
|
// callback.
|
|
816
|
-
const consumedProbe = taskLedger.deliveryFor(taskId)?.state === 'claimed';
|
|
886
|
+
const consumedProbe = acceptance === 'inserted' ? false : taskLedger.deliveryFor(taskId)?.state === 'claimed';
|
|
817
887
|
// F5 (settlement integrity): the debt gate — a process-label
|
|
818
888
|
// caller cannot receive receipts, so this delivery is born
|
|
819
889
|
// fire-and-forget (receiptExpected:false, answered as
|
|
@@ -842,8 +912,10 @@ export function registerWireFaces(webServer, d) {
|
|
|
842
912
|
// nothing can pay, and a nudge chasing an answer nobody owes.
|
|
843
913
|
if (!deliveredReceipt) {
|
|
844
914
|
taskLedger.trackInbound(taskId, team, receiptTarget, contextId === '' ? undefined : contextId, receiptExpectation !== 'process-label', briefOf(message), auth, deliveredTo === team ? undefined : deliveredTo, String(target.id), consumedProbe);
|
|
845
|
-
|
|
846
|
-
|
|
915
|
+
if (acceptance !== 'inserted')
|
|
916
|
+
armReceiptAutosend(target, taskId, receiptTarget, message, steerFloor);
|
|
917
|
+
if (acceptance !== 'inserted')
|
|
918
|
+
armAsyncNudge(target, team, taskId, config.asyncNudgeDelayMs);
|
|
847
919
|
}
|
|
848
920
|
const payload = JSON.stringify({
|
|
849
921
|
routed: true,
|
|
@@ -854,6 +926,7 @@ export function registerWireFaces(webServer, d) {
|
|
|
854
926
|
context_id: contextId,
|
|
855
927
|
task_status: 'TASK_STATE_DELIVERED',
|
|
856
928
|
artifacts: [],
|
|
929
|
+
...(acceptance === 'inserted' ? { acceptance, note: ACCEPTANCE_INSERTED_NOTE } : {}),
|
|
857
930
|
consumed: consumedProbe,
|
|
858
931
|
...(req.headers['x-a2a-guard'] !== undefined ? { delivered_to: deliveredTo } : {}),
|
|
859
932
|
receipt: receiptExpectation === 'process-label' || deliveredReceipt ? 'none' : 'routed',
|
|
@@ -862,6 +935,12 @@ export function registerWireFaces(webServer, d) {
|
|
|
862
935
|
res.end(payload);
|
|
863
936
|
}
|
|
864
937
|
catch (error) {
|
|
938
|
+
if (error instanceof FollowupAcceptanceUnknown) {
|
|
939
|
+
const payload = JSON.stringify({ error: ACCEPTANCE_UNKNOWN_NOTE, acceptance: 'unknown', task_id: taskId, team, task_status: 'TASK_STATE_FAILED', code: -32000 });
|
|
940
|
+
res.writeHead(200, { 'Content-Type': 'application/json', 'Content-Length': Buffer.byteLength(payload) });
|
|
941
|
+
res.end(payload);
|
|
942
|
+
return;
|
|
943
|
+
}
|
|
865
944
|
if (error instanceof AdmittedBookkeepingError)
|
|
866
945
|
steered = true;
|
|
867
946
|
if (!steered) {
|
|
@@ -888,15 +967,7 @@ export function registerWireFaces(webServer, d) {
|
|
|
888
967
|
});
|
|
889
968
|
return;
|
|
890
969
|
}
|
|
891
|
-
|
|
892
|
-
// native-teams bridge), so the tail answers inside an IIFE.
|
|
893
|
-
await (async () => {
|
|
894
|
-
// Native-teams inbound bridge (opt-in): prepare BEFORE answering
|
|
895
|
-
// delivered — claim, seam, and parent initiator are everything
|
|
896
|
-
// that can fail fast, and a phantom dispatch must never answer
|
|
897
|
-
// success. Past prepare, the round fires detached (noWait means
|
|
898
|
-
// delivery, not settlement); its late outcome corrects the
|
|
899
|
-
// activity ring and the log.
|
|
970
|
+
{
|
|
900
971
|
const standardMiss = async () => {
|
|
901
972
|
if (team === config.team) {
|
|
902
973
|
const live = liveAgent();
|
|
@@ -919,54 +990,25 @@ export function registerWireFaces(webServer, d) {
|
|
|
919
990
|
}
|
|
920
991
|
refuseNoWait(wake?.kind === 'no-face' ? noWakeFaceText(team) : wake?.kind === 'archived' ? archivedColdMatchText(team) : noColdMatchText(team), false);
|
|
921
992
|
};
|
|
922
|
-
|
|
923
|
-
|
|
924
|
-
if (prepared.reason === 'error') {
|
|
925
|
-
refuseNoWait(prepared.error);
|
|
926
|
-
return;
|
|
927
|
-
}
|
|
928
|
-
await standardMiss();
|
|
929
|
-
return;
|
|
930
|
-
}
|
|
931
|
-
recordActivity('in', team, caller, true);
|
|
932
|
-
void nativeTeamsRound(prepared, team, caller, message, taskId, proofClause, undefined, (_team, _taskId, from) => directHeader(from))
|
|
933
|
-
.then(outcome => {
|
|
934
|
-
if (!outcome.ok) {
|
|
935
|
-
recordActivity('in', team, caller, false);
|
|
936
|
-
logger.warn(`a2a: detached native-teams round for "${team}" failed: ${outcome.error}`);
|
|
937
|
-
}
|
|
938
|
-
// W7 slice-2 hook 2: only a genuinely settled detached round
|
|
939
|
-
// records an outcome. The deadline's settled:false
|
|
940
|
-
// projection is a placeholder, not a product — the same
|
|
941
|
-
// ruling as hook 1's DELIVERED skip; placeholder prose never
|
|
942
|
-
// enters the ledger a replay could adopt from.
|
|
943
|
-
if (taskId !== '') {
|
|
944
|
-
if (!outcome.ok)
|
|
945
|
-
idempotencyStore.recordOutcome(taskId, { status: 'failed', error: outcome.error });
|
|
946
|
-
else if (outcome.settled)
|
|
947
|
-
idempotencyStore.recordOutcome(taskId, { status: 'completed', reply: outcome.reply });
|
|
948
|
-
}
|
|
949
|
-
});
|
|
950
|
-
const payload = JSON.stringify({ routed: true, delivered: true, team, session, task_id: taskId, context_id: contextId, task_status: 'TASK_STATE_DELIVERED', artifacts: [], consumed: false, bridge: 'native-teams' });
|
|
951
|
-
res.writeHead(200, { 'Content-Type': 'application/json', 'Content-Length': Buffer.byteLength(payload) });
|
|
952
|
-
res.end(payload);
|
|
953
|
-
})();
|
|
993
|
+
await standardMiss();
|
|
994
|
+
}
|
|
954
995
|
return;
|
|
955
996
|
}
|
|
956
997
|
let syncTarget;
|
|
957
998
|
// A forwarded synchronous delivery still owes its automatic receipt after the HTTP waiter expires.
|
|
958
|
-
const syncSteered = req.headers['x-a2a-guard'] === undefined || parseReceipt(message) !== null ? undefined : (target, floor) => {
|
|
999
|
+
const syncSteered = req.headers['x-a2a-guard'] === undefined || parseReceipt(message) !== null ? undefined : (target, floor, acceptance) => {
|
|
959
1000
|
syncTarget = sessionTeamOf(target);
|
|
960
1001
|
const receiptTarget = callback !== '' ? callback : caller;
|
|
961
1002
|
const auth = buildAuthorization(admission, { caller, proof: callerProof, ...(claim.ok ? { claim: { caller: claim.caller, origin: originOf(claim.callerUrl) } } : {}), ...(admission.rule === 'remote-ref-cli' && claim.ok ? { carrierUrl: originOf(claim.callerUrl) } : {}), ingress: 'wire', allowlistVersion: admittedAt.version, target: team, receiptTarget, receivedAt: admittedAt.at });
|
|
962
1003
|
try {
|
|
963
|
-
taskLedger.trackInbound(taskId, team, receiptTarget, contextId, receiptExpectationOf(receiptTarget) !== 'process-label', briefOf(message), auth, syncTarget === team ? undefined : syncTarget, String(target.id), taskLedger.deliveryFor(taskId)?.state === 'claimed');
|
|
1004
|
+
taskLedger.trackInbound(taskId, team, receiptTarget, contextId, receiptExpectationOf(receiptTarget) !== 'process-label', briefOf(message), auth, syncTarget === team ? undefined : syncTarget, String(target.id), acceptance === 'inserted' ? false : taskLedger.deliveryFor(taskId)?.state === 'claimed');
|
|
964
1005
|
}
|
|
965
1006
|
catch (error) {
|
|
966
1007
|
taskLedger.noteAdmittedBookkeepingFailure(error);
|
|
967
1008
|
throw new AdmittedBookkeepingError(error);
|
|
968
1009
|
}
|
|
969
|
-
|
|
1010
|
+
if (acceptance !== 'inserted')
|
|
1011
|
+
armReceiptAutosend(target, taskId, receiptTarget, message, floor);
|
|
970
1012
|
};
|
|
971
1013
|
await routeIntoAgent(team, message, caller, taskId, proofClause, directHeader, undefined, syncSteered, claim.ok ? claim.card.publicKey : undefined).then(async (outcome) => {
|
|
972
1014
|
if (outcome.ok && outcome.receiverBookkeeping === 'failed') {
|
|
@@ -989,10 +1031,10 @@ export function registerWireFaces(webServer, d) {
|
|
|
989
1031
|
// settle a node on placeholder text (the exact hazard W7 gap B
|
|
990
1032
|
// closed, barred from resurrecting through the outcome ledger).
|
|
991
1033
|
if (taskId !== '') {
|
|
992
|
-
if (!outcome.ok) {
|
|
1034
|
+
if (!outcome.ok && outcome.acceptance !== 'unknown') {
|
|
993
1035
|
idempotencyStore.recordOutcome(taskId, { status: 'failed', error: outcome.error });
|
|
994
1036
|
}
|
|
995
|
-
else if (outcome.placeholder === true) {
|
|
1037
|
+
else if (!outcome.ok || outcome.placeholder === true) {
|
|
996
1038
|
// placeholder prose never enters the ledger
|
|
997
1039
|
}
|
|
998
1040
|
else if (outcome.status === undefined || outcome.status === 'TASK_STATE_COMPLETED') {
|
|
@@ -1004,22 +1046,19 @@ export function registerWireFaces(webServer, d) {
|
|
|
1004
1046
|
routed: true,
|
|
1005
1047
|
team,
|
|
1006
1048
|
session,
|
|
1049
|
+
...(outcome.acceptance === 'inserted' ? { acceptance: 'inserted', delivered: true, note: ACCEPTANCE_INSERTED_NOTE, consumed: false } : {}),
|
|
1007
1050
|
result: { text: outcome.reply },
|
|
1008
1051
|
...(syncTarget !== undefined ? { delivered_to: syncTarget } : {}),
|
|
1009
1052
|
// #298: a positive, cross-host statement that this text is the member's own final reply — the turn
|
|
1010
|
-
// that read this task's steer (`ownTurn`), never a placeholder
|
|
1011
|
-
...(outcome.ownTurn === true && outcome.placeholder !== true &&
|
|
1053
|
+
// that read this task's steer (`ownTurn`), never a placeholder or another turn (#305 F3/F4).
|
|
1054
|
+
...(outcome.ownTurn === true && outcome.placeholder !== true && (outcome.status ?? 'TASK_STATE_COMPLETED') === 'TASK_STATE_COMPLETED' ? { reply_final: true } : {}),
|
|
1012
1055
|
task_id: taskId,
|
|
1013
1056
|
context_id: contextId,
|
|
1014
|
-
task_status: outcome.status ?? 'TASK_STATE_COMPLETED',
|
|
1057
|
+
task_status: outcome.placeholder === true || (outcome.ownTurn !== true && outcome.status === undefined) ? 'TASK_STATE_DELIVERED' : outcome.status ?? 'TASK_STATE_COMPLETED',
|
|
1058
|
+
...(outcome.placeholder === true || outcome.ownTurn !== true ? { receipt: syncTarget === undefined ? 'none' : 'routed' } : {}),
|
|
1015
1059
|
artifacts: [],
|
|
1016
|
-
// The bridge marker rides the wire so the caller's
|
|
1017
|
-
// trackOwedTask skips a receipt-less native round — without
|
|
1018
|
-
// it, a cross-node unsettled round books an unpayable owed
|
|
1019
|
-
// row and re-creates the TASK_CAP backlog.
|
|
1020
|
-
...(outcome.bridge !== undefined ? { bridge: outcome.bridge } : {}),
|
|
1021
1060
|
})
|
|
1022
|
-
: JSON.stringify({ error: outcome.error, code: -32000, team, task_id: taskId, task_status: 'TASK_STATE_FAILED' });
|
|
1061
|
+
: JSON.stringify({ ...(outcome.acceptance === 'unknown' ? { acceptance: 'unknown' } : {}), error: outcome.error, code: -32000, team, task_id: taskId, task_status: 'TASK_STATE_FAILED' });
|
|
1023
1062
|
res.writeHead(200, { 'Content-Type': 'application/json', 'Content-Length': Buffer.byteLength(payload) });
|
|
1024
1063
|
res.end(payload);
|
|
1025
1064
|
});
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
export const ACCEPTANCE_UNKNOWN_NOTE = '接纳状态未知,请用原 task id 对账,不要换 id 重派';
|
|
2
|
+
export const ACCEPTANCE_INSERTED_NOTE = '已送达、后续处理未确认,请按原 task id 对账,不要重派';
|
|
3
|
+
export class FollowupAcceptanceUnknown extends Error {
|
|
4
|
+
constructor() { super(ACCEPTANCE_UNKNOWN_NOTE); }
|
|
5
|
+
}
|
|
6
|
+
/** A read failure leaves the event floor unknown, never implicitly zero. */
|
|
7
|
+
export function hostEventCount(agent) {
|
|
8
|
+
try {
|
|
9
|
+
const session = agent.session;
|
|
10
|
+
return (session?.snapshotEvents?.() ?? session?.events ?? []).length;
|
|
11
|
+
}
|
|
12
|
+
catch {
|
|
13
|
+
return undefined;
|
|
14
|
+
}
|
|
15
|
+
}
|
|
16
|
+
/** Only a host occurrence in the exact target session can establish acceptance. */
|
|
17
|
+
export function hostInserted(agent, sessionId, messageId, eventFloor) {
|
|
18
|
+
const host = agent;
|
|
19
|
+
try {
|
|
20
|
+
if (String(host.id) !== sessionId || String(host.session?.id) !== sessionId)
|
|
21
|
+
return false;
|
|
22
|
+
}
|
|
23
|
+
catch {
|
|
24
|
+
return false;
|
|
25
|
+
}
|
|
26
|
+
try {
|
|
27
|
+
if ([...(host.inbox?.nextTurn ?? []), ...(host.inbox?.nextStep ?? [])].some(message => message.id === messageId))
|
|
28
|
+
return true;
|
|
29
|
+
}
|
|
30
|
+
catch { /* Accepted event history can still prove insertion after an inbox accessor fails. */ }
|
|
31
|
+
if (eventFloor === undefined)
|
|
32
|
+
return false;
|
|
33
|
+
try {
|
|
34
|
+
const events = host.session?.snapshotEvents?.() ?? host.session?.events ?? [];
|
|
35
|
+
return events.slice(eventFloor).some(event => event.type === 'agent/inbox/spliced' && event.data?.inserted?.some(message => message.id === messageId)
|
|
36
|
+
|| event.type === 'agent/inbox/claimed' && event.data?.message?.id === messageId
|
|
37
|
+
|| event.type === 'user/message' && event.data?.id === messageId);
|
|
38
|
+
}
|
|
39
|
+
catch {
|
|
40
|
+
return false;
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
/** A conflict seen before invoking followup is a definite pre-admission refusal. */
|
|
44
|
+
export function pendingMessage(agent, messageId) {
|
|
45
|
+
const inbox = agent.inbox;
|
|
46
|
+
return [...(inbox?.nextTurn ?? []), ...(inbox?.nextStep ?? [])].some(message => message.id === messageId);
|
|
47
|
+
}
|
package/lib/followup-delivery.js
CHANGED
|
@@ -3,6 +3,7 @@ import { MessageId } from '@deepseek-ai/dsh-llm';
|
|
|
3
3
|
import { AdmittedBookkeepingError } from "./admitted-bookkeeping.js";
|
|
4
4
|
import { deliveryFingerprint } from "./task-delivery.js";
|
|
5
5
|
import { createHash } from 'node:crypto';
|
|
6
|
+
import { FollowupAcceptanceUnknown, hostInserted, hostEventCount, pendingMessage } from "./followup-admission.js";
|
|
6
7
|
export class FollowupDelivery {
|
|
7
8
|
d;
|
|
8
9
|
constructor(d) {
|
|
@@ -14,6 +15,8 @@ export class FollowupDelivery {
|
|
|
14
15
|
throw Error('A2A requires Agent.followup; target runtime lacks sourced next-turn delivery');
|
|
15
16
|
const sessionId = String(agent.id), fingerprint = deliveryFingerprint(sessionId, text, sender, localFrom);
|
|
16
17
|
const messageId = MessageId('a2a-followup-' + createHash('sha256').update(taskId === undefined ? fingerprint + ':' + Date.now() + ':' + Math.random() : sessionId + ':' + taskId).digest('hex'));
|
|
18
|
+
if (typeof text !== 'string' || [sender, localFrom, taskId, callerKey].some(value => value !== undefined && typeof value !== 'string'))
|
|
19
|
+
throw Error('A2A followup input must contain string fields');
|
|
17
20
|
if (taskId) {
|
|
18
21
|
const existing = this.d.ledger.deliveryFor(taskId);
|
|
19
22
|
if (existing) {
|
|
@@ -22,23 +25,37 @@ export class FollowupDelivery {
|
|
|
22
25
|
if (existing.state === 'cancelled' || existing.state === 'failed')
|
|
23
26
|
throw Error('task delivery correspondence is terminal; no replay');
|
|
24
27
|
if (existing.state === 'reserved')
|
|
25
|
-
throw
|
|
28
|
+
throw new FollowupAcceptanceUnknown();
|
|
26
29
|
if (this.d.ledger.orphanDelivery(taskId))
|
|
27
30
|
throw new AdmittedBookkeepingError(undefined);
|
|
28
31
|
return;
|
|
29
32
|
}
|
|
33
|
+
if (pendingMessage(agent, String(messageId)))
|
|
34
|
+
throw Error('message is already pending');
|
|
30
35
|
this.d.ledger.reserveDelivery({ version: 1, taskId, messageId, sessionId, fingerprint, ...(taskExpected ? { taskExpected: true } : {}), ...(callerKey ? { callerKey } : {}), createdAt: Date.now(), state: 'reserved' });
|
|
31
36
|
}
|
|
32
37
|
const source = { kind: 'a2a-relay', form: 'relay', ...(sender === undefined ? {} : { senderSessionId: sender }), ...(localFrom === undefined ? {} : { localSender: localFrom }), ...(taskId === undefined ? {} : { taskId }) };
|
|
33
38
|
const message = { id: messageId, role: 'user', content: [{ type: 'text', text }], source };
|
|
34
39
|
this.d.taint(agent, localFrom);
|
|
40
|
+
const acceptedSession = agent.session, eventFloor = hostEventCount(agent);
|
|
35
41
|
try {
|
|
36
42
|
agent.followup(message);
|
|
37
43
|
}
|
|
38
44
|
catch (error) {
|
|
39
45
|
// The host may throw after durable insertion; preserve reserved/unknown, never blind replay.
|
|
40
46
|
this.d.warn('FOLLOWUP_ADMISSION_FAILED');
|
|
41
|
-
|
|
47
|
+
const reserved = taskId ? this.d.ledger.deliveryFor(taskId) : undefined;
|
|
48
|
+
if (agent.session === acceptedSession && reserved?.sessionId === sessionId && reserved.messageId === String(messageId) && hostInserted(agent, reserved.sessionId, reserved.messageId, eventFloor)) {
|
|
49
|
+
try {
|
|
50
|
+
if (reserved.state === 'reserved')
|
|
51
|
+
this.d.ledger.updateDelivery(taskId, 'enqueued');
|
|
52
|
+
}
|
|
53
|
+
catch {
|
|
54
|
+
this.d.warn('FOLLOWUP_ACCEPTED_COMMIT_FAILED');
|
|
55
|
+
}
|
|
56
|
+
return 'inserted';
|
|
57
|
+
}
|
|
58
|
+
throw new FollowupAcceptanceUnknown();
|
|
42
59
|
}
|
|
43
60
|
if (taskId)
|
|
44
61
|
try {
|