@capybara-hq/kernel 0.1.0-rc.97 → 0.1.0-rc.99
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/bootstrap.json +17 -17
- package/dist/catalog/git-source.d.ts +5 -0
- package/dist/catalog/git-source.js +9 -5
- package/dist/catalog/marketplace-fetch.d.ts +9 -0
- package/dist/catalog/marketplace-fetch.js +9 -5
- package/dist/catalog/marketplaces.service.d.ts +1 -1
- package/dist/channels/channels.schemas.d.ts +10 -0
- package/dist/channels/channels.schemas.js +7 -0
- package/dist/channels/connections.service.d.ts +7 -0
- package/dist/channels/connections.service.js +4 -0
- package/dist/channels/features.d.ts +18 -1
- package/dist/channels/features.js +22 -0
- package/dist/channels/outbound.d.ts +19 -0
- package/dist/channels/outbound.js +531 -18
- package/dist/channels/phrases.d.ts +10 -0
- package/dist/channels/phrases.js +4 -0
- package/dist/channels/progress.d.ts +75 -0
- package/dist/channels/progress.js +216 -0
- package/dist/conversations/event-log.d.ts +8 -2
- package/dist/conversations/events.d.ts +6 -0
- package/dist/conversations/events.js +7 -1
- package/dist/conversations/prompt-suggestions.js +2 -2
- package/dist/db/kernel-schema.d.ts +16 -0
- package/dist/evals/run-replay.js +2 -2
- package/dist/evals/step-replay.js +2 -2
- package/dist/evals/worker.js +3 -1
- package/dist/extensions/plugin-icons.d.ts +7 -0
- package/dist/extensions/plugin-icons.js +8 -0
- package/dist/models/purposes.js +2 -2
- package/dist/net/safe-fetch.d.ts +22 -4
- package/dist/net/safe-fetch.js +74 -0
- package/dist/platform/file-ref.d.ts +2 -0
- package/dist/platform/file-ref.js +1 -3
- package/dist/platform/ops/channels.ops.js +24 -5
- package/dist/runtime/model-call.d.ts +23 -2
- package/dist/runtime/model-call.js +64 -9
- package/dist/runtime/run-drafts.d.ts +46 -4
- package/dist/runtime/run-drafts.js +110 -9
- package/dist/runtime/run-steps.d.ts +2 -1
- package/dist/runtime/run-steps.js +6 -2
- package/dist/runtime/runtime.module.js +3 -0
- package/dist/runtime/stream.controller.d.ts +7 -5
- package/dist/runtime/stream.controller.js +10 -6
- package/dist/runtime/stream.js +9 -1
- package/dist/runtime/write-base.d.ts +95 -0
- package/dist/runtime/write-base.js +281 -0
- package/dist/runtime/write-base.service.d.ts +68 -0
- package/dist/runtime/write-base.service.js +184 -0
- package/dist/sandbox/kernel-read.d.ts +39 -9
- package/dist/sandbox/kernel-read.js +33 -3
- package/dist/sandbox/operation-authority.d.ts +16 -12
- package/dist/sandbox/operation-authority.js +33 -20
- package/dist/sandbox/operation-intents.d.ts +10 -4
- package/dist/sandbox/operation-intents.js +31 -11
- package/dist/sandbox/sandbox.service.d.ts +30 -7
- package/dist/sandbox/sandbox.service.js +47 -13
- package/dist/tools/builtins/agent.js +4 -0
- package/dist/tools/builtins/image/generate.js +1 -0
- package/dist/tools/builtins/platform.js +4 -3
- package/dist/tools/builtins/sandbox/bash.d.ts +3 -1
- package/dist/tools/builtins/sandbox/bash.js +23 -11
- package/dist/tools/builtins/sandbox/common.d.ts +4 -1
- package/dist/tools/builtins/sandbox/common.js +5 -2
- package/dist/tools/builtins/sandbox/edit.js +1 -0
- package/dist/tools/builtins/sandbox/glob.js +2 -1
- package/dist/tools/builtins/sandbox/grep.js +2 -1
- package/dist/tools/builtins/sandbox/search-command.d.ts +4 -3
- package/dist/tools/builtins/sandbox/search-command.js +11 -3
- package/dist/tools/builtins/sandbox/write.js +1 -0
- package/dist/tools/builtins/send-message.js +1 -0
- package/dist/tools/info.d.ts +21 -2
- package/dist/tools/info.js +55 -12
- package/dist/tools/network-asks.d.ts +23 -0
- package/dist/tools/network-asks.js +24 -5
- package/dist/tools/pipeline.d.ts +3 -1
- package/dist/tools/pipeline.js +76 -12
- package/dist/tools/registry.d.ts +12 -11
- package/dist/tools/registry.js +6 -5
- package/package.json +3 -3
- package/src/migrations/0185_channel_process_display.sql +13 -0
|
@@ -25,14 +25,17 @@ import { ConversationLock, } from "../runtime/conversation-lock.js";
|
|
|
25
25
|
import { ScheduledTasksService } from "../schedules/scheduled-tasks.service.js";
|
|
26
26
|
import { StorageService } from "../storage/storage.service.js";
|
|
27
27
|
import { ApprovalsService } from "../tools/approvals.service.js";
|
|
28
|
+
import { toolInfo } from "../tools/info.js";
|
|
28
29
|
import { QuestionsService } from "../tools/questions.service.js";
|
|
29
30
|
import { ToolRegistry } from "../tools/registry.js";
|
|
30
|
-
import { approvalCard, cardMessage, connectUrl, conversationUrl, personFieldsCard, questionCard, webBase, } from "./cards.js";
|
|
31
|
+
import { approvalCard, callSummary, cardMessage, connectUrl, conversationUrl, personFieldsCard, questionCard, webBase, } from "./cards.js";
|
|
31
32
|
import { ChannelConnections, FILE_CALL_TIMEOUT_MS, } from "./connections.service.js";
|
|
33
|
+
import { processDisplayOf, progressCardMessage } from "./features.js";
|
|
32
34
|
import { FileSlots, fileKind, fileLinkText, fileRootText, planFileDelivery, pluginFileName, readArtifactCapped, } from "./file-delivery.js";
|
|
33
35
|
import { ChannelInbound } from "./inbound.js";
|
|
34
36
|
import { ChannelJobs, INBOUND_JOB, idempotencyKey, RESUME_JOB, } from "./jobs.js";
|
|
35
37
|
import { phrase } from "./phrases.js";
|
|
38
|
+
import { initProgress, progressCard, promotedAnswer, reduceProgress, statusLine, } from "./progress.js";
|
|
36
39
|
import { insertThread } from "./threads.js";
|
|
37
40
|
// The queue, job names, ids and priorities live with the producer (jobs.ts)
|
|
38
41
|
export { CHANNEL_QUEUE_NAME, DELIVER_ATTEMPTS, DELIVER_JOB, DELIVER_PRIORITY, deliverJobId, followUpJobId, INBOUND_ATTEMPTS, INBOUND_JOB, INBOUND_PRIORITY, idempotencyKey, inboundJobId, } from "./jobs.js";
|
|
@@ -59,6 +62,12 @@ export function closingText(prior, how, locale) {
|
|
|
59
62
|
export const DELIVER_LOCK_PREFIX = "capk:channel-deliver:";
|
|
60
63
|
/** 草稿更新的最小间隔(毫秒);渠道声明了更大的 `features.minEditIntervalMs` 时取后者。 */
|
|
61
64
|
export const DRAFT_INTERVAL_MS = 1000;
|
|
65
|
+
/**
|
|
66
|
+
* A channel without edits gets a milestone message (the pinned card's text) at most this often per
|
|
67
|
+
* run (process blocks spec §10.4); measured between the events' log times, so every replica decides
|
|
68
|
+
* the same.
|
|
69
|
+
*/
|
|
70
|
+
export const MILESTONE_INTERVAL_MS = 60_000;
|
|
62
71
|
/** 没有新消息时多久复核一次(是否该结束、是否有待刷新的草稿)。 */
|
|
63
72
|
const IDLE_POLL_MS = 500;
|
|
64
73
|
/** 投递锁丢失 / 被自己上一次(已崩溃的)尝试占着时,任务推迟多久再试。 */
|
|
@@ -409,6 +418,15 @@ let ChannelOutbound = class ChannelOutbound {
|
|
|
409
418
|
fail_seq: null,
|
|
410
419
|
fail_count: 0,
|
|
411
420
|
...(a.draft !== undefined && { draft_message_id: a.draft }),
|
|
421
|
+
...(a.progress !== undefined && {
|
|
422
|
+
progress_message_id: a.progress.messageId,
|
|
423
|
+
progress_run_id: a.progress.runId,
|
|
424
|
+
milestone_at: null,
|
|
425
|
+
progress_reposted: false,
|
|
426
|
+
progress_final: false,
|
|
427
|
+
}),
|
|
428
|
+
...(a.milestoneAt !== undefined && { milestone_at: a.milestoneAt }),
|
|
429
|
+
...(a.progressFinal && { progress_final: true }),
|
|
412
430
|
updated_at: new Date(),
|
|
413
431
|
})
|
|
414
432
|
.where("conversation_id", "=", a.conversationId)
|
|
@@ -529,6 +547,15 @@ ChannelOutbound = __decorate([
|
|
|
529
547
|
__param(14, Inject(StorageService))
|
|
530
548
|
], ChannelOutbound);
|
|
531
549
|
export { ChannelOutbound };
|
|
550
|
+
/** One `bind` card per handoff link, in one message (process blocks spec §6.2). */
|
|
551
|
+
function handoffsMessage(links, locale) {
|
|
552
|
+
const cards = links.map((p) => {
|
|
553
|
+
const text = p.titles?.[locale] ?? p.text;
|
|
554
|
+
return { kind: "bind", text, url: p.url };
|
|
555
|
+
});
|
|
556
|
+
return { text: phrase("handoffs", locale).replace("{n}", String(cards.length)), cards };
|
|
557
|
+
}
|
|
558
|
+
const hasToolCall = (content) => content.some((b) => b.type === "tool_call");
|
|
532
559
|
/** 一次投递任务(本进程持有):订阅、补读、草稿节流。 */
|
|
533
560
|
class Delivery {
|
|
534
561
|
d;
|
|
@@ -564,10 +591,43 @@ class Delivery {
|
|
|
564
591
|
/** 任务开始时连接的 `updated_at`(毫秒)与上次复核连接的时刻。 */
|
|
565
592
|
version = 0;
|
|
566
593
|
checkedAt = 0;
|
|
567
|
-
/**
|
|
594
|
+
/**
|
|
595
|
+
* The platform rejected an edit of the draft for good: it is not edited again, and the final
|
|
596
|
+
* text goes out as a new message (Ruling A22).
|
|
597
|
+
*/
|
|
568
598
|
draftBroken = false;
|
|
569
|
-
/**
|
|
599
|
+
/** Finished steps: deltas arriving later are dropped. */
|
|
570
600
|
finalized = new Set();
|
|
601
|
+
/** How runs show their process here (read at the start of the job). */
|
|
602
|
+
progressKind = "off";
|
|
603
|
+
display = "detailed";
|
|
604
|
+
/**
|
|
605
|
+
* The current run's progress state: a fold of its events (rebuilt from the log at the start of a
|
|
606
|
+
* job, never kept between jobs in memory); its message id and run are in PG.
|
|
607
|
+
*/
|
|
608
|
+
progress;
|
|
609
|
+
progressId = null;
|
|
610
|
+
/** The log time of the run's last milestone message (`milestone_at`), ms. */
|
|
611
|
+
milestoneAt = null;
|
|
612
|
+
/** The pinned text the run's last milestone message carried (rebuilt from the log). */
|
|
613
|
+
milestoneText;
|
|
614
|
+
/** How many of `progress.pending` went out in a merged handoff message already. */
|
|
615
|
+
handoffsSent = 0;
|
|
616
|
+
/** The card changed since its last edit, and when that edit was. */
|
|
617
|
+
progressDirty = false;
|
|
618
|
+
lastProgressAt = 0;
|
|
619
|
+
/** The last edit failed retryably (cleared by a successful one). */
|
|
620
|
+
progressRetry;
|
|
621
|
+
/** The seq of the run's end event (its final edit's idempotency key); undefined while running. */
|
|
622
|
+
progressEndSeq;
|
|
623
|
+
/**
|
|
624
|
+
* The run's card was re-posted after a rejected edit (once per run: in this job, or in an earlier
|
|
625
|
+
* one, `progress_reposted`); a rejection after that stops the edits.
|
|
626
|
+
*/
|
|
627
|
+
progressReposted = false;
|
|
628
|
+
progressBroken = false;
|
|
629
|
+
/** Tool display metadata for the card's step labels, per tool key (this job only). */
|
|
630
|
+
toolInfos = new Map();
|
|
571
631
|
constructor(d, conversationId, lease, stopping) {
|
|
572
632
|
this.d = d;
|
|
573
633
|
this.conversationId = conversationId;
|
|
@@ -594,6 +654,11 @@ class Delivery {
|
|
|
594
654
|
"last_seq",
|
|
595
655
|
"draft_message_id",
|
|
596
656
|
"pending_thread_account_id",
|
|
657
|
+
"progress_message_id",
|
|
658
|
+
"progress_run_id",
|
|
659
|
+
"milestone_at",
|
|
660
|
+
"progress_reposted",
|
|
661
|
+
"progress_final",
|
|
597
662
|
])
|
|
598
663
|
.where("conversation_id", "=", this.conversationId)
|
|
599
664
|
.executeTakeFirst();
|
|
@@ -626,10 +691,10 @@ class Delivery {
|
|
|
626
691
|
}
|
|
627
692
|
if (this.s.row.status !== "active")
|
|
628
693
|
return { kind: "done" };
|
|
629
|
-
const
|
|
630
|
-
if (
|
|
694
|
+
const conn = await this.connectionState();
|
|
695
|
+
if (conn === undefined)
|
|
631
696
|
return { kind: "done" };
|
|
632
|
-
this.version = version;
|
|
697
|
+
this.version = conn.version;
|
|
633
698
|
this.target = row.target;
|
|
634
699
|
this.threadPending = row.pending_thread_account_id !== null;
|
|
635
700
|
this.seen = Number(row.last_seq);
|
|
@@ -637,6 +702,22 @@ class Delivery {
|
|
|
637
702
|
this.draftId = row.draft_message_id;
|
|
638
703
|
this.locale = await conversationLocale(this.d.db, this.s.row.orgId, this.conversationId, this.seen);
|
|
639
704
|
this.base = webBase(this.d.config.get().http.publicUrl);
|
|
705
|
+
const display = processDisplayOf(conn.processDisplay, this.target.chatType);
|
|
706
|
+
// without a web base the card has no link to the full process: today's messages
|
|
707
|
+
this.progressKind =
|
|
708
|
+
display === "off" || this.base === undefined
|
|
709
|
+
? "off"
|
|
710
|
+
: this.s.features.edit
|
|
711
|
+
? "card"
|
|
712
|
+
: "plain";
|
|
713
|
+
if (display !== "off")
|
|
714
|
+
this.display = display;
|
|
715
|
+
if (this.progressKind !== "off" && row.progress_run_id !== null) {
|
|
716
|
+
this.progressId = row.progress_message_id;
|
|
717
|
+
this.milestoneAt = row.milestone_at?.getTime() ?? null;
|
|
718
|
+
this.progressReposted = row.progress_reposted;
|
|
719
|
+
await this.rebuildProgress(row.progress_run_id, row.progress_final);
|
|
720
|
+
}
|
|
640
721
|
return await this.loop();
|
|
641
722
|
}
|
|
642
723
|
catch (err) {
|
|
@@ -718,16 +799,21 @@ class Delivery {
|
|
|
718
799
|
this.seen = seq;
|
|
719
800
|
return true;
|
|
720
801
|
}
|
|
721
|
-
/**
|
|
722
|
-
|
|
802
|
+
/**
|
|
803
|
+
* The connection's `updated_at` (ms) and process display setting, read live; undefined when it
|
|
804
|
+
* is disabled or deleted. A changed setting bumps `updated_at`, so the job hands over (`changed`).
|
|
805
|
+
*/
|
|
806
|
+
async connectionState() {
|
|
723
807
|
const r = await this.d.db
|
|
724
808
|
.selectFrom("channel_connections")
|
|
725
|
-
.select(["status", "updated_at"])
|
|
809
|
+
.select(["status", "updated_at", "process_display"])
|
|
726
810
|
.where("id", "=", this.s.row.id)
|
|
727
811
|
.where("org_id", "=", this.s.row.orgId)
|
|
728
812
|
.where("deleted_at", "is", null)
|
|
729
813
|
.executeTakeFirst();
|
|
730
|
-
return r?.status === "active"
|
|
814
|
+
return r?.status === "active"
|
|
815
|
+
? { version: r.updated_at.getTime(), processDisplay: r.process_display }
|
|
816
|
+
: undefined;
|
|
731
817
|
}
|
|
732
818
|
/**
|
|
733
819
|
* 至多每 {@link IDLE_POLL_MS} 复核一次连接:停用 / 删除 → `done`(不复核、不再投递);改过(轮换凭据等,
|
|
@@ -737,7 +823,7 @@ class Delivery {
|
|
|
737
823
|
if (Date.now() - this.checkedAt < IDLE_POLL_MS)
|
|
738
824
|
return undefined;
|
|
739
825
|
this.checkedAt = Date.now();
|
|
740
|
-
const v = await this.
|
|
826
|
+
const v = (await this.connectionState())?.version;
|
|
741
827
|
if (v === undefined)
|
|
742
828
|
return { kind: "done" };
|
|
743
829
|
if (v !== this.version)
|
|
@@ -774,6 +860,7 @@ class Delivery {
|
|
|
774
860
|
}
|
|
775
861
|
}
|
|
776
862
|
await this.flushDraft();
|
|
863
|
+
await this.flushProgress(false);
|
|
777
864
|
if (await this.waitWake(IDLE_POLL_MS)) {
|
|
778
865
|
lastMessageAt = Date.now();
|
|
779
866
|
continue;
|
|
@@ -785,9 +872,16 @@ class Delivery {
|
|
|
785
872
|
needCatchUp = false;
|
|
786
873
|
if (this.inbox.length > 0)
|
|
787
874
|
continue;
|
|
788
|
-
//
|
|
789
|
-
|
|
875
|
+
// the run waits or ended and the log is read; or caught up with no output for long (later
|
|
876
|
+
// events owe a new job)
|
|
877
|
+
if (quiet || (await this.idle())) {
|
|
878
|
+
// the card's last throttled change is not left for a job that may never come; an edit
|
|
879
|
+
// still failing retryably fails this attempt, and the retry's rebuild edits the card
|
|
880
|
+
await this.flushProgress(true);
|
|
881
|
+
if (this.progressDirty && this.progressRetry !== undefined)
|
|
882
|
+
throw this.progressRetry;
|
|
790
883
|
return { kind: "done", seen: this.seen };
|
|
884
|
+
}
|
|
791
885
|
}
|
|
792
886
|
}
|
|
793
887
|
}
|
|
@@ -848,8 +942,10 @@ class Delivery {
|
|
|
848
942
|
await this.advance(this.seen);
|
|
849
943
|
}
|
|
850
944
|
/**
|
|
851
|
-
*
|
|
852
|
-
*
|
|
945
|
+
* Advances `last_seq` (recording draft / card / progress ids in the same transaction, clearing
|
|
946
|
+
* the failure count), on condition that it still holds the value this delivery wrote last:
|
|
947
|
+
* advanced by someone else (another instance took over after the lock was lost) stops it, so
|
|
948
|
+
* nothing is sent twice.
|
|
853
949
|
*/
|
|
854
950
|
async advance(seq, opts = {}) {
|
|
855
951
|
const advanced = await this.d.writes.advanceIn({
|
|
@@ -857,6 +953,9 @@ class Delivery {
|
|
|
857
953
|
persisted: this.persisted,
|
|
858
954
|
seq,
|
|
859
955
|
...(opts.draft !== undefined && { draft: opts.draft }),
|
|
956
|
+
...(opts.progress !== undefined && { progress: opts.progress }),
|
|
957
|
+
...(opts.milestoneAt !== undefined && { milestoneAt: opts.milestoneAt }),
|
|
958
|
+
...(opts.progressFinal && { progressFinal: opts.progressFinal }),
|
|
860
959
|
...(opts.card && {
|
|
861
960
|
card: { ...opts.card, connectionId: this.s.row.id, target: this.target },
|
|
862
961
|
}),
|
|
@@ -916,6 +1015,8 @@ class Delivery {
|
|
|
916
1015
|
return sent;
|
|
917
1016
|
}
|
|
918
1017
|
async handle(e) {
|
|
1018
|
+
if (this.progressKind !== "off" && (await this.handleProgress(e)))
|
|
1019
|
+
return;
|
|
919
1020
|
switch (e.type) {
|
|
920
1021
|
case "user_message": {
|
|
921
1022
|
// a new message: what follows speaks its author's language (see conversationLocale)
|
|
@@ -1362,7 +1463,8 @@ class Delivery {
|
|
|
1362
1463
|
catch (err) {
|
|
1363
1464
|
if (!editRejected(err))
|
|
1364
1465
|
throw err;
|
|
1365
|
-
//
|
|
1466
|
+
// the draft's edit was rejected (too old to edit, content refused): the whole text goes
|
|
1467
|
+
// out as a new message, not counted as a poison event
|
|
1366
1468
|
this.d.log.warn("channel draft edit rejected; sending the final text as a new message", {
|
|
1367
1469
|
conversationId: this.conversationId,
|
|
1368
1470
|
error: this.redact(errMsg(err)),
|
|
@@ -1375,7 +1477,11 @@ class Delivery {
|
|
|
1375
1477
|
}
|
|
1376
1478
|
await this.advance(seq, { draft: null });
|
|
1377
1479
|
}
|
|
1378
|
-
/**
|
|
1480
|
+
/**
|
|
1481
|
+
* A streamed delta: only text received from the step's start (matching `offset`) accumulates;
|
|
1482
|
+
* deltas are not logged and do not advance the delivery. With a progress card the text is the
|
|
1483
|
+
* card's status line instead of a draft.
|
|
1484
|
+
*/
|
|
1379
1485
|
onDelta(m) {
|
|
1380
1486
|
if (!this.s.features.edit)
|
|
1381
1487
|
return;
|
|
@@ -1385,6 +1491,12 @@ class Delivery {
|
|
|
1385
1491
|
if (m.delta === "step_reset") {
|
|
1386
1492
|
// 该步重试:此前的文本作废,下一次尝试从 offset 0 重新开始
|
|
1387
1493
|
this.streaming = { key, text: "", complete: false };
|
|
1494
|
+
// the card drops the abandoned attempt's status line at its next refresh
|
|
1495
|
+
if (this.progressKind === "card" &&
|
|
1496
|
+
this.progress?.runId === m.runId &&
|
|
1497
|
+
this.progress.endedAt === undefined) {
|
|
1498
|
+
this.progressDirty = true;
|
|
1499
|
+
}
|
|
1388
1500
|
return;
|
|
1389
1501
|
}
|
|
1390
1502
|
if (m.delta !== "text" || m.text === undefined)
|
|
@@ -1401,11 +1513,20 @@ class Delivery {
|
|
|
1401
1513
|
return;
|
|
1402
1514
|
}
|
|
1403
1515
|
this.dirty = true;
|
|
1516
|
+
if (this.progressKind === "card" &&
|
|
1517
|
+
this.display === "detailed" &&
|
|
1518
|
+
this.progress?.runId === m.runId &&
|
|
1519
|
+
this.progress.endedAt === undefined) {
|
|
1520
|
+
this.progressDirty = true;
|
|
1521
|
+
}
|
|
1404
1522
|
}
|
|
1405
1523
|
/**
|
|
1406
1524
|
* 首次有文本时发草稿(先把消息 id 写进 PG 再继续),之后至多每 `max(1s, features.minEditIntervalMs)` 更新一次。
|
|
1407
1525
|
*/
|
|
1408
1526
|
async flushDraft() {
|
|
1527
|
+
// a progress card shows the streamed text as its status line: no draft
|
|
1528
|
+
if (this.progressKind === "card")
|
|
1529
|
+
return;
|
|
1409
1530
|
const cur = this.streaming;
|
|
1410
1531
|
if (!cur?.complete || !this.dirty || cur.text.trim() === "")
|
|
1411
1532
|
return;
|
|
@@ -1437,7 +1558,7 @@ class Delivery {
|
|
|
1437
1558
|
catch (err) {
|
|
1438
1559
|
if (!editRejected(err))
|
|
1439
1560
|
throw err;
|
|
1440
|
-
//
|
|
1561
|
+
// an edit rejected midway: the draft is not edited again, the final text goes out anew
|
|
1441
1562
|
this.draftBroken = true;
|
|
1442
1563
|
this.dirty = false;
|
|
1443
1564
|
return;
|
|
@@ -1448,4 +1569,396 @@ class Delivery {
|
|
|
1448
1569
|
this.lastDraftAt = now;
|
|
1449
1570
|
this.dirty = false;
|
|
1450
1571
|
}
|
|
1572
|
+
// ---- the progress card (process blocks spec §6.2, §6.3) ----
|
|
1573
|
+
/**
|
|
1574
|
+
* The progress side of an event on a `card` / `plain` delivery. True when the event is fully
|
|
1575
|
+
* handled here (narration, the answer, a handoff, a pinned card); false hands it on to the usual
|
|
1576
|
+
* handling (blocking cards, files, run ends) after the progress card took its part.
|
|
1577
|
+
*/
|
|
1578
|
+
async handleProgress(e) {
|
|
1579
|
+
if (e.type === "run_started") {
|
|
1580
|
+
// a manual compaction run has no steps and no answer: no progress for it
|
|
1581
|
+
if (e.runId === null || e.payload.trigger === "compact")
|
|
1582
|
+
return false;
|
|
1583
|
+
await this.startProgress(e.runId, e.seq, e.createdAt);
|
|
1584
|
+
return true;
|
|
1585
|
+
}
|
|
1586
|
+
const prev = this.progress;
|
|
1587
|
+
if (prev === undefined || prev.endedAt !== undefined)
|
|
1588
|
+
return false;
|
|
1589
|
+
if (e.runId !== null && e.runId !== prev.runId)
|
|
1590
|
+
return false;
|
|
1591
|
+
const next = await this.reduce(prev, e);
|
|
1592
|
+
this.progress = next;
|
|
1593
|
+
if (next !== prev)
|
|
1594
|
+
this.progressDirty = true;
|
|
1595
|
+
switch (e.type) {
|
|
1596
|
+
case "assistant_message": {
|
|
1597
|
+
// the step's streamed text is over (its status line falls back to the narration)
|
|
1598
|
+
const key = `${e.runId}:${e.payload.step}`;
|
|
1599
|
+
this.finalized.add(key);
|
|
1600
|
+
if (this.streaming?.key === key) {
|
|
1601
|
+
this.streaming = undefined;
|
|
1602
|
+
this.dirty = false;
|
|
1603
|
+
}
|
|
1604
|
+
// narration (spec §1.1) shows only as the card's status line; thinking is never sent
|
|
1605
|
+
if (hasToolCall(e.payload.content))
|
|
1606
|
+
return true;
|
|
1607
|
+
await this.answer(e.seq, e.runId, e.payload.step, e.payload.content);
|
|
1608
|
+
return true;
|
|
1609
|
+
}
|
|
1610
|
+
case "tool_result":
|
|
1611
|
+
// a handoff is a pending action (sent merged after the answer): the card shows it now
|
|
1612
|
+
if (e.payload.view?.kind === "handoff")
|
|
1613
|
+
await this.editProgress(e.seq);
|
|
1614
|
+
else if (next.pinnedVersion !== prev.pinnedVersion)
|
|
1615
|
+
await this.milestone(e.seq, e.createdAt);
|
|
1616
|
+
return true;
|
|
1617
|
+
case "approval_requested":
|
|
1618
|
+
case "question_asked":
|
|
1619
|
+
case "approval_decided":
|
|
1620
|
+
case "question_answered":
|
|
1621
|
+
case "subagent_waiting":
|
|
1622
|
+
case "subagent_finished":
|
|
1623
|
+
// a wait for a person starts or ends: at once; the blocking card itself follows as usual
|
|
1624
|
+
if (next.state !== prev.state)
|
|
1625
|
+
await this.editProgress(e.seq);
|
|
1626
|
+
return false;
|
|
1627
|
+
case "run_finished":
|
|
1628
|
+
case "run_failed":
|
|
1629
|
+
case "run_aborted":
|
|
1630
|
+
await this.endProgress(e.seq);
|
|
1631
|
+
return false;
|
|
1632
|
+
default:
|
|
1633
|
+
return false;
|
|
1634
|
+
}
|
|
1635
|
+
}
|
|
1636
|
+
/**
|
|
1637
|
+
* A run starts: an edit channel posts its progress card (a new message, so it notifies), a
|
|
1638
|
+
* channel without edits a start message. The card's id and run are written in the same advance
|
|
1639
|
+
* as the event, so a replica that takes over edits the same message.
|
|
1640
|
+
*/
|
|
1641
|
+
async startProgress(runId, seq, at) {
|
|
1642
|
+
// the previous run's final edit may still be pending (throttled or failed retryably): it lands
|
|
1643
|
+
// now, with its end event's key, and is marked final, before this run's card takes over
|
|
1644
|
+
if (this.progress?.endedAt !== undefined)
|
|
1645
|
+
await this.flushProgress(true);
|
|
1646
|
+
const s = initProgress(runId, at.toISOString());
|
|
1647
|
+
this.progress = s;
|
|
1648
|
+
this.handoffsSent = 0;
|
|
1649
|
+
this.progressDirty = false;
|
|
1650
|
+
this.progressReposted = false;
|
|
1651
|
+
this.progressBroken = false;
|
|
1652
|
+
this.progressRetry = undefined;
|
|
1653
|
+
this.progressEndSeq = undefined;
|
|
1654
|
+
this.milestoneAt = null;
|
|
1655
|
+
this.milestoneText = undefined;
|
|
1656
|
+
if (this.progressKind === "card") {
|
|
1657
|
+
const { messageId } = await this.send(this.progressMessage(s), idempotencyKey(`${this.conversationId}-progress-${runId}`));
|
|
1658
|
+
this.lastProgressAt = Date.now();
|
|
1659
|
+
await this.advance(seq, { progress: { messageId, runId } });
|
|
1660
|
+
this.progressId = messageId;
|
|
1661
|
+
return;
|
|
1662
|
+
}
|
|
1663
|
+
// `brief` on a channel without edits: no start message, only the answer and what blocks
|
|
1664
|
+
if (this.display === "detailed")
|
|
1665
|
+
await this.send({ text: phrase("runStarted", this.locale) }, this.key(seq));
|
|
1666
|
+
await this.advance(seq, { progress: { messageId: null, runId } });
|
|
1667
|
+
this.progressId = null;
|
|
1668
|
+
}
|
|
1669
|
+
/**
|
|
1670
|
+
* The answer (a step without a tool call): one new message with the whole text, then the run's
|
|
1671
|
+
* handoff links not sent yet, merged into one message, and one advance past both. A draft left by
|
|
1672
|
+
* a job without the card (the setting changed mid-run) is finished as before.
|
|
1673
|
+
*/
|
|
1674
|
+
async answer(seq, runId, step, content) {
|
|
1675
|
+
let sent = false;
|
|
1676
|
+
if (this.draftId !== null) {
|
|
1677
|
+
await this.finalize(runId, step, content, seq);
|
|
1678
|
+
}
|
|
1679
|
+
else {
|
|
1680
|
+
const text = content
|
|
1681
|
+
.filter((b) => b.type === "text")
|
|
1682
|
+
.map((b) => b.text ?? "")
|
|
1683
|
+
.join("");
|
|
1684
|
+
if (text.trim() !== "") {
|
|
1685
|
+
await this.send({ text }, this.key(seq));
|
|
1686
|
+
sent = true;
|
|
1687
|
+
}
|
|
1688
|
+
}
|
|
1689
|
+
if (await this.sendHandoffs(seq))
|
|
1690
|
+
sent = true;
|
|
1691
|
+
if (sent)
|
|
1692
|
+
await this.advance(seq);
|
|
1693
|
+
}
|
|
1694
|
+
/** The run's handoff links not sent yet, as one message; false when there are none. */
|
|
1695
|
+
async sendHandoffs(seq) {
|
|
1696
|
+
const links = this.progress?.pending.slice(this.handoffsSent) ?? [];
|
|
1697
|
+
if (links.length === 0)
|
|
1698
|
+
return false;
|
|
1699
|
+
await this.send(handoffsMessage(links, this.locale), this.key(seq, "-handoffs"));
|
|
1700
|
+
this.handoffsSent += links.length;
|
|
1701
|
+
return true;
|
|
1702
|
+
}
|
|
1703
|
+
/**
|
|
1704
|
+
* The pinned card changed: the progress card shows it at once; a channel without edits gets its
|
|
1705
|
+
* text as a milestone message, unless the last one is at most a minute older (by the events' log
|
|
1706
|
+
* times, so a replica that takes over decides the same; `milestone_at` is in PG).
|
|
1707
|
+
*/
|
|
1708
|
+
async milestone(seq, at) {
|
|
1709
|
+
if (this.progressKind === "card") {
|
|
1710
|
+
await this.editProgress(seq);
|
|
1711
|
+
return;
|
|
1712
|
+
}
|
|
1713
|
+
// `brief`: no milestones on a channel without edits
|
|
1714
|
+
if (this.display !== "detailed")
|
|
1715
|
+
return;
|
|
1716
|
+
const pinned = this.progress?.pinned;
|
|
1717
|
+
if (pinned === undefined)
|
|
1718
|
+
return;
|
|
1719
|
+
const t = at.getTime();
|
|
1720
|
+
if (this.milestoneAt !== null && t - this.milestoneAt <= MILESTONE_INTERVAL_MS)
|
|
1721
|
+
return;
|
|
1722
|
+
await this.send({ text: pinned }, this.key(seq, "-milestone"));
|
|
1723
|
+
await this.advance(seq, { milestoneAt: at });
|
|
1724
|
+
this.milestoneAt = t;
|
|
1725
|
+
this.milestoneText = pinned;
|
|
1726
|
+
}
|
|
1727
|
+
/**
|
|
1728
|
+
* The run ended. A run that finished with no answer after its last narration gets that
|
|
1729
|
+
* narration as its answer message (process blocks spec §10 Execution rulings), with the handoff
|
|
1730
|
+
* links an answer takes along. Then the card is edited down to its finished form, and once that
|
|
1731
|
+
* edit is done (or refused for good) `progress_final` is set in the advance past the end event,
|
|
1732
|
+
* so a later job leaves the card alone. A channel without edits gets, in `detailed`, the pinned
|
|
1733
|
+
* text as a trailing milestone when the last one sent differs (a change the minute throttle
|
|
1734
|
+
* held back), and the handoff links no answer took along (a run that failed or stopped first).
|
|
1735
|
+
*/
|
|
1736
|
+
async endProgress(seq) {
|
|
1737
|
+
const s = this.progress;
|
|
1738
|
+
const promoted = s === undefined ? undefined : promotedAnswer(s);
|
|
1739
|
+
let sent = false;
|
|
1740
|
+
if (this.progressKind === "plain" &&
|
|
1741
|
+
this.display === "detailed" &&
|
|
1742
|
+
s?.pinned !== undefined &&
|
|
1743
|
+
s.pinned !== this.milestoneText) {
|
|
1744
|
+
await this.send({ text: s.pinned }, this.key(seq, "-milestone"));
|
|
1745
|
+
this.milestoneText = s.pinned;
|
|
1746
|
+
sent = true;
|
|
1747
|
+
}
|
|
1748
|
+
if (promoted !== undefined) {
|
|
1749
|
+
await this.send({ text: promoted }, this.key(seq, "-answer"));
|
|
1750
|
+
sent = true;
|
|
1751
|
+
}
|
|
1752
|
+
if (this.progressKind === "card") {
|
|
1753
|
+
if (promoted !== undefined && (await this.sendHandoffs(seq)))
|
|
1754
|
+
sent = true;
|
|
1755
|
+
this.progressEndSeq = seq;
|
|
1756
|
+
if (await this.editProgress(seq))
|
|
1757
|
+
await this.advance(seq, { progressFinal: true });
|
|
1758
|
+
else if (sent)
|
|
1759
|
+
await this.advance(seq);
|
|
1760
|
+
return;
|
|
1761
|
+
}
|
|
1762
|
+
if (await this.sendHandoffs(seq))
|
|
1763
|
+
sent = true;
|
|
1764
|
+
if (sent)
|
|
1765
|
+
await this.advance(seq);
|
|
1766
|
+
}
|
|
1767
|
+
/** Folds one event into the state; a step's tool labels are looked up first. */
|
|
1768
|
+
async reduce(s, e) {
|
|
1769
|
+
if (e.type === "assistant_message") {
|
|
1770
|
+
const keys = e.payload.content.flatMap((b) => b.type === "tool_call" && !this.toolInfos.has(b.name) ? [b.name] : []);
|
|
1771
|
+
if (keys.length > 0) {
|
|
1772
|
+
const infos = await toolInfo({ db: this.d.db, registry: this.d.registry }, this.s.row.orgId, keys);
|
|
1773
|
+
for (const k of keys)
|
|
1774
|
+
this.toolInfos.set(k, infos.find((i) => i.key === k));
|
|
1775
|
+
}
|
|
1776
|
+
}
|
|
1777
|
+
return reduceProgress(s, e, (key, input) => this.stepLabel(key, input), this.base);
|
|
1778
|
+
}
|
|
1779
|
+
/** A step as the approval card names a call: the tool's title and key argument, redacted. */
|
|
1780
|
+
stepLabel(key, input) {
|
|
1781
|
+
const info = this.toolInfos.get(key);
|
|
1782
|
+
const line = callSummary({ summary: null, input }, info, this.locale, this.s.redact);
|
|
1783
|
+
return line !== "" ? line : (info?.tool ?? key);
|
|
1784
|
+
}
|
|
1785
|
+
/**
|
|
1786
|
+
* Rebuilds the state of the run whose card this delivery edits (`progress_run_id`) by folding
|
|
1787
|
+
* its events from its `run_started` up to `last_seq`, so a job on any replica continues the same
|
|
1788
|
+
* card. The handoff links an answer took along count as sent.
|
|
1789
|
+
*/
|
|
1790
|
+
async rebuildProgress(runId, final) {
|
|
1791
|
+
const start = await this.d.db
|
|
1792
|
+
.selectFrom("conversation_events")
|
|
1793
|
+
.select("seq")
|
|
1794
|
+
.where("conversation_id", "=", this.conversationId)
|
|
1795
|
+
.where("run_id", "=", runId)
|
|
1796
|
+
.where("type", "=", "run_started")
|
|
1797
|
+
.executeTakeFirst();
|
|
1798
|
+
if (!start)
|
|
1799
|
+
return;
|
|
1800
|
+
let s;
|
|
1801
|
+
let handoffs = 0;
|
|
1802
|
+
// the milestones a channel without edits sent follow from the log times alone: replayed here
|
|
1803
|
+
let milestoneAt = null;
|
|
1804
|
+
let milestoneText;
|
|
1805
|
+
let after = Number(start.seq) - 1;
|
|
1806
|
+
let done = false;
|
|
1807
|
+
while (!done) {
|
|
1808
|
+
const evs = await this.d.eventLog.readAfter(this.conversationId, after, PAGE);
|
|
1809
|
+
done = evs.length < PAGE;
|
|
1810
|
+
for (const e of evs) {
|
|
1811
|
+
// later events are delivered by this job as usual
|
|
1812
|
+
if (e.seq > this.seen) {
|
|
1813
|
+
done = true;
|
|
1814
|
+
break;
|
|
1815
|
+
}
|
|
1816
|
+
after = e.seq;
|
|
1817
|
+
if (e.type === "run_started") {
|
|
1818
|
+
if (e.runId === runId)
|
|
1819
|
+
s = initProgress(runId, e.createdAt.toISOString());
|
|
1820
|
+
continue;
|
|
1821
|
+
}
|
|
1822
|
+
if (s === undefined || s.endedAt !== undefined)
|
|
1823
|
+
continue;
|
|
1824
|
+
const before = s;
|
|
1825
|
+
s = await this.reduce(s, e);
|
|
1826
|
+
if (s.endedAt !== undefined)
|
|
1827
|
+
this.progressEndSeq = e.seq;
|
|
1828
|
+
const answered = e.type === "assistant_message" && e.runId === runId && !hasToolCall(e.payload.content);
|
|
1829
|
+
const ended = s.endedAt !== undefined &&
|
|
1830
|
+
(this.progressKind === "plain" || promotedAnswer(s) !== undefined);
|
|
1831
|
+
if (answered || ended)
|
|
1832
|
+
handoffs = s.pending.length;
|
|
1833
|
+
if (s.pinnedVersion !== before.pinnedVersion && e.type === "tool_result") {
|
|
1834
|
+
const t = e.createdAt.getTime();
|
|
1835
|
+
if (milestoneAt === null || t - milestoneAt > MILESTONE_INTERVAL_MS) {
|
|
1836
|
+
milestoneAt = t;
|
|
1837
|
+
milestoneText = s.pinned;
|
|
1838
|
+
}
|
|
1839
|
+
}
|
|
1840
|
+
if (s.endedAt !== undefined && s.pinned !== undefined)
|
|
1841
|
+
milestoneText = s.pinned;
|
|
1842
|
+
}
|
|
1843
|
+
}
|
|
1844
|
+
this.progress = s;
|
|
1845
|
+
this.handoffsSent = handoffs;
|
|
1846
|
+
this.milestoneText = milestoneText;
|
|
1847
|
+
// one refresh: a previous job may have died (or failed retryably) before its edit; an ended
|
|
1848
|
+
// run's card only while its final edit may not have landed
|
|
1849
|
+
this.progressDirty = s !== undefined && !(s.endedAt !== undefined && final);
|
|
1850
|
+
}
|
|
1851
|
+
/** The progress card message for the state, with the step being streamed as its status line. */
|
|
1852
|
+
progressMessage(s) {
|
|
1853
|
+
const cur = this.streaming;
|
|
1854
|
+
const streamed = cur?.complete && cur.key.startsWith(`${s.runId}:`) && !this.finalized.has(cur.key)
|
|
1855
|
+
? statusLine(cur.text)
|
|
1856
|
+
: undefined;
|
|
1857
|
+
const card = progressCard(streamed !== undefined ? { ...s, status: streamed } : s, {
|
|
1858
|
+
base: this.base,
|
|
1859
|
+
conversationId: this.conversationId,
|
|
1860
|
+
locale: this.locale,
|
|
1861
|
+
mode: this.display,
|
|
1862
|
+
now: Date.now(),
|
|
1863
|
+
});
|
|
1864
|
+
return progressCardMessage(this.s.features, card, this.locale);
|
|
1865
|
+
}
|
|
1866
|
+
/**
|
|
1867
|
+
* Edits the progress card to the current state (`seq`: the event that changed it, for the
|
|
1868
|
+
* idempotency key; none for a throttled refresh). True when the card needs nothing more for
|
|
1869
|
+
* this state: the edit landed, or the platform refused it for good. A retryable failure (rate
|
|
1870
|
+
* limit, network) leaves the card dirty for the next interval instead of failing the job, so
|
|
1871
|
+
* blocking cards and the answer still go out. A rejected edit (message too old, content
|
|
1872
|
+
* refused) of a running card posts the card again once per run, recording the new message's id
|
|
1873
|
+
* and the re-post (`progress_reposted`) in one write; after that, and always for an ended
|
|
1874
|
+
* card, a rejection leaves the card as it is. The re-post's idempotency key derives from the
|
|
1875
|
+
* rejected message, so a job that re-posts the same rejected card again (the first one died
|
|
1876
|
+
* before its write) reuses it.
|
|
1877
|
+
*/
|
|
1878
|
+
async editProgress(seq) {
|
|
1879
|
+
const s = this.progress;
|
|
1880
|
+
if (this.progressKind !== "card" || s === undefined || this.progressId === null)
|
|
1881
|
+
return true;
|
|
1882
|
+
if (this.progressBroken)
|
|
1883
|
+
return true;
|
|
1884
|
+
this.progressDirty = false;
|
|
1885
|
+
this.lastProgressAt = Date.now();
|
|
1886
|
+
const message = this.progressMessage(s);
|
|
1887
|
+
const key = seq === undefined ? undefined : this.key(seq, "-progress");
|
|
1888
|
+
const rejected = this.progressId;
|
|
1889
|
+
try {
|
|
1890
|
+
await this.s.update(this.target, rejected, message, key, this.locale);
|
|
1891
|
+
this.progressRetry = undefined;
|
|
1892
|
+
return true;
|
|
1893
|
+
}
|
|
1894
|
+
catch (err) {
|
|
1895
|
+
if (!isChannelSendError(err) || err.retryable) {
|
|
1896
|
+
// the card catches up at the next interval; the delivery goes on
|
|
1897
|
+
this.progressDirty = true;
|
|
1898
|
+
this.progressRetry = err instanceof Error ? err : new Error(String(err));
|
|
1899
|
+
this.d.log.warn("channel progress edit failed; retrying at the next interval", {
|
|
1900
|
+
conversationId: this.conversationId,
|
|
1901
|
+
error: this.redact(errMsg(err)),
|
|
1902
|
+
});
|
|
1903
|
+
return false;
|
|
1904
|
+
}
|
|
1905
|
+
if (!editRejected(err))
|
|
1906
|
+
throw err;
|
|
1907
|
+
this.d.log.warn("channel progress edit rejected", {
|
|
1908
|
+
conversationId: this.conversationId,
|
|
1909
|
+
reposted: this.progressReposted,
|
|
1910
|
+
ended: s.endedAt !== undefined,
|
|
1911
|
+
error: this.redact(errMsg(err)),
|
|
1912
|
+
});
|
|
1913
|
+
}
|
|
1914
|
+
this.progressRetry = undefined;
|
|
1915
|
+
// an ended card is not worth a new message: the answer and any failure notice are out already
|
|
1916
|
+
if (this.progressReposted || s.endedAt !== undefined) {
|
|
1917
|
+
this.progressBroken = true;
|
|
1918
|
+
return true;
|
|
1919
|
+
}
|
|
1920
|
+
this.progressReposted = true;
|
|
1921
|
+
const { messageId } = await this.send(message, idempotencyKey(`${this.conversationId}-progress-${s.runId}-again-${rejected}`));
|
|
1922
|
+
// fenced like the draft id: only while this delivery still owns `last_seq` and the run
|
|
1923
|
+
const r = await this.d.db
|
|
1924
|
+
.updateTable("channel_deliveries")
|
|
1925
|
+
.set({ progress_message_id: messageId, progress_reposted: true, updated_at: new Date() })
|
|
1926
|
+
.where("conversation_id", "=", this.conversationId)
|
|
1927
|
+
.where("last_seq", "=", String(this.persisted))
|
|
1928
|
+
.where("progress_run_id", "=", s.runId)
|
|
1929
|
+
.executeTakeFirst();
|
|
1930
|
+
if (r.numUpdatedRows === 0n)
|
|
1931
|
+
throw new DeliveryLostError();
|
|
1932
|
+
this.progressId = messageId;
|
|
1933
|
+
return true;
|
|
1934
|
+
}
|
|
1935
|
+
/**
|
|
1936
|
+
* A throttled refresh of the card: at most every `max(1s, features.minEditIntervalMs)`, like the
|
|
1937
|
+
* streaming draft; `force` ignores the interval (the job is about to end). An ended run's card
|
|
1938
|
+
* is dirty only when its final edit has not landed: it is edited with the end event's key, then
|
|
1939
|
+
* marked final (a write fenced like the re-post's).
|
|
1940
|
+
*/
|
|
1941
|
+
async flushProgress(force) {
|
|
1942
|
+
if (this.progressKind !== "card" || !this.progressDirty)
|
|
1943
|
+
return;
|
|
1944
|
+
const interval = Math.max(DRAFT_INTERVAL_MS, this.s.features.minEditIntervalMs ?? 0);
|
|
1945
|
+
if (!force && Date.now() - this.lastProgressAt < interval)
|
|
1946
|
+
return;
|
|
1947
|
+
const s = this.progress;
|
|
1948
|
+
if (s?.endedAt === undefined) {
|
|
1949
|
+
await this.editProgress(undefined);
|
|
1950
|
+
return;
|
|
1951
|
+
}
|
|
1952
|
+
if (!(await this.editProgress(this.progressEndSeq)))
|
|
1953
|
+
return;
|
|
1954
|
+
const r = await this.d.db
|
|
1955
|
+
.updateTable("channel_deliveries")
|
|
1956
|
+
.set({ progress_final: true, updated_at: new Date() })
|
|
1957
|
+
.where("conversation_id", "=", this.conversationId)
|
|
1958
|
+
.where("last_seq", "=", String(this.persisted))
|
|
1959
|
+
.where("progress_run_id", "=", s.runId)
|
|
1960
|
+
.executeTakeFirst();
|
|
1961
|
+
if (r.numUpdatedRows === 0n)
|
|
1962
|
+
throw new DeliveryLostError();
|
|
1963
|
+
}
|
|
1451
1964
|
}
|