@cogitator-ai/bridge 0.4.0 → 0.6.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +87 -35
- package/dist/adapter.d.ts +34 -2
- package/dist/adapter.d.ts.map +1 -1
- package/dist/adapters/claude.d.ts +95 -2
- package/dist/adapters/claude.d.ts.map +1 -1
- package/dist/adapters/claude.js +207 -3
- package/dist/adapters/claude.js.map +1 -1
- package/dist/adapters/hosted.d.ts +38 -5
- package/dist/adapters/hosted.d.ts.map +1 -1
- package/dist/adapters/hosted.js +190 -10
- package/dist/adapters/hosted.js.map +1 -1
- package/dist/client.d.ts +26 -1
- package/dist/client.d.ts.map +1 -1
- package/dist/client.js +38 -1
- package/dist/client.js.map +1 -1
- package/dist/dispatcher.d.ts +145 -3
- package/dist/dispatcher.d.ts.map +1 -1
- package/dist/dispatcher.js +602 -24
- package/dist/dispatcher.js.map +1 -1
- package/dist/errors.d.ts +1 -1
- package/dist/errors.d.ts.map +1 -1
- package/dist/errors.js.map +1 -1
- package/dist/guards.d.ts +3 -2
- package/dist/guards.d.ts.map +1 -1
- package/dist/guards.js +4 -3
- package/dist/guards.js.map +1 -1
- package/dist/host.d.ts +9 -0
- package/dist/host.d.ts.map +1 -1
- package/dist/host.js +2 -0
- package/dist/host.js.map +1 -1
- package/dist/index.d.ts +16 -8
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +8 -4
- package/dist/index.js.map +1 -1
- package/dist/inputs.d.ts +100 -1
- package/dist/inputs.d.ts.map +1 -1
- package/dist/inputs.js +35 -1
- package/dist/inputs.js.map +1 -1
- package/dist/job-record.d.ts +1 -0
- package/dist/job-record.d.ts.map +1 -1
- package/dist/job-record.js +1 -0
- package/dist/job-record.js.map +1 -1
- package/dist/letters.d.ts.map +1 -1
- package/dist/letters.js +23 -1
- package/dist/letters.js.map +1 -1
- package/dist/permit.d.ts +43 -0
- package/dist/permit.d.ts.map +1 -0
- package/dist/permit.js +118 -0
- package/dist/permit.js.map +1 -0
- package/dist/person-channel.d.ts +45 -0
- package/dist/person-channel.d.ts.map +1 -0
- package/dist/person-channel.js +160 -0
- package/dist/person-channel.js.map +1 -0
- package/dist/person-inbox.d.ts +31 -0
- package/dist/person-inbox.d.ts.map +1 -0
- package/dist/person-inbox.js +69 -0
- package/dist/person-inbox.js.map +1 -0
- package/dist/person.d.ts +65 -0
- package/dist/person.d.ts.map +1 -0
- package/dist/person.js +31 -0
- package/dist/person.js.map +1 -0
- package/dist/protocol.d.ts +8 -1
- package/dist/protocol.d.ts.map +1 -1
- package/dist/protocol.js +7 -1
- package/dist/protocol.js.map +1 -1
- package/dist/rights/index.d.ts +36 -0
- package/dist/rights/index.d.ts.map +1 -0
- package/dist/rights/index.js +186 -0
- package/dist/rights/index.js.map +1 -0
- package/dist/server.d.ts.map +1 -1
- package/dist/server.js +11 -0
- package/dist/server.js.map +1 -1
- package/dist/setup/claude.d.ts +4 -2
- package/dist/setup/claude.d.ts.map +1 -1
- package/dist/setup/claude.js +9 -3
- package/dist/setup/claude.js.map +1 -1
- package/dist/store/sqlite.d.ts +6 -1
- package/dist/store/sqlite.d.ts.map +1 -1
- package/dist/store/sqlite.js +74 -18
- package/dist/store/sqlite.js.map +1 -1
- package/dist/store/store.d.ts +6 -2
- package/dist/store/store.d.ts.map +1 -1
- package/dist/testing/fake-harnesses.d.ts +15 -2
- package/dist/testing/fake-harnesses.d.ts.map +1 -1
- package/dist/testing/fake-harnesses.js +17 -2
- package/dist/testing/fake-harnesses.js.map +1 -1
- package/dist/tools/guidance.d.ts.map +1 -1
- package/dist/tools/guidance.js +1 -0
- package/dist/tools/guidance.js.map +1 -1
- package/dist/tools/tools.d.ts.map +1 -1
- package/dist/tools/tools.js +27 -4
- package/dist/tools/tools.js.map +1 -1
- package/dist/types.d.ts +87 -1
- package/dist/types.d.ts.map +1 -1
- package/dist/types.js +31 -0
- package/dist/types.js.map +1 -1
- package/fakes/claude.mjs +175 -8
- package/fakes/lib.mjs +58 -7
- package/fakes/mcp.mjs +5 -1
- package/package.json +6 -1
package/dist/dispatcher.js
CHANGED
|
@@ -3,12 +3,12 @@ import { isAbsolute, resolve as resolvePath } from 'node:path';
|
|
|
3
3
|
import { TaskManager, textPart, toMessage } from '@cogitator-ai/a2a';
|
|
4
4
|
import { BridgeError } from './errors.js';
|
|
5
5
|
import { deliveryBackoff, exhaustedBudget, formatDuration, nextDepth, resolveBudget, resolveLimits, } from './guards.js';
|
|
6
|
-
import { AgentsFilterSchema, CreateJobInputSchema, DEFAULT_INBOX_LIMIT, DEFAULT_LIST_LIMIT, DEFAULT_WAIT_MS, DeliveredInputSchema, InboxInputSchema, JobsFilterSchema, JournalQuerySchema, LettersFilterSchema, SendLetterInputSchema, VerificationInputSchema, WaitInputSchema, } from './inputs.js';
|
|
6
|
+
import { AgentsFilterSchema, CreateJobInputSchema, DEFAULT_INBOX_LIMIT, DEFAULT_LIST_LIMIT, DEFAULT_VERDICT_WAIT_MS, DEFAULT_WAIT_MS, DeliveredInputSchema, EscalateInputSchema, InboxInputSchema, JobsFilterSchema, JournalQuerySchema, LettersFilterSchema, PersonAnswerInputSchema, SendLetterInputSchema, StuckInputSchema, VerdictInputSchema, VerificationInputSchema, WaitInputSchema, WithdrawInputSchema, } from './inputs.js';
|
|
7
7
|
import { isFinishedJobState, jobOf, jobRecordOf } from './job-record.js';
|
|
8
8
|
import { expectationOf, forHistory, newLetterId, normalizeBody, oneLine, quoted, renderLetter, repeats, titleOf, } from './letters.js';
|
|
9
9
|
import { canonicalPath, findCheckoutRoot, findProjectRoot, isInside } from './paths.js';
|
|
10
10
|
import { allocateAgentName, resolveAddress } from './registry.js';
|
|
11
|
-
import { BRIDGE_JOB_KEY, BRIDGE_SENDER, CallerIdentitySchema, DEFAULT_LIMITS, HarnessNameSchema, INBOX_DELIVERY, NO_CAPABILITIES, } from './types.js';
|
|
11
|
+
import { BRIDGE_JOB_KEY, BRIDGE_SENDER, CallerIdentitySchema, DEFAULT_LIMITS, HarnessNameSchema, INBOX_DELIVERY, NO_CAPABILITIES, PERSON, } from './types.js';
|
|
12
12
|
const ACTIVE_JOB_STATES = ['submitted', 'working', 'input-required'];
|
|
13
13
|
const UNREAD_STATES = ['queued', 'delivered'];
|
|
14
14
|
const NEEDS_ANSWER = ['question', 'permission'];
|
|
@@ -110,6 +110,14 @@ export class BridgeDispatcher extends EventEmitter {
|
|
|
110
110
|
letterId;
|
|
111
111
|
onError;
|
|
112
112
|
assertWritable;
|
|
113
|
+
rights;
|
|
114
|
+
person;
|
|
115
|
+
/** When each agent's other parties were last told it waits at its window, see `stuck` */
|
|
116
|
+
stuckTold = new Map();
|
|
117
|
+
/** Those waiting for the verdict of a permission request, by its id, see `verdict` */
|
|
118
|
+
verdictWaiters = new Map();
|
|
119
|
+
/** What the person route is told, one thing after another */
|
|
120
|
+
personNews = Promise.resolve();
|
|
113
121
|
queue = Promise.resolve();
|
|
114
122
|
deliveries = new Map();
|
|
115
123
|
background = new Set();
|
|
@@ -142,6 +150,8 @@ export class BridgeDispatcher extends EventEmitter {
|
|
|
142
150
|
this.letterId = options.newLetterId ?? newLetterId;
|
|
143
151
|
this.onError = options.onError ?? (() => undefined);
|
|
144
152
|
this.assertWritable = options.assertWritable;
|
|
153
|
+
this.rights = options.rights;
|
|
154
|
+
this.person = options.person;
|
|
145
155
|
for (const adapter of options.adapters ?? []) {
|
|
146
156
|
const harness = parse(HarnessNameSchema, adapter.harness, 'Cannot use the adapter');
|
|
147
157
|
if (this.adapters.has(harness)) {
|
|
@@ -151,6 +161,7 @@ export class BridgeDispatcher extends EventEmitter {
|
|
|
151
161
|
}
|
|
152
162
|
for (const adapter of this.adapters.values())
|
|
153
163
|
adapter.attach?.(this);
|
|
164
|
+
this.person?.attach?.(this);
|
|
154
165
|
}
|
|
155
166
|
/**
|
|
156
167
|
* Puts the calling session into the address book, or finds it there. A session is known by
|
|
@@ -176,6 +187,7 @@ export class BridgeDispatcher extends EventEmitter {
|
|
|
176
187
|
cwd,
|
|
177
188
|
project,
|
|
178
189
|
...(caller.sessionName && { sessionName: caller.sessionName }),
|
|
190
|
+
...(caller.permissionMode && { permissionMode: caller.permissionMode }),
|
|
179
191
|
status: 'active',
|
|
180
192
|
lastSeenAt: now,
|
|
181
193
|
};
|
|
@@ -199,6 +211,7 @@ export class BridgeDispatcher extends EventEmitter {
|
|
|
199
211
|
...reach,
|
|
200
212
|
sessionId: caller.sessionId,
|
|
201
213
|
...(caller.sessionName && { sessionName: caller.sessionName }),
|
|
214
|
+
...(caller.permissionMode && { permissionMode: caller.permissionMode }),
|
|
202
215
|
status: 'active',
|
|
203
216
|
lastSeenAt: now,
|
|
204
217
|
};
|
|
@@ -216,6 +229,7 @@ export class BridgeDispatcher extends EventEmitter {
|
|
|
216
229
|
harness: caller.harness,
|
|
217
230
|
sessionId: caller.sessionId,
|
|
218
231
|
...(caller.sessionName && { sessionName: caller.sessionName }),
|
|
232
|
+
...(caller.permissionMode && { permissionMode: caller.permissionMode }),
|
|
219
233
|
project,
|
|
220
234
|
cwd,
|
|
221
235
|
...reach,
|
|
@@ -383,13 +397,20 @@ export class BridgeDispatcher extends EventEmitter {
|
|
|
383
397
|
* Sends a letter on a job to its other party: a question, an answer, a report that ends the
|
|
384
398
|
* job, a note. The call returns once the bridge has the letter, the answer comes as a letter.
|
|
385
399
|
*
|
|
400
|
+
* A permission request that names its call (`ask`) is judged first by the rules of the agent
|
|
401
|
+
* that handed the job over: what they forbid is refused at once, what they allow is that
|
|
402
|
+
* agent's to answer, and the rest waits for the person. So the one carrying a job out never
|
|
403
|
+
* gets leave the one who handed it over does not have. The decision comes through `verdict`.
|
|
404
|
+
*
|
|
386
405
|
* @throws BridgeError `not_registered`, `unknown_job`, `not_a_party`, `job_finished`,
|
|
387
406
|
* `invalid_letter`, `loop_detected` (the same letter twice in a row), `budget_exhausted` (the
|
|
388
|
-
* job ran out of letters or time, and has failed)
|
|
407
|
+
* job ran out of letters or time, and has failed), `needs_person` (an agent allowing what only
|
|
408
|
+
* the person can)
|
|
389
409
|
*/
|
|
390
410
|
async send(caller, input) {
|
|
391
411
|
const request = parse(SendLetterInputSchema, input, 'Cannot send the letter');
|
|
392
412
|
this.checkBody(request.body);
|
|
413
|
+
const rights = request.ask ? await this.rightsFor(request.job, request.ask) : undefined;
|
|
393
414
|
const outcome = await this.asCaller(caller, async (tx) => {
|
|
394
415
|
const from = this.requireCaller(caller);
|
|
395
416
|
if (request.id) {
|
|
@@ -418,7 +439,28 @@ export class BridgeDispatcher extends EventEmitter {
|
|
|
418
439
|
if (request.kind === 'report' && !isAssignee) {
|
|
419
440
|
throw new BridgeError('invalid_letter', `Only ${job.to}, who carries job ${job.number} out, reports on it`);
|
|
420
441
|
}
|
|
442
|
+
if (request.ask && !isAssignee) {
|
|
443
|
+
throw new BridgeError('invalid_letter', `Only ${job.to}, who carries job ${job.number} out, asks leave for a call`);
|
|
444
|
+
}
|
|
421
445
|
const answered = this.answeredLetter(request, job, from.name);
|
|
446
|
+
if (request.kind === 'answer' && answered) {
|
|
447
|
+
if (answered.ask && !request.verdict) {
|
|
448
|
+
throw new BridgeError('invalid_letter', `The permission request ${answered.id} takes a decision: allow or deny`, { letter: answered.id });
|
|
449
|
+
}
|
|
450
|
+
if (!answered.ask && request.verdict) {
|
|
451
|
+
throw new BridgeError('invalid_letter', `The ${answered.kind} ${answered.id} takes an answer in words, not a decision`, { letter: answered.id });
|
|
452
|
+
}
|
|
453
|
+
if (answered.ask && answered.needsPerson && request.verdict === 'allow') {
|
|
454
|
+
const error = new BridgeError('needs_person', `The permission request ${answered.id} is the person's to allow: your own rules would have you ask them too. They were asked. You can refuse it`, { job: job.number, letter: answered.id });
|
|
455
|
+
this.journal(tx, {
|
|
456
|
+
type: 'letter.rejected',
|
|
457
|
+
job: job.number,
|
|
458
|
+
agent: from.name,
|
|
459
|
+
data: { reason: error.code, kind: request.kind, to, inReplyTo: answered.id },
|
|
460
|
+
});
|
|
461
|
+
return new Refusal(error);
|
|
462
|
+
}
|
|
463
|
+
}
|
|
422
464
|
const previous = this.store.listLetters({
|
|
423
465
|
job: job.number,
|
|
424
466
|
from: from.name,
|
|
@@ -426,7 +468,8 @@ export class BridgeDispatcher extends EventEmitter {
|
|
|
426
468
|
newestFirst: true,
|
|
427
469
|
limit: 1,
|
|
428
470
|
})[0];
|
|
429
|
-
if (repeats(previous, request.kind, request.body, answered?.id)
|
|
471
|
+
if (repeats(previous, request.kind, request.body, answered?.id) &&
|
|
472
|
+
!this.wasAllowed(previous)) {
|
|
430
473
|
const error = new BridgeError('loop_detected', `This ${request.kind} says what your last letter on job ${job.number} said, so it was not delivered. Say something new, report or cancel the job`, { job: job.number, previous: previous.id });
|
|
431
474
|
this.journal(tx, {
|
|
432
475
|
type: 'letter.rejected',
|
|
@@ -437,7 +480,8 @@ export class BridgeDispatcher extends EventEmitter {
|
|
|
437
480
|
return new Refusal(error);
|
|
438
481
|
}
|
|
439
482
|
const now = this.now();
|
|
440
|
-
const
|
|
483
|
+
const clockHeld = now >= Date.parse(job.deadlineAt) && this.waitsForPerson(job.number);
|
|
484
|
+
const exhausted = exhaustedBudget(job, now, request.kind, clockHeld);
|
|
441
485
|
if (exhausted) {
|
|
442
486
|
const reason = exhausted === 'letters'
|
|
443
487
|
? `the job used all ${job.budget.letters} letters of its budget`
|
|
@@ -457,6 +501,12 @@ export class BridgeDispatcher extends EventEmitter {
|
|
|
457
501
|
}
|
|
458
502
|
if (isAssignee && job.state === 'submitted')
|
|
459
503
|
await this.pickUp(tx, job);
|
|
504
|
+
const forPerson = rights === 'ask' && this.person !== undefined;
|
|
505
|
+
const refused = rights === 'deny'
|
|
506
|
+
? `The rules of ${job.from} forbid this, so it is refused`
|
|
507
|
+
: rights === 'ask' && !forPerson
|
|
508
|
+
? 'Only the person can allow this, and this bridge has no way to reach them, so it is refused'
|
|
509
|
+
: undefined;
|
|
460
510
|
const letter = this.accept(tx, {
|
|
461
511
|
id: request.id ?? this.letterId(),
|
|
462
512
|
job: job.number,
|
|
@@ -466,41 +516,454 @@ export class BridgeDispatcher extends EventEmitter {
|
|
|
466
516
|
body: request.body,
|
|
467
517
|
...(answered && { inReplyTo: answered.id }),
|
|
468
518
|
...(request.kind === 'report' && { outcome: request.outcome ?? 'completed' }),
|
|
469
|
-
...(
|
|
470
|
-
|
|
519
|
+
...(request.ask && { ask: request.ask }),
|
|
520
|
+
...(request.verdict && { verdict: request.verdict }),
|
|
521
|
+
...(forPerson && { needsPerson: true, personAskedAt: this.iso(now) }),
|
|
522
|
+
...(expectationOf(request.kind) === 'reply' &&
|
|
523
|
+
!refused && {
|
|
524
|
+
replyDueAt: this.iso(now + (forPerson ? this.limits.personReplyTimeoutMs : job.budget.replyTimeoutMs)),
|
|
471
525
|
}),
|
|
472
526
|
});
|
|
473
527
|
await this.patchRecord(job.taskId, { lettersUsed: job.lettersUsed + 1 });
|
|
474
|
-
if (
|
|
528
|
+
if (refused) {
|
|
529
|
+
const settled = this.refuse(tx, letter, refused);
|
|
530
|
+
return { letter: settled, job: this.requireJob(job.number).job, duplicate: false };
|
|
531
|
+
}
|
|
532
|
+
if (forPerson) {
|
|
533
|
+
tx.asked.push({ letter: letter.id, again: false });
|
|
534
|
+
await this.startWaiting(job.number, now);
|
|
535
|
+
}
|
|
536
|
+
if (answered && request.kind === 'answer') {
|
|
475
537
|
this.markHandled(tx, answered);
|
|
538
|
+
if (answered.ask)
|
|
539
|
+
this.markHandled(tx, letter);
|
|
540
|
+
if (answered.needsPerson)
|
|
541
|
+
await this.stopWaiting(job.number, now, false);
|
|
542
|
+
}
|
|
476
543
|
if (request.kind === 'report') {
|
|
477
544
|
const state = letter.outcome === 'failed' ? 'failed' : 'completed';
|
|
478
545
|
await this.transition(tx, job.number, state, forHistory(request.body, letter.id));
|
|
479
546
|
if (state === 'failed')
|
|
480
547
|
await this.patchRecord(job.taskId, { reason: `reported as failed by ${from.name}` });
|
|
481
548
|
this.closeLetters(tx, job.number, letter.id);
|
|
549
|
+
await this.stopWaiting(job.number, now, false);
|
|
482
550
|
await this.cancelChildren(tx, job);
|
|
483
551
|
}
|
|
484
552
|
else if (isAssignee && NEEDS_ANSWER.includes(request.kind)) {
|
|
485
553
|
await this.transition(tx, job.number, 'input-required', forHistory(request.body, letter.id));
|
|
486
554
|
}
|
|
487
555
|
else if (request.kind === 'answer' && !isAssignee) {
|
|
488
|
-
|
|
489
|
-
job: job.number,
|
|
490
|
-
from: job.to,
|
|
491
|
-
kinds: NEEDS_ANSWER,
|
|
492
|
-
states: ['queued', 'delivered', 'read'],
|
|
493
|
-
});
|
|
494
|
-
if (open === 0 && this.requireJob(job.number).job.state === 'input-required') {
|
|
495
|
-
await this.transition(tx, job.number, 'working', forHistory(request.body, letter.id));
|
|
496
|
-
}
|
|
556
|
+
await this.resumeIfAnswered(tx, job, forHistory(request.body, letter.id));
|
|
497
557
|
}
|
|
498
|
-
return {
|
|
558
|
+
return {
|
|
559
|
+
letter: this.store.getLetter(letter.id) ?? letter,
|
|
560
|
+
job: this.requireJob(job.number).job,
|
|
561
|
+
duplicate: false,
|
|
562
|
+
};
|
|
499
563
|
});
|
|
500
564
|
if (outcome instanceof Refusal)
|
|
501
565
|
throw outcome.error;
|
|
502
566
|
return outcome;
|
|
503
567
|
}
|
|
568
|
+
/**
|
|
569
|
+
* Passes a question or a permission request addressed to the caller on to the person: the
|
|
570
|
+
* answer is theirs to give now, and goes to the one who asked. The caller can still answer it
|
|
571
|
+
* itself, except to allow a call its own rules leave to the person. Passing a letter on twice
|
|
572
|
+
* changes nothing.
|
|
573
|
+
*
|
|
574
|
+
* @throws BridgeError `unknown_letter` for a letter that is not addressed to the caller,
|
|
575
|
+
* `invalid_letter` for one that takes no answer or waits no more, `no_person` when the bridge
|
|
576
|
+
* has no way to reach the person
|
|
577
|
+
*/
|
|
578
|
+
async escalate(caller, input) {
|
|
579
|
+
const request = parse(EscalateInputSchema, input, 'Cannot pass the letter on');
|
|
580
|
+
return this.asCaller(caller, async (tx) => {
|
|
581
|
+
const agent = this.requireCaller(caller);
|
|
582
|
+
const letter = request.letter === undefined
|
|
583
|
+
? this.openLetter(request.job ?? 0, agent.name)
|
|
584
|
+
: this.store.getLetter(request.letter);
|
|
585
|
+
if (letter?.to !== agent.name) {
|
|
586
|
+
throw new BridgeError('unknown_letter', `There is no letter ${request.letter} addressed to you`, { letter: request.letter });
|
|
587
|
+
}
|
|
588
|
+
const { job } = this.requireJob(letter.job);
|
|
589
|
+
if (!NEEDS_ANSWER.includes(letter.kind) ||
|
|
590
|
+
letter.state === 'handled' ||
|
|
591
|
+
isFinishedJobState(job.state)) {
|
|
592
|
+
throw new BridgeError('invalid_letter', `The ${letter.kind} ${letter.id} waits for no answer, so there is nothing to pass on`, { letter: letter.id });
|
|
593
|
+
}
|
|
594
|
+
if (letter.needsPerson)
|
|
595
|
+
return letter;
|
|
596
|
+
if (!this.person) {
|
|
597
|
+
throw new BridgeError('no_person', 'This bridge has no way to reach the person. Ask them yourself, in your own window', { letter: letter.id });
|
|
598
|
+
}
|
|
599
|
+
const now = this.now();
|
|
600
|
+
const updated = this.store.updateLetter(letter.id, {
|
|
601
|
+
needsPerson: true,
|
|
602
|
+
personAskedAt: this.iso(now),
|
|
603
|
+
replyDueAt: this.iso(now + this.limits.personReplyTimeoutMs),
|
|
604
|
+
clear: ['remindedAt'],
|
|
605
|
+
});
|
|
606
|
+
this.journal(tx, {
|
|
607
|
+
type: 'letter.escalated',
|
|
608
|
+
job: job.number,
|
|
609
|
+
letter: letter.id,
|
|
610
|
+
agent: agent.name,
|
|
611
|
+
});
|
|
612
|
+
tx.asked.push({ letter: letter.id, again: false });
|
|
613
|
+
await this.startWaiting(job.number, now);
|
|
614
|
+
return updated;
|
|
615
|
+
});
|
|
616
|
+
}
|
|
617
|
+
/**
|
|
618
|
+
* Takes what the person said to a letter that waits for them: `allow` or `deny` for a
|
|
619
|
+
* permission request that names its call, words for anything else. The answer goes to the one
|
|
620
|
+
* who asked, signed `person`. Whoever calls this speaks for the person, so it is not served to
|
|
621
|
+
* agents: a route to the person calls it, see `PersonRoute`.
|
|
622
|
+
*
|
|
623
|
+
* @throws BridgeError `unknown_letter` when no such letter waits for the person,
|
|
624
|
+
* `invalid_letter` when it waits no more or the answer is of the wrong kind
|
|
625
|
+
*/
|
|
626
|
+
async personAnswer(input) {
|
|
627
|
+
const request = parse(PersonAnswerInputSchema, input, "Cannot take the person's answer");
|
|
628
|
+
if (request.body !== undefined)
|
|
629
|
+
this.checkBody(request.body);
|
|
630
|
+
return this.mutate(async (tx) => {
|
|
631
|
+
const target = this.store.getLetter(request.letter);
|
|
632
|
+
if (!target?.needsPerson || !NEEDS_ANSWER.includes(target.kind)) {
|
|
633
|
+
throw new BridgeError('unknown_letter', `No letter ${request.letter} waits for the person`, { letter: request.letter });
|
|
634
|
+
}
|
|
635
|
+
const { job } = this.requireJob(target.job);
|
|
636
|
+
if (target.state === 'handled' || isFinishedJobState(job.state)) {
|
|
637
|
+
throw new BridgeError('invalid_letter', `The ${target.kind} ${target.id} waits no more: ${isFinishedJobState(job.state) ? `job #${job.number} is ${job.state}` : this.settledBy(target)}`, { letter: target.id, job: job.number });
|
|
638
|
+
}
|
|
639
|
+
if (target.ask && !request.verdict) {
|
|
640
|
+
throw new BridgeError('invalid_letter', `The permission request ${target.id} takes a decision: allow or deny`, { letter: target.id });
|
|
641
|
+
}
|
|
642
|
+
if (!target.ask && (request.verdict || request.body === undefined)) {
|
|
643
|
+
throw new BridgeError('invalid_letter', `The ${target.kind} ${target.id} takes an answer in words`, { letter: target.id });
|
|
644
|
+
}
|
|
645
|
+
const body = request.body ??
|
|
646
|
+
(request.verdict === 'allow' ? 'Allowed by the person' : 'Refused by the person');
|
|
647
|
+
const letter = this.accept(tx, {
|
|
648
|
+
id: this.letterId(),
|
|
649
|
+
job: job.number,
|
|
650
|
+
kind: 'answer',
|
|
651
|
+
from: PERSON,
|
|
652
|
+
to: target.from,
|
|
653
|
+
body,
|
|
654
|
+
inReplyTo: target.id,
|
|
655
|
+
...(request.verdict && { verdict: request.verdict }),
|
|
656
|
+
});
|
|
657
|
+
this.markHandled(tx, target);
|
|
658
|
+
const sent = target.ask ? this.markHandled(tx, letter) : letter;
|
|
659
|
+
await this.stopWaiting(job.number, this.now(), true);
|
|
660
|
+
await this.resumeIfAnswered(tx, job, forHistory(body, letter.id));
|
|
661
|
+
return { letter: sent, job: this.requireJob(job.number).job, duplicate: false };
|
|
662
|
+
});
|
|
663
|
+
}
|
|
664
|
+
/**
|
|
665
|
+
* Says the caller's session waits for a person at its own window, such as for the answer to
|
|
666
|
+
* its harness's permission dialog: something only a person there can give. Whoever handed it
|
|
667
|
+
* a job that still runs is told in a note, and the person through their route, so nobody
|
|
668
|
+
* waits for an agent that itself waits. Told once in `limits.windowNoticeMs` for an agent,
|
|
669
|
+
* however often its harness says so. Resolves with the jobs whose other party was told.
|
|
670
|
+
*/
|
|
671
|
+
async stuck(caller, input) {
|
|
672
|
+
const request = parse(StuckInputSchema, input, 'Cannot note that the session waits');
|
|
673
|
+
return this.asCaller(caller, async (tx) => this.noteStuck(tx, this.requireCaller(caller), request.what));
|
|
674
|
+
}
|
|
675
|
+
noteStuck(tx, agent, what) {
|
|
676
|
+
const now = this.now();
|
|
677
|
+
const told = this.stuckTold.get(agent.name);
|
|
678
|
+
if (told !== undefined && now - told < this.limits.windowNoticeMs)
|
|
679
|
+
return [];
|
|
680
|
+
const jobs = this.store
|
|
681
|
+
.jobTasks({ to: agent.name, states: ACTIVE_JOB_STATES })
|
|
682
|
+
.flatMap((task) => jobOf(task) ?? [])
|
|
683
|
+
.filter((job) => !this.holdsCall(agent.name, job.number))
|
|
684
|
+
.sort((a, b) => a.number - b.number);
|
|
685
|
+
if (jobs.length === 0)
|
|
686
|
+
return [];
|
|
687
|
+
this.stuckTold.set(agent.name, now);
|
|
688
|
+
for (const job of jobs) {
|
|
689
|
+
this.systemNote(tx, job, job.from, `${agent.name} waits for a person at its own window, and job #${job.number} stands still until they answer there. It shows:\n${quoted(what)}\nNobody can answer that from here. If the user is with you, tell them in one line.`);
|
|
690
|
+
}
|
|
691
|
+
tx.notices.push({
|
|
692
|
+
agent: agent.name,
|
|
693
|
+
jobs,
|
|
694
|
+
text: `${agent.name} waits for you at its own window: ${oneLine(what)}`,
|
|
695
|
+
});
|
|
696
|
+
return jobs.map((job) => job.number);
|
|
697
|
+
}
|
|
698
|
+
/** How a letter that waits no more was settled, for whoever answers it too late. */
|
|
699
|
+
settledBy(letter) {
|
|
700
|
+
const [answer] = this.store.listLetters({
|
|
701
|
+
inReplyTo: letter.id,
|
|
702
|
+
kinds: ['answer'],
|
|
703
|
+
newestFirst: true,
|
|
704
|
+
limit: 1,
|
|
705
|
+
});
|
|
706
|
+
return answer?.from === BRIDGE_SENDER ? answer.body : 'it is answered';
|
|
707
|
+
}
|
|
708
|
+
/**
|
|
709
|
+
* Whether the agent holds a call of the job for a verdict it asked through the bridge. Its
|
|
710
|
+
* harness may say all the while that the session waits for a permission (Claude Code does, a
|
|
711
|
+
* few seconds into the hook that asks leave), but that wait is answered through the bridge,
|
|
712
|
+
* not at a window.
|
|
713
|
+
*/
|
|
714
|
+
holdsCall(agent, job) {
|
|
715
|
+
return this.store
|
|
716
|
+
.listLetters({
|
|
717
|
+
job,
|
|
718
|
+
from: agent,
|
|
719
|
+
kinds: ['permission'],
|
|
720
|
+
states: ['queued', 'delivered', 'read'],
|
|
721
|
+
})
|
|
722
|
+
.some((letter) => letter.ask !== undefined);
|
|
723
|
+
}
|
|
724
|
+
/** The letters that wait for the person, oldest first, each with its job and the text to show. */
|
|
725
|
+
async forPerson() {
|
|
726
|
+
return this.enqueue(async () => this.store
|
|
727
|
+
.listLetters({ needsPerson: true, states: ['queued', 'delivered', 'read'] })
|
|
728
|
+
.map((letter) => {
|
|
729
|
+
const { job } = this.requireJob(letter.job);
|
|
730
|
+
return { letter: renderLetter(letter, job), job };
|
|
731
|
+
}));
|
|
732
|
+
}
|
|
733
|
+
/**
|
|
734
|
+
* Whether a permission request the caller sent is decided. Answers at once when it is,
|
|
735
|
+
* otherwise as soon as it is, or with `waiting` when `timeoutMs` passes: the caller asks
|
|
736
|
+
* again. A request whose job ended before anybody answered counts as refused.
|
|
737
|
+
*
|
|
738
|
+
* @throws BridgeError `unknown_letter` for anything but a permission request of the caller
|
|
739
|
+
* that names its call
|
|
740
|
+
*/
|
|
741
|
+
async verdict(caller, input, signal) {
|
|
742
|
+
const request = parse(VerdictInputSchema, input, 'Cannot look the verdict up');
|
|
743
|
+
const timeoutMs = request.timeoutMs ?? DEFAULT_VERDICT_WAIT_MS;
|
|
744
|
+
const first = await this.asCaller(caller, async () => {
|
|
745
|
+
const agent = this.requireCaller(caller);
|
|
746
|
+
const letter = this.store.getLetter(request.letter);
|
|
747
|
+
if (letter?.from !== agent.name || letter.kind !== 'permission' || !letter.ask) {
|
|
748
|
+
throw new BridgeError('unknown_letter', `You sent no permission request ${request.letter} that names its call`, { letter: request.letter });
|
|
749
|
+
}
|
|
750
|
+
const decision = this.decisionOf(letter);
|
|
751
|
+
if (decision.state === 'decided' || timeoutMs === 0 || signal?.aborted || this.closing) {
|
|
752
|
+
return decision;
|
|
753
|
+
}
|
|
754
|
+
return { later: this.untilDecided(letter.id, timeoutMs, signal) };
|
|
755
|
+
});
|
|
756
|
+
if (!('later' in first))
|
|
757
|
+
return first;
|
|
758
|
+
await first.later;
|
|
759
|
+
if (this.closed)
|
|
760
|
+
return { state: 'waiting' };
|
|
761
|
+
return this.enqueue(async () => {
|
|
762
|
+
const letter = this.store.getLetter(request.letter);
|
|
763
|
+
return letter ? this.decisionOf(letter) : { state: 'waiting' };
|
|
764
|
+
});
|
|
765
|
+
}
|
|
766
|
+
/**
|
|
767
|
+
* Takes back a permission request the caller sent and holds its call for no more, such as when
|
|
768
|
+
* the hook that waited for the verdict gave up and left the call to its harness. The request
|
|
769
|
+
* is done with as refused in the bridge's name: nobody is asked to decide it any more, an
|
|
770
|
+
* answer that comes late is refused instead of looking as if it let the call through, and a
|
|
771
|
+
* job that waited only for it works again. A request that was decided already keeps its
|
|
772
|
+
* decision, and the caller gets it.
|
|
773
|
+
*
|
|
774
|
+
* @throws BridgeError `unknown_letter` for anything but a permission request of the caller
|
|
775
|
+
* that names its call
|
|
776
|
+
*/
|
|
777
|
+
async withdraw(caller, input) {
|
|
778
|
+
const request = parse(WithdrawInputSchema, input, 'Cannot take the request back');
|
|
779
|
+
return this.asCaller(caller, async (tx) => {
|
|
780
|
+
const agent = this.requireCaller(caller);
|
|
781
|
+
const letter = this.store.getLetter(request.letter);
|
|
782
|
+
if (letter?.from !== agent.name || letter.kind !== 'permission' || !letter.ask) {
|
|
783
|
+
throw new BridgeError('unknown_letter', `You sent no permission request ${request.letter} that names its call`, { letter: request.letter });
|
|
784
|
+
}
|
|
785
|
+
const decision = this.decisionOf(letter);
|
|
786
|
+
if (decision.state === 'decided')
|
|
787
|
+
return decision;
|
|
788
|
+
const { job } = this.requireJob(letter.job);
|
|
789
|
+
const reason = `${agent.name} waits for this decision no more`;
|
|
790
|
+
this.refuse(tx, letter, reason);
|
|
791
|
+
if (letter.needsPerson)
|
|
792
|
+
await this.stopWaiting(job.number, this.now(), false);
|
|
793
|
+
await this.resumeIfAnswered(tx, job, forHistory(reason, letter.id));
|
|
794
|
+
return { state: 'withdrawn' };
|
|
795
|
+
});
|
|
796
|
+
}
|
|
797
|
+
decisionOf(letter) {
|
|
798
|
+
if (letter.state !== 'handled')
|
|
799
|
+
return { state: 'waiting' };
|
|
800
|
+
const answer = this.store
|
|
801
|
+
.listLetters({ inReplyTo: letter.id, kinds: ['answer'], newestFirst: true })
|
|
802
|
+
.find((candidate) => candidate.verdict !== undefined);
|
|
803
|
+
if (answer?.verdict) {
|
|
804
|
+
return { state: 'decided', verdict: answer.verdict, reason: answer.body, by: answer.from };
|
|
805
|
+
}
|
|
806
|
+
const { job } = this.requireJob(letter.job);
|
|
807
|
+
return {
|
|
808
|
+
state: 'decided',
|
|
809
|
+
verdict: 'deny',
|
|
810
|
+
reason: `Nobody answered before job #${job.number} was ${job.state}${job.reason ? ` (${job.reason})` : ''}`,
|
|
811
|
+
by: BRIDGE_SENDER,
|
|
812
|
+
};
|
|
813
|
+
}
|
|
814
|
+
/** Resolves when the request gets its verdict, `ms` pass, or `signal` aborts. */
|
|
815
|
+
untilDecided(letterId, ms, signal) {
|
|
816
|
+
return new Promise((resolve) => {
|
|
817
|
+
const waiting = this.verdictWaiters.get(letterId) ?? new Set();
|
|
818
|
+
this.verdictWaiters.set(letterId, waiting);
|
|
819
|
+
const look = () => {
|
|
820
|
+
clearTimeout(timer);
|
|
821
|
+
signal?.removeEventListener('abort', look);
|
|
822
|
+
waiting.delete(look);
|
|
823
|
+
if (waiting.size === 0 && this.verdictWaiters.get(letterId) === waiting) {
|
|
824
|
+
this.verdictWaiters.delete(letterId);
|
|
825
|
+
}
|
|
826
|
+
resolve();
|
|
827
|
+
};
|
|
828
|
+
const timer = setTimeout(look, ms);
|
|
829
|
+
signal?.addEventListener('abort', look, { once: true });
|
|
830
|
+
waiting.add(look);
|
|
831
|
+
});
|
|
832
|
+
}
|
|
833
|
+
/**
|
|
834
|
+
* What the rules of the agent that handed a job over make of a call. A job handed over from
|
|
835
|
+
* inside a job is bound by every agent up the chain: the call is theirs to allow only when it
|
|
836
|
+
* is each one's, and forbidden when any of them may not make it. A judge that throws, and a
|
|
837
|
+
* bridge without one, leave the call to the person: nothing is allowed by accident.
|
|
838
|
+
*/
|
|
839
|
+
async rightsFor(number, ask) {
|
|
840
|
+
if (!this.rights)
|
|
841
|
+
return 'ask';
|
|
842
|
+
let rights = 'allow';
|
|
843
|
+
try {
|
|
844
|
+
for (let at = number; at !== undefined;) {
|
|
845
|
+
const job = this.jobIfAny(at);
|
|
846
|
+
if (!job)
|
|
847
|
+
return 'ask';
|
|
848
|
+
const said = await this.rights({ job, delegator: this.store.getAgent(job.from), ask });
|
|
849
|
+
if (said === 'deny')
|
|
850
|
+
return 'deny';
|
|
851
|
+
if (said === 'ask')
|
|
852
|
+
rights = 'ask';
|
|
853
|
+
at = job.parent;
|
|
854
|
+
}
|
|
855
|
+
}
|
|
856
|
+
catch (error) {
|
|
857
|
+
this.onError(asError(error));
|
|
858
|
+
return 'ask';
|
|
859
|
+
}
|
|
860
|
+
return rights;
|
|
861
|
+
}
|
|
862
|
+
jobIfAny(number) {
|
|
863
|
+
const task = this.store.taskOfJob(number);
|
|
864
|
+
return task && jobOf(task) ? this.requireJob(number).job : undefined;
|
|
865
|
+
}
|
|
866
|
+
/** Whether a permission request was answered with `allow`: the same call may be asked for again. */
|
|
867
|
+
wasAllowed(letter) {
|
|
868
|
+
if (letter?.kind !== 'permission' || !letter.ask)
|
|
869
|
+
return false;
|
|
870
|
+
const decision = this.decisionOf(letter);
|
|
871
|
+
return decision.state === 'decided' && decision.verdict === 'allow';
|
|
872
|
+
}
|
|
873
|
+
/**
|
|
874
|
+
* Refuses a permission request on the spot, in the bridge's own name: the request is done
|
|
875
|
+
* with, and its sender finds the refusal through `verdict`.
|
|
876
|
+
*/
|
|
877
|
+
refuse(tx, request, reason) {
|
|
878
|
+
const settled = this.markHandled(tx, request);
|
|
879
|
+
const answer = this.accept(tx, {
|
|
880
|
+
id: this.letterId(),
|
|
881
|
+
job: request.job,
|
|
882
|
+
kind: 'answer',
|
|
883
|
+
from: BRIDGE_SENDER,
|
|
884
|
+
to: request.from,
|
|
885
|
+
body: reason,
|
|
886
|
+
inReplyTo: request.id,
|
|
887
|
+
verdict: 'deny',
|
|
888
|
+
});
|
|
889
|
+
this.markHandled(tx, answer);
|
|
890
|
+
return settled;
|
|
891
|
+
}
|
|
892
|
+
/**
|
|
893
|
+
* Whether a job waits for the person right now: a letter of it does, or a job handed over
|
|
894
|
+
* from inside it waits for them.
|
|
895
|
+
*/
|
|
896
|
+
waitsForPerson(number) {
|
|
897
|
+
const own = this.store.countLetters({
|
|
898
|
+
job: number,
|
|
899
|
+
needsPerson: true,
|
|
900
|
+
states: ['queued', 'delivered', 'read'],
|
|
901
|
+
});
|
|
902
|
+
if (own > 0)
|
|
903
|
+
return true;
|
|
904
|
+
return this.store.jobTasks({ parent: number, states: ACTIVE_JOB_STATES }).some((task) => {
|
|
905
|
+
const child = jobOf(task);
|
|
906
|
+
return child !== undefined && this.waitsForPerson(child.number);
|
|
907
|
+
});
|
|
908
|
+
}
|
|
909
|
+
/** A job and the jobs it was handed over from inside of, the nearest first, while they run. */
|
|
910
|
+
chainOf(number) {
|
|
911
|
+
const chain = [];
|
|
912
|
+
for (let at = number; at !== undefined;) {
|
|
913
|
+
const job = this.jobIfAny(at);
|
|
914
|
+
if (!job)
|
|
915
|
+
break;
|
|
916
|
+
if (!isFinishedJobState(job.state))
|
|
917
|
+
chain.push(job);
|
|
918
|
+
at = job.parent;
|
|
919
|
+
}
|
|
920
|
+
return chain;
|
|
921
|
+
}
|
|
922
|
+
/**
|
|
923
|
+
* Notes that a job began to wait for the person, and with it every job it is part of: none
|
|
924
|
+
* of them is failed by its deadline while the wait lasts.
|
|
925
|
+
*/
|
|
926
|
+
async startWaiting(number, now) {
|
|
927
|
+
for (const job of this.chainOf(number)) {
|
|
928
|
+
if (!job.personWaitSince) {
|
|
929
|
+
await this.patchRecord(job.taskId, { personWaitSince: this.iso(now) });
|
|
930
|
+
}
|
|
931
|
+
}
|
|
932
|
+
}
|
|
933
|
+
/**
|
|
934
|
+
* Settles the wait of a job and of every job it is part of after a letter that waited for the
|
|
935
|
+
* person was dealt with. Time spent waiting for the person is not time the agents worked:
|
|
936
|
+
* when the person answered (`answered`), the deadline moves by as long as the job waited so
|
|
937
|
+
* far. When an agent dealt with the letter itself, or the job ended, nothing is given back, so
|
|
938
|
+
* agents cannot buy a job time by leaving letters to the person and taking them back. A job
|
|
939
|
+
* that still waits for another letter goes on waiting.
|
|
940
|
+
*/
|
|
941
|
+
async stopWaiting(number, now, answered) {
|
|
942
|
+
for (const job of this.chainOf(number)) {
|
|
943
|
+
if (!job.personWaitSince)
|
|
944
|
+
continue;
|
|
945
|
+
const waited = Math.max(0, now - Date.parse(job.personWaitSince));
|
|
946
|
+
const still = this.waitsForPerson(job.number);
|
|
947
|
+
await this.patchRecord(job.taskId, {
|
|
948
|
+
...(answered && { deadlineAt: this.iso(Date.parse(job.deadlineAt) + waited) }),
|
|
949
|
+
personWaitSince: still
|
|
950
|
+
? this.iso(answered ? now : Date.parse(job.personWaitSince))
|
|
951
|
+
: undefined,
|
|
952
|
+
});
|
|
953
|
+
}
|
|
954
|
+
}
|
|
955
|
+
/** Puts a job that waited for an answer back to work once nothing of it waits for one. */
|
|
956
|
+
async resumeIfAnswered(tx, job, said) {
|
|
957
|
+
const open = this.store.countLetters({
|
|
958
|
+
job: job.number,
|
|
959
|
+
from: job.to,
|
|
960
|
+
kinds: NEEDS_ANSWER,
|
|
961
|
+
states: ['queued', 'delivered', 'read'],
|
|
962
|
+
});
|
|
963
|
+
if (open === 0 && this.requireJob(job.number).job.state === 'input-required') {
|
|
964
|
+
await this.transition(tx, job.number, 'working', said);
|
|
965
|
+
}
|
|
966
|
+
}
|
|
504
967
|
/**
|
|
505
968
|
* The letters waiting for the caller, oldest first, each with the text to show. Taking them
|
|
506
969
|
* marks them read, and taking a job's first letter starts the job. One call returns `limit`
|
|
@@ -817,6 +1280,8 @@ export class BridgeDispatcher extends EventEmitter {
|
|
|
817
1280
|
for (const late of overdue) {
|
|
818
1281
|
if (isFinishedJobState(this.requireJob(late.number).job.state))
|
|
819
1282
|
continue;
|
|
1283
|
+
if (this.waitsForPerson(late.number))
|
|
1284
|
+
continue;
|
|
820
1285
|
await this.failJob(tx, late.number, ranOutOfTime(late));
|
|
821
1286
|
failed.push(late.number);
|
|
822
1287
|
}
|
|
@@ -829,6 +1294,27 @@ export class BridgeDispatcher extends EventEmitter {
|
|
|
829
1294
|
this.store.updateLetter(letter.id, { clear: ['replyDueAt'] });
|
|
830
1295
|
continue;
|
|
831
1296
|
}
|
|
1297
|
+
if (fresh.needsPerson) {
|
|
1298
|
+
const patience = this.limits.personReplyTimeoutMs;
|
|
1299
|
+
if (!fresh.remindedAt) {
|
|
1300
|
+
this.store.updateLetter(letter.id, {
|
|
1301
|
+
remindedAt: this.iso(now),
|
|
1302
|
+
replyDueAt: this.iso(now + patience),
|
|
1303
|
+
});
|
|
1304
|
+
tx.asked.push({ letter: letter.id, again: true });
|
|
1305
|
+
this.journal(tx, {
|
|
1306
|
+
type: 'letter.reminded',
|
|
1307
|
+
job: job.number,
|
|
1308
|
+
letter: letter.id,
|
|
1309
|
+
agent: PERSON,
|
|
1310
|
+
});
|
|
1311
|
+
reminded.push(letter.id);
|
|
1312
|
+
continue;
|
|
1313
|
+
}
|
|
1314
|
+
await this.failJob(tx, job.number, `the person did not answer the ${letter.kind} ${letter.id} in ${formatDuration(2 * patience)}`);
|
|
1315
|
+
failed.push(job.number);
|
|
1316
|
+
continue;
|
|
1317
|
+
}
|
|
832
1318
|
const pickup = expectationOf(letter.kind) === 'pickup';
|
|
833
1319
|
if (!fresh.remindedAt) {
|
|
834
1320
|
this.store.updateLetter(letter.id, {
|
|
@@ -883,7 +1369,17 @@ export class BridgeDispatcher extends EventEmitter {
|
|
|
883
1369
|
this.listing.add(harness);
|
|
884
1370
|
const asked = now;
|
|
885
1371
|
this.track(within(adapter.liveSessions(), this.limits.deliveryTimeoutMs, `Listing the ${harness} sessions`)
|
|
886
|
-
.then((sessions) => this.mutate(
|
|
1372
|
+
.then((sessions) => this.mutate(async (tx) => {
|
|
1373
|
+
await this.applyPresence(tx, harness, new Set(sessions.map((session) => session.sessionId)), adapter.ownsSessions === true, asked);
|
|
1374
|
+
for (const session of sessions) {
|
|
1375
|
+
if (!session.waitingFor)
|
|
1376
|
+
continue;
|
|
1377
|
+
const agent = this.store.agentOfSession(harness, session.sessionId);
|
|
1378
|
+
if (agent?.status !== 'active')
|
|
1379
|
+
continue;
|
|
1380
|
+
this.noteStuck(tx, agent, `It waits for: ${session.waitingFor}`);
|
|
1381
|
+
}
|
|
1382
|
+
}))
|
|
887
1383
|
.finally(() => this.listing.delete(harness)));
|
|
888
1384
|
}
|
|
889
1385
|
}
|
|
@@ -977,6 +1473,8 @@ export class BridgeDispatcher extends EventEmitter {
|
|
|
977
1473
|
this.closing = true;
|
|
978
1474
|
for (const waiter of [...this.waiters.values()])
|
|
979
1475
|
waiter.end('closed');
|
|
1476
|
+
for (const letter of [...this.verdictWaiters.keys()])
|
|
1477
|
+
this.announce(letter);
|
|
980
1478
|
await this.idle();
|
|
981
1479
|
await Promise.all([...this.adapters.values()].map(async (adapter) => {
|
|
982
1480
|
try {
|
|
@@ -1017,7 +1515,15 @@ export class BridgeDispatcher extends EventEmitter {
|
|
|
1017
1515
|
});
|
|
1018
1516
|
}
|
|
1019
1517
|
async transact(work) {
|
|
1020
|
-
const tx = {
|
|
1518
|
+
const tx = {
|
|
1519
|
+
entries: [],
|
|
1520
|
+
wake: new Set(),
|
|
1521
|
+
spawns: [],
|
|
1522
|
+
asked: [],
|
|
1523
|
+
settled: [],
|
|
1524
|
+
decided: new Set(),
|
|
1525
|
+
notices: [],
|
|
1526
|
+
};
|
|
1021
1527
|
const result = await this.store.transaction(() => {
|
|
1022
1528
|
this.assertWritable?.();
|
|
1023
1529
|
return work(tx);
|
|
@@ -1036,8 +1542,63 @@ export class BridgeDispatcher extends EventEmitter {
|
|
|
1036
1542
|
}
|
|
1037
1543
|
for (const agent of tx.wake)
|
|
1038
1544
|
this.wake(agent);
|
|
1545
|
+
for (const letter of tx.decided)
|
|
1546
|
+
this.announce(letter);
|
|
1547
|
+
this.tellPerson(tx);
|
|
1039
1548
|
return result;
|
|
1040
1549
|
}
|
|
1550
|
+
/** Lets those who wait for the verdict of a permission request look again. */
|
|
1551
|
+
announce(letterId) {
|
|
1552
|
+
const waiting = this.verdictWaiters.get(letterId);
|
|
1553
|
+
if (!waiting)
|
|
1554
|
+
return;
|
|
1555
|
+
this.verdictWaiters.delete(letterId);
|
|
1556
|
+
for (const look of waiting)
|
|
1557
|
+
look();
|
|
1558
|
+
}
|
|
1559
|
+
/**
|
|
1560
|
+
* Hands the person route what a call changed for it, after the call is stored and in the
|
|
1561
|
+
* order it happened. A route that throws, or takes longer than a delivery may, stops nothing:
|
|
1562
|
+
* the letter still waits in the bridge, and what comes after it is still told.
|
|
1563
|
+
*/
|
|
1564
|
+
tellPerson(tx) {
|
|
1565
|
+
const route = this.person;
|
|
1566
|
+
if (!route || this.closing)
|
|
1567
|
+
return;
|
|
1568
|
+
if (tx.asked.length + tx.settled.length + tx.notices.length === 0)
|
|
1569
|
+
return;
|
|
1570
|
+
const rendered = (id) => {
|
|
1571
|
+
const letter = this.store.getLetter(id);
|
|
1572
|
+
if (!letter)
|
|
1573
|
+
return undefined;
|
|
1574
|
+
const { job } = this.requireJob(letter.job);
|
|
1575
|
+
return { letter: renderLetter(letter, job), job };
|
|
1576
|
+
};
|
|
1577
|
+
const news = [];
|
|
1578
|
+
const settled = new Set(tx.settled);
|
|
1579
|
+
for (const { letter: id, again } of tx.asked) {
|
|
1580
|
+
if (settled.has(id))
|
|
1581
|
+
continue;
|
|
1582
|
+
const found = rendered(id);
|
|
1583
|
+
if (found)
|
|
1584
|
+
news.push(() => route.ask({ ...found, again }));
|
|
1585
|
+
}
|
|
1586
|
+
for (const id of settled) {
|
|
1587
|
+
const found = rendered(id);
|
|
1588
|
+
if (found)
|
|
1589
|
+
news.push(() => route.settle(found));
|
|
1590
|
+
}
|
|
1591
|
+
for (const notice of tx.notices)
|
|
1592
|
+
news.push(() => route.tell?.(notice));
|
|
1593
|
+
for (const tell of news) {
|
|
1594
|
+
this.personNews = this.personNews
|
|
1595
|
+
.then(() => within(Promise.resolve().then(tell), this.limits.deliveryTimeoutMs, 'Telling the person of a letter'))
|
|
1596
|
+
.catch((error) => {
|
|
1597
|
+
this.onError(asError(error));
|
|
1598
|
+
});
|
|
1599
|
+
}
|
|
1600
|
+
this.track(this.personNews);
|
|
1601
|
+
}
|
|
1041
1602
|
journal(tx, entry) {
|
|
1042
1603
|
tx.entries.push(this.store.appendJournal({ at: this.iso(), ...entry }));
|
|
1043
1604
|
}
|
|
@@ -1127,6 +1688,7 @@ export class BridgeDispatcher extends EventEmitter {
|
|
|
1127
1688
|
await this.transition(tx, number, 'failed', reason);
|
|
1128
1689
|
await this.patchRecord(job.taskId, { reason });
|
|
1129
1690
|
this.closeLetters(tx, number);
|
|
1691
|
+
await this.stopWaiting(number, this.now(), false);
|
|
1130
1692
|
const text = `Job #${number} has failed: ${reason}.`;
|
|
1131
1693
|
this.systemNote(tx, job, job.from, text);
|
|
1132
1694
|
this.systemNote(tx, job, job.to, `${text} Stop working on it.`);
|
|
@@ -1139,6 +1701,7 @@ export class BridgeDispatcher extends EventEmitter {
|
|
|
1139
1701
|
await this.transition(tx, number, 'canceled', reason);
|
|
1140
1702
|
await this.patchRecord(job.taskId, { reason });
|
|
1141
1703
|
this.closeLetters(tx, number);
|
|
1704
|
+
await this.stopWaiting(number, this.now(), false);
|
|
1142
1705
|
this.systemNote(tx, job, job.to, note);
|
|
1143
1706
|
await this.cancelChildren(tx, job);
|
|
1144
1707
|
}
|
|
@@ -1226,6 +1789,9 @@ export class BridgeDispatcher extends EventEmitter {
|
|
|
1226
1789
|
body: letter.body,
|
|
1227
1790
|
...(letter.inReplyTo && { inReplyTo: letter.inReplyTo }),
|
|
1228
1791
|
...(letter.outcome && { outcome: letter.outcome }),
|
|
1792
|
+
...(letter.ask && { ask: letter.ask }),
|
|
1793
|
+
...(letter.verdict && { verdict: letter.verdict }),
|
|
1794
|
+
...(letter.needsPerson && { needsPerson: true }),
|
|
1229
1795
|
},
|
|
1230
1796
|
});
|
|
1231
1797
|
tx.wake.add(letter.to);
|
|
@@ -1266,8 +1832,16 @@ export class BridgeDispatcher extends EventEmitter {
|
|
|
1266
1832
|
}
|
|
1267
1833
|
if (request.kind !== 'answer')
|
|
1268
1834
|
return undefined;
|
|
1835
|
+
return this.openLetter(job.number, caller);
|
|
1836
|
+
}
|
|
1837
|
+
/**
|
|
1838
|
+
* The one letter of a job that waits for the caller's answer.
|
|
1839
|
+
*
|
|
1840
|
+
* @throws BridgeError `invalid_letter` when none does, or several do
|
|
1841
|
+
*/
|
|
1842
|
+
openLetter(number, caller) {
|
|
1269
1843
|
const open = this.store.listLetters({
|
|
1270
|
-
job:
|
|
1844
|
+
job: number,
|
|
1271
1845
|
to: caller,
|
|
1272
1846
|
kinds: NEEDS_ANSWER,
|
|
1273
1847
|
states: ['queued', 'delivered', 'read'],
|
|
@@ -1275,11 +1849,11 @@ export class BridgeDispatcher extends EventEmitter {
|
|
|
1275
1849
|
if (open.length === 1)
|
|
1276
1850
|
return open[0];
|
|
1277
1851
|
if (open.length === 0) {
|
|
1278
|
-
throw new BridgeError('invalid_letter', `Nothing on job ${
|
|
1279
|
-
job:
|
|
1852
|
+
throw new BridgeError('invalid_letter', `Nothing on job ${number} waits for your answer. Send a note instead`, {
|
|
1853
|
+
job: number,
|
|
1280
1854
|
});
|
|
1281
1855
|
}
|
|
1282
|
-
throw new BridgeError('invalid_letter', `Several letters on job ${
|
|
1856
|
+
throw new BridgeError('invalid_letter', `Several letters on job ${number} wait for your answer: ${open.map((letter) => letter.id).join(', ')}. Say which one with inReplyTo`, { job: number, letters: open.map((letter) => letter.id) });
|
|
1283
1857
|
}
|
|
1284
1858
|
markRead(tx, letter) {
|
|
1285
1859
|
if (STATE_RANK[letter.state] >= STATE_RANK.read)
|
|
@@ -1310,6 +1884,10 @@ export class BridgeDispatcher extends EventEmitter {
|
|
|
1310
1884
|
letter: letter.id,
|
|
1311
1885
|
agent: letter.to,
|
|
1312
1886
|
});
|
|
1887
|
+
if (letter.needsPerson)
|
|
1888
|
+
tx.settled.push(letter.id);
|
|
1889
|
+
if (letter.kind === 'permission' && letter.ask)
|
|
1890
|
+
tx.decided.add(letter.id);
|
|
1313
1891
|
return updated;
|
|
1314
1892
|
}
|
|
1315
1893
|
/**
|