@animalabs/agent-framework 0.28.0 → 0.30.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 +88 -25
- package/dist/src/admission/admit.d.ts +90 -0
- package/dist/src/admission/admit.d.ts.map +1 -0
- package/dist/src/admission/admit.js +43 -0
- package/dist/src/admission/admit.js.map +1 -0
- package/dist/src/agent.d.ts +21 -0
- package/dist/src/agent.d.ts.map +1 -1
- package/dist/src/agent.js +47 -7
- package/dist/src/agent.js.map +1 -1
- package/dist/src/api/mcp-server-core.d.ts.map +1 -1
- package/dist/src/api/mcp-server-core.js +3 -12
- package/dist/src/api/mcp-server-core.js.map +1 -1
- package/dist/src/api/server.d.ts.map +1 -1
- package/dist/src/api/server.js +7 -3
- package/dist/src/api/server.js.map +1 -1
- package/dist/src/author-presentation.d.ts +50 -0
- package/dist/src/author-presentation.d.ts.map +1 -0
- package/dist/src/author-presentation.js +58 -0
- package/dist/src/author-presentation.js.map +1 -0
- package/dist/src/auto-continue.d.ts +2 -0
- package/dist/src/auto-continue.d.ts.map +1 -1
- package/dist/src/auto-continue.js +5 -2
- package/dist/src/auto-continue.js.map +1 -1
- package/dist/src/code-execution/isolate/runner.d.ts +7 -5
- package/dist/src/code-execution/isolate/runner.d.ts.map +1 -1
- package/dist/src/code-execution/isolate/runner.js +7 -5
- package/dist/src/code-execution/isolate/runner.js.map +1 -1
- package/dist/src/code-execution/isolate/scripts.d.ts.map +1 -1
- package/dist/src/code-execution/isolate/scripts.js +3 -2
- package/dist/src/code-execution/isolate/scripts.js.map +1 -1
- package/dist/src/dendrite/index.d.ts +6 -0
- package/dist/src/dendrite/index.d.ts.map +1 -0
- package/dist/src/dendrite/index.js +3 -0
- package/dist/src/dendrite/index.js.map +1 -0
- package/dist/src/dendrite/presets.d.ts +60 -0
- package/dist/src/dendrite/presets.d.ts.map +1 -0
- package/dist/src/dendrite/presets.js +117 -0
- package/dist/src/dendrite/presets.js.map +1 -0
- package/dist/src/dendrite/registry.d.ts +260 -0
- package/dist/src/dendrite/registry.d.ts.map +1 -0
- package/dist/src/dendrite/registry.js +742 -0
- package/dist/src/dendrite/registry.js.map +1 -0
- package/dist/src/dendrite/types.d.ts +392 -0
- package/dist/src/dendrite/types.d.ts.map +1 -0
- package/dist/src/dendrite/types.js +24 -0
- package/dist/src/dendrite/types.js.map +1 -0
- package/dist/src/framework.d.ts +846 -67
- package/dist/src/framework.d.ts.map +1 -1
- package/dist/src/framework.js +4213 -924
- package/dist/src/framework.js.map +1 -1
- package/dist/src/gate/event-gate.d.ts +46 -14
- package/dist/src/gate/event-gate.d.ts.map +1 -1
- package/dist/src/gate/event-gate.js +143 -53
- package/dist/src/gate/event-gate.js.map +1 -1
- package/dist/src/gate/index.d.ts +1 -1
- package/dist/src/gate/index.d.ts.map +1 -1
- package/dist/src/gate/index.js +1 -1
- package/dist/src/gate/index.js.map +1 -1
- package/dist/src/gate/types.d.ts +12 -2
- package/dist/src/gate/types.d.ts.map +1 -1
- package/dist/src/heartbeat/heartbeat.d.ts +18 -0
- package/dist/src/heartbeat/heartbeat.d.ts.map +1 -1
- package/dist/src/heartbeat/heartbeat.js +34 -8
- package/dist/src/heartbeat/heartbeat.js.map +1 -1
- package/dist/src/held-writes.d.ts +3 -3
- package/dist/src/held-writes.js +3 -3
- package/dist/src/host-presentation.d.ts +174 -0
- package/dist/src/host-presentation.d.ts.map +1 -0
- package/dist/src/host-presentation.js +565 -0
- package/dist/src/host-presentation.js.map +1 -0
- package/dist/src/index.d.ts +7 -4
- package/dist/src/index.d.ts.map +1 -1
- package/dist/src/index.js +7 -2
- package/dist/src/index.js.map +1 -1
- package/dist/src/line-reader.d.ts +4 -0
- package/dist/src/line-reader.d.ts.map +1 -0
- package/dist/src/line-reader.js +59 -0
- package/dist/src/line-reader.js.map +1 -0
- package/dist/src/mcpl/channel-registry.d.ts +118 -15
- package/dist/src/mcpl/channel-registry.d.ts.map +1 -1
- package/dist/src/mcpl/channel-registry.js +266 -110
- package/dist/src/mcpl/channel-registry.js.map +1 -1
- package/dist/src/mcpl/conversation-router.d.ts.map +1 -1
- package/dist/src/mcpl/conversation-router.js +2 -1
- package/dist/src/mcpl/conversation-router.js.map +1 -1
- package/dist/src/mcpl/convert-block.d.ts +1 -0
- package/dist/src/mcpl/convert-block.d.ts.map +1 -1
- package/dist/src/mcpl/convert-block.js +16 -4
- package/dist/src/mcpl/convert-block.js.map +1 -1
- package/dist/src/mcpl/hook-orchestrator.d.ts.map +1 -1
- package/dist/src/mcpl/hook-orchestrator.js +4 -3
- package/dist/src/mcpl/hook-orchestrator.js.map +1 -1
- package/dist/src/mcpl/inbound-source.d.ts +3 -1
- package/dist/src/mcpl/inbound-source.d.ts.map +1 -1
- package/dist/src/mcpl/inbound-source.js +3 -1
- package/dist/src/mcpl/inbound-source.js.map +1 -1
- package/dist/src/mcpl/modern-connection.d.ts.map +1 -1
- package/dist/src/mcpl/modern-connection.js +11 -7
- package/dist/src/mcpl/modern-connection.js.map +1 -1
- package/dist/src/mcpl/protocol-family.d.ts +3 -2
- package/dist/src/mcpl/protocol-family.d.ts.map +1 -1
- package/dist/src/mcpl/protocol-family.js +25 -3
- package/dist/src/mcpl/protocol-family.js.map +1 -1
- package/dist/src/mcpl/push-coalescer.d.ts +9 -0
- package/dist/src/mcpl/push-coalescer.d.ts.map +1 -1
- package/dist/src/mcpl/push-coalescer.js +21 -0
- package/dist/src/mcpl/push-coalescer.js.map +1 -1
- package/dist/src/mcpl/push-handler.js +2 -2
- package/dist/src/mcpl/push-handler.js.map +1 -1
- package/dist/src/mcpl/references.d.ts +12 -40
- package/dist/src/mcpl/references.d.ts.map +1 -1
- package/dist/src/mcpl/references.js +29 -23
- package/dist/src/mcpl/references.js.map +1 -1
- package/dist/src/mcpl/server-connection.d.ts.map +1 -1
- package/dist/src/mcpl/server-connection.js +20 -20
- package/dist/src/mcpl/server-connection.js.map +1 -1
- package/dist/src/mcpl/skip-reply-wake.d.ts +25 -0
- package/dist/src/mcpl/skip-reply-wake.d.ts.map +1 -1
- package/dist/src/mcpl/skip-reply-wake.js +25 -0
- package/dist/src/mcpl/skip-reply-wake.js.map +1 -1
- package/dist/src/mcpl/tool-presence.d.ts.map +1 -1
- package/dist/src/mcpl/tool-presence.js +18 -17
- package/dist/src/mcpl/tool-presence.js.map +1 -1
- package/dist/src/mcpl/tool-signature.d.ts.map +1 -1
- package/dist/src/mcpl/tool-signature.js +17 -16
- package/dist/src/mcpl/tool-signature.js.map +1 -1
- package/dist/src/mcpl/toolset-host.d.ts +8 -26
- package/dist/src/mcpl/toolset-host.d.ts.map +1 -1
- package/dist/src/mcpl/toolset-host.js +16 -6
- package/dist/src/mcpl/toolset-host.js.map +1 -1
- package/dist/src/mcpl/toolsets-module.d.ts +14 -25
- package/dist/src/mcpl/toolsets-module.d.ts.map +1 -1
- package/dist/src/mcpl/toolsets-module.js +187 -50
- package/dist/src/mcpl/toolsets-module.js.map +1 -1
- package/dist/src/mcpl/transport.d.ts +1 -1
- package/dist/src/mcpl/transport.d.ts.map +1 -1
- package/dist/src/mcpl/transport.js +16 -16
- package/dist/src/mcpl/transport.js.map +1 -1
- package/dist/src/mcpl/types.d.ts +28 -12
- package/dist/src/mcpl/types.d.ts.map +1 -1
- package/dist/src/mcpl/types.js.map +1 -1
- package/dist/src/module-registry.d.ts +6 -7
- package/dist/src/module-registry.d.ts.map +1 -1
- package/dist/src/module-registry.js +6 -7
- package/dist/src/module-registry.js.map +1 -1
- package/dist/src/modules/api/index.d.ts.map +1 -1
- package/dist/src/modules/api/index.js +4 -2
- package/dist/src/modules/api/index.js.map +1 -1
- package/dist/src/modules/discord/index.d.ts.map +1 -1
- package/dist/src/modules/discord/index.js +33 -25
- package/dist/src/modules/discord/index.js.map +1 -1
- package/dist/src/modules/history/index.js +8 -6
- package/dist/src/modules/history/index.js.map +1 -1
- package/dist/src/modules/sender-name.d.ts +7 -0
- package/dist/src/modules/sender-name.d.ts.map +1 -0
- package/dist/src/modules/sender-name.js +10 -0
- package/dist/src/modules/sender-name.js.map +1 -0
- package/dist/src/modules/workspace/answers.d.ts +5 -1
- package/dist/src/modules/workspace/answers.d.ts.map +1 -1
- package/dist/src/modules/workspace/answers.js +16 -1
- package/dist/src/modules/workspace/answers.js.map +1 -1
- package/dist/src/modules/workspace/direct-write.d.ts.map +1 -1
- package/dist/src/modules/workspace/direct-write.js +6 -4
- package/dist/src/modules/workspace/direct-write.js.map +1 -1
- package/dist/src/modules/workspace/effects.d.ts +4 -2
- package/dist/src/modules/workspace/effects.d.ts.map +1 -1
- package/dist/src/modules/workspace/effects.js +50 -40
- package/dist/src/modules/workspace/effects.js.map +1 -1
- package/dist/src/modules/workspace/index.d.ts +1 -0
- package/dist/src/modules/workspace/index.d.ts.map +1 -1
- package/dist/src/modules/workspace/index.js +66 -36
- package/dist/src/modules/workspace/index.js.map +1 -1
- package/dist/src/modules/workspace/observe.d.ts +51 -20
- package/dist/src/modules/workspace/observe.d.ts.map +1 -1
- package/dist/src/modules/workspace/observe.js +120 -82
- package/dist/src/modules/workspace/observe.js.map +1 -1
- package/dist/src/modules/workspace/reconcile.d.ts +7 -1
- package/dist/src/modules/workspace/reconcile.d.ts.map +1 -1
- package/dist/src/modules/workspace/reconcile.js +133 -37
- package/dist/src/modules/workspace/reconcile.js.map +1 -1
- package/dist/src/notice-tags.d.ts +81 -0
- package/dist/src/notice-tags.d.ts.map +1 -0
- package/dist/src/notice-tags.js +85 -0
- package/dist/src/notice-tags.js.map +1 -0
- package/dist/src/reasoning-loss-notice.d.ts.map +1 -1
- package/dist/src/reasoning-loss-notice.js +5 -3
- package/dist/src/reasoning-loss-notice.js.map +1 -1
- package/dist/src/silent-heartbeat.d.ts +5 -55
- package/dist/src/silent-heartbeat.d.ts.map +1 -1
- package/dist/src/silent-heartbeat.js +63 -7
- package/dist/src/silent-heartbeat.js.map +1 -1
- package/dist/src/stored-injections.d.ts +4 -0
- package/dist/src/stored-injections.d.ts.map +1 -1
- package/dist/src/stored-injections.js +6 -0
- package/dist/src/stored-injections.js.map +1 -1
- package/dist/src/supplied-text.d.ts +35 -0
- package/dist/src/supplied-text.d.ts.map +1 -0
- package/dist/src/supplied-text.js +141 -0
- package/dist/src/supplied-text.js.map +1 -0
- package/dist/src/tool-args.d.ts.map +1 -1
- package/dist/src/tool-args.js +9 -8
- package/dist/src/tool-args.js.map +1 -1
- package/dist/src/tool-image-ledger.d.ts.map +1 -1
- package/dist/src/tool-image-ledger.js +2 -1
- package/dist/src/tool-image-ledger.js.map +1 -1
- package/dist/src/tool-presentation.d.ts.map +1 -1
- package/dist/src/tool-presentation.js +5 -4
- package/dist/src/tool-presentation.js.map +1 -1
- package/dist/src/tune-out/coordinator.d.ts +382 -11
- package/dist/src/tune-out/coordinator.d.ts.map +1 -1
- package/dist/src/tune-out/coordinator.js +1100 -119
- package/dist/src/tune-out/coordinator.js.map +1 -1
- package/dist/src/tune-out/tools.d.ts +101 -5
- package/dist/src/tune-out/tools.d.ts.map +1 -1
- package/dist/src/tune-out/tools.js +55 -18
- package/dist/src/tune-out/tools.js.map +1 -1
- package/dist/src/types/agent.d.ts +48 -9
- package/dist/src/types/agent.d.ts.map +1 -1
- package/dist/src/types/framework.d.ts +142 -0
- package/dist/src/types/framework.d.ts.map +1 -1
- package/dist/src/types/module.d.ts +22 -11
- package/dist/src/types/module.d.ts.map +1 -1
- package/dist/src/types/trace.d.ts +136 -0
- package/dist/src/types/trace.d.ts.map +1 -1
- package/package.json +3 -3
- package/src/admission/admit.ts +113 -0
- package/src/agent.ts +52 -7
- package/src/api/mcp-server-core.ts +3 -14
- package/src/api/server.ts +7 -3
- package/src/author-presentation.ts +81 -0
- package/src/auto-continue.ts +8 -2
- package/src/code-execution/isolate/runner.ts +7 -5
- package/src/code-execution/isolate/scripts.ts +3 -2
- package/src/dendrite/index.ts +32 -0
- package/src/dendrite/presets.ts +149 -0
- package/src/dendrite/registry.ts +808 -0
- package/src/dendrite/types.ts +397 -0
- package/src/framework.ts +4362 -852
- package/src/gate/event-gate.ts +159 -52
- package/src/gate/index.ts +1 -1
- package/src/gate/types.ts +12 -2
- package/src/heartbeat/heartbeat.ts +48 -9
- package/src/held-writes.ts +3 -3
- package/src/host-presentation.ts +612 -0
- package/src/index.ts +17 -4
- package/src/line-reader.ts +58 -0
- package/src/mcpl/channel-registry.ts +306 -111
- package/src/mcpl/conversation-router.ts +2 -1
- package/src/mcpl/convert-block.ts +17 -4
- package/src/mcpl/hook-orchestrator.ts +4 -3
- package/src/mcpl/inbound-source.ts +3 -1
- package/src/mcpl/modern-connection.ts +11 -7
- package/src/mcpl/protocol-family.ts +24 -3
- package/src/mcpl/push-coalescer.ts +19 -0
- package/src/mcpl/push-handler.ts +2 -2
- package/src/mcpl/references.ts +31 -23
- package/src/mcpl/server-connection.ts +20 -18
- package/src/mcpl/skip-reply-wake.ts +35 -0
- package/src/mcpl/tool-presence.ts +18 -17
- package/src/mcpl/tool-signature.ts +17 -16
- package/src/mcpl/toolset-host.ts +18 -6
- package/src/mcpl/toolsets-module.ts +149 -50
- package/src/mcpl/transport.ts +18 -14
- package/src/mcpl/types.ts +29 -12
- package/src/module-registry.ts +6 -7
- package/src/modules/api/index.ts +4 -2
- package/src/modules/discord/index.ts +37 -25
- package/src/modules/history/index.ts +8 -6
- package/src/modules/sender-name.ts +9 -0
- package/src/modules/workspace/answers.ts +20 -2
- package/src/modules/workspace/direct-write.ts +4 -3
- package/src/modules/workspace/effects.ts +50 -40
- package/src/modules/workspace/index.ts +58 -34
- package/src/modules/workspace/observe.ts +139 -88
- package/src/modules/workspace/reconcile.ts +159 -36
- package/src/notice-tags.ts +86 -0
- package/src/reasoning-loss-notice.ts +5 -3
- package/src/silent-heartbeat.ts +11 -7
- package/src/stored-injections.ts +7 -0
- package/src/supplied-text.ts +154 -0
- package/src/tool-args.ts +9 -8
- package/src/tool-image-ledger.ts +2 -1
- package/src/tool-presentation.ts +5 -4
- package/src/tune-out/coordinator.ts +1252 -123
- package/src/tune-out/tools.ts +152 -11
- package/src/types/agent.ts +51 -9
- package/src/types/framework.ts +146 -0
- package/src/types/module.ts +23 -11
- package/src/types/trace.ts +150 -0
|
@@ -14,7 +14,10 @@
|
|
|
14
14
|
* <backscroll> precedent), and `[Tune-out: …]` bracket notices carry
|
|
15
15
|
* lifecycle facts (the [Gate: …] precedent).
|
|
16
16
|
*/
|
|
17
|
+
import { NOTICE_TAG } from '../notice-tags.js';
|
|
18
|
+
import { cutToFit, quotedValue, suppliedValue } from '../supplied-text.js';
|
|
17
19
|
import { randomUUID } from 'node:crypto';
|
|
20
|
+
import { authorLine, authorNamed, beginsWithAuthorLine } from '../author-presentation.js';
|
|
18
21
|
import { CapabilityGrant } from '../mcpl/capability-grant.js';
|
|
19
22
|
import { armAfter, armAt } from '../deadline-timer.js';
|
|
20
23
|
/** Defaults for tune_out tool params. */
|
|
@@ -26,16 +29,48 @@ export const TUNE_OUT_DEFAULTS = {
|
|
|
26
29
|
/** Coalescing window for wake invocations: a mention storm becomes one
|
|
27
30
|
* subconscious turn, and max-wakes counts invocations, not messages. */
|
|
28
31
|
const WAKE_COALESCE_MS = 2_000;
|
|
32
|
+
/**
|
|
33
|
+
* One backlog line: author, then the message's blocks in order — text as
|
|
34
|
+
* is, anything else named by kind (`[image]`, `[document]`), so a release
|
|
35
|
+
* never drops a block silently (#232 gap 4). The author is named once: a
|
|
36
|
+
* server that renders `Name: body` into the text itself is not doubled.
|
|
37
|
+
* A name the line adds is a value someone supplied, kept to one line with
|
|
38
|
+
* its notice openings marked (authorLine), as main's dump writes it.
|
|
39
|
+
*/
|
|
40
|
+
export function renderHeldLine(m) {
|
|
41
|
+
const author = authorNamed(m.metadata) ?? m.participant;
|
|
42
|
+
const parts = m.content.map((b) => b.type === 'text' ? b.text : `[${b.type}]`);
|
|
43
|
+
const line = parts.filter((p) => p.length > 0).join(' ');
|
|
44
|
+
const firstText = m.content.find((b) => b.type === 'text')?.text;
|
|
45
|
+
return firstText !== undefined && beginsWithAuthorLine(author, firstText) ? line : authorLine(author, line);
|
|
46
|
+
}
|
|
47
|
+
/** The deferred write a stored row landed from, when it came through the queue. */
|
|
48
|
+
function writeIdOf(m) {
|
|
49
|
+
const writeId = m.metadata?.deferredWriteId;
|
|
50
|
+
return typeof writeId === 'string' ? writeId : undefined;
|
|
51
|
+
}
|
|
52
|
+
/**
|
|
53
|
+
* Whether a held message is one of this channel's: by its channel id, and by
|
|
54
|
+
* its server where it records one, since two servers can register the same
|
|
55
|
+
* channel id. A message recording neither is taken as the channel's, as
|
|
56
|
+
* before servers were recorded.
|
|
57
|
+
*/
|
|
58
|
+
function inChannelOf(serverId, channelId) {
|
|
59
|
+
return (m) => {
|
|
60
|
+
const meta = m.metadata;
|
|
61
|
+
return (meta?.channelId ?? channelId) === channelId && (meta?.serverId ?? serverId) === serverId;
|
|
62
|
+
};
|
|
63
|
+
}
|
|
29
64
|
/** How long after an end time whose cancel threw the cancel is tried again. */
|
|
30
65
|
const EXPIRY_RETRY_MS = 60_000;
|
|
31
66
|
/** Ends a backlog line cut to fit in one of the residents' messages. */
|
|
32
|
-
const CUT_MARK =
|
|
67
|
+
const CUT_MARK = ` [${NOTICE_TAG.cutToFit}; the whole message is in the channel's history]`;
|
|
33
68
|
/**
|
|
34
69
|
* tune_out's refusal of a channel already tuned out: its settings, then what
|
|
35
70
|
* its transport is now where the repeat tried to open it again (`transport`,
|
|
36
71
|
* from the framework's dispatch), then how to change the settings.
|
|
37
72
|
*/
|
|
38
|
-
export function alreadyTunedOutText(
|
|
73
|
+
export function alreadyTunedOutText(quoted, p, transport) {
|
|
39
74
|
// A duration so long its end is past what a Date can hold has no time to show.
|
|
40
75
|
const expires = p.expiresAtMs !== undefined ? new Date(p.expiresAtMs) : undefined;
|
|
41
76
|
const until = expires && Number.isFinite(expires.getTime())
|
|
@@ -43,19 +78,12 @@ export function alreadyTunedOutText(shown, p, transport) {
|
|
|
43
78
|
: '';
|
|
44
79
|
// A thrown error's words may end without a stop.
|
|
45
80
|
const now = transport === undefined ? '' : /[.!?]$/.test(transport) ? `${transport} ` : `${transport}. `;
|
|
46
|
-
return `Nothing changed${transport !== undefined ? ' in the tune-out' : ''}: ${
|
|
81
|
+
return `Nothing changed${transport !== undefined ? ' in the tune-out' : ''}: ${quoted} is already `
|
|
47
82
|
+ `tuned out, with cadenceSeconds ${p.cadenceSeconds}, backlogCap ${p.backlogCap} and maxWakes ${p.maxWakes}${until}. `
|
|
48
83
|
+ now
|
|
49
84
|
+ 'To change those, cancel it first with tune_out mode "cancel", which delivers its backlog to you now, then call '
|
|
50
85
|
+ 'tune_out again with the new settings.';
|
|
51
86
|
}
|
|
52
|
-
/** The first `length` code units of `text`, one fewer where the last would be
|
|
53
|
-
* the first half of a surrogate pair. */
|
|
54
|
-
function prefixOf(text, length) {
|
|
55
|
-
const cut = text.slice(0, Math.max(0, length));
|
|
56
|
-
const last = cut.charCodeAt(cut.length - 1);
|
|
57
|
-
return last >= 0xd800 && last <= 0xdbff ? cut.slice(0, -1) : cut;
|
|
58
|
-
}
|
|
59
87
|
/** What a thrown value says, without throwing: an Error's message, or the
|
|
60
88
|
* value as text, which String() can't give for an object with no prototype. */
|
|
61
89
|
function thrownReason(error) {
|
|
@@ -79,8 +107,60 @@ export class TuneOutCoordinator {
|
|
|
79
107
|
expiryTimers = new Map();
|
|
80
108
|
/** Channels with a wake invocation pending inside the coalescing window. */
|
|
81
109
|
pendingWakes = new Map();
|
|
82
|
-
/**
|
|
110
|
+
/**
|
|
111
|
+
* Held messages the channel's reader hasn't looked at, per channel key:
|
|
112
|
+
* what makes a cadence period worth a look. Counted up as messages are
|
|
113
|
+
* held and back to zero at each look; rebuilt from the held rows where
|
|
114
|
+
* memory can't know it (rebuildTally): after a restart, and when a
|
|
115
|
+
* channel's own tune-out ends while the all-except hold still holds it.
|
|
116
|
+
* A failed reader fork's messages count again (readerFailed).
|
|
117
|
+
*/
|
|
83
118
|
divertedSinceInvocation = new Map();
|
|
119
|
+
/**
|
|
120
|
+
* The persistent subconscious's last look at each held channel, per epoch:
|
|
121
|
+
* the store's sequence when the look was asked for. Durable, so that after
|
|
122
|
+
* a restart its next look counts only what was held since (rebuildTally).
|
|
123
|
+
* Reader forks need none: what they were handed is in memory, and after a
|
|
124
|
+
* restart the first fork of an epoch is handed all it has held.
|
|
125
|
+
*/
|
|
126
|
+
lastLooksCache;
|
|
127
|
+
/**
|
|
128
|
+
* `reader: 'forks'`: the highest sequence of a held message already
|
|
129
|
+
* handed to a reader fork, per epoch and channel (handOffKey). Each held
|
|
130
|
+
* message is delivered to exactly one fork. A channel the all-except hold
|
|
131
|
+
* holds can be taken by a tune-out of its own and given back, and each
|
|
132
|
+
* epoch's readers read that epoch's messages, so what one epoch's readers
|
|
133
|
+
* were handed never moves or clears the other's. In-memory: after a
|
|
134
|
+
* restart the first fork of an epoch is handed everything the epoch has
|
|
135
|
+
* held, which is the right side to err on.
|
|
136
|
+
*/
|
|
137
|
+
readerCursor = new Map();
|
|
138
|
+
/**
|
|
139
|
+
* `reader: 'forks'`: the deferred writes handed to a reader fork while
|
|
140
|
+
* still queued, per epoch and channel. Each lands in the store later as a row
|
|
141
|
+
* stamped with the same id (`metadata.deferredWriteId`), past the cursor;
|
|
142
|
+
* that row is not handed again. Cleared with the cursor.
|
|
143
|
+
*/
|
|
144
|
+
readerHandedWrites = new Map();
|
|
145
|
+
/**
|
|
146
|
+
* `reader: 'forks'`: held messages a reader fork was handed but never read,
|
|
147
|
+
* per epoch and channel: its derive failed, or its run threw before it reported
|
|
148
|
+
* (readerFailed). The next invocation is handed them again, cursor or no:
|
|
149
|
+
* stored rows by id, and by write id those that were queued when handed
|
|
150
|
+
* (stored or still queued now). Cleared with the cursor.
|
|
151
|
+
*/
|
|
152
|
+
readerReturned = new Map();
|
|
153
|
+
/**
|
|
154
|
+
* `reader: 'forks'`: the late forks derived for an ended epoch's messages
|
|
155
|
+
* (readerFailed), so that a late fork's own failure derives no other.
|
|
156
|
+
*/
|
|
157
|
+
lateForks = new WeakSet();
|
|
158
|
+
/** The all-except scope's durable record, cached (undefined = not read yet). */
|
|
159
|
+
scopeCache;
|
|
160
|
+
/** The epoch whose release this process delivered and whose hold is not yet recorded as cleared. */
|
|
161
|
+
scopeReleased;
|
|
162
|
+
/** Timer key for the scope's cadence and expiry. */
|
|
163
|
+
static SCOPE_KEY = '\0all-except';
|
|
84
164
|
constructor(channelRegistry, serverRegistry, hooks) {
|
|
85
165
|
this.channelRegistry = channelRegistry;
|
|
86
166
|
this.serverRegistry = serverRegistry;
|
|
@@ -89,6 +169,26 @@ export class TuneOutCoordinator {
|
|
|
89
169
|
key(serverId, channelId) {
|
|
90
170
|
return `${serverId}\0${channelId}`;
|
|
91
171
|
}
|
|
172
|
+
/** The readers' hand-off bookkeeping's key: one epoch's reading of one channel. */
|
|
173
|
+
handOffKey(epochId, serverId, channelId) {
|
|
174
|
+
return `${epochId}\0${serverId}\0${channelId}`;
|
|
175
|
+
}
|
|
176
|
+
/** An ended epoch's hand-off bookkeeping goes with it, every channel's. */
|
|
177
|
+
dropHandOffs(epochId) {
|
|
178
|
+
for (const map of [this.readerCursor, this.readerHandedWrites, this.readerReturned]) {
|
|
179
|
+
for (const key of map.keys())
|
|
180
|
+
if (key.startsWith(`${epochId}\0`))
|
|
181
|
+
map.delete(key);
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
/** A reader exists: the persistent subconscious, or forks on demand. */
|
|
185
|
+
readerAvailable() {
|
|
186
|
+
return this.hooks.subconsciousName() != null || typeof this.hooks.invokeReader === 'function';
|
|
187
|
+
}
|
|
188
|
+
/** Reader forks are the configured reader. */
|
|
189
|
+
get forkReader() {
|
|
190
|
+
return this.hooks.subconsciousName() == null && typeof this.hooks.invokeReader === 'function';
|
|
191
|
+
}
|
|
92
192
|
/** A channel as the resident and the subconscious are shown it
|
|
93
193
|
* (ChannelRegistry.nameShown): its id, or, where another server registers
|
|
94
194
|
* the same id, its server-qualified name, which tune_out and
|
|
@@ -97,6 +197,9 @@ export class TuneOutCoordinator {
|
|
|
97
197
|
shown(serverId, channelId) {
|
|
98
198
|
return this.channelRegistry.nameShown({ serverId, channelId });
|
|
99
199
|
}
|
|
200
|
+
quotedShown(serverId, channelId) {
|
|
201
|
+
return this.channelRegistry.quotedShown({ serverId, channelId });
|
|
202
|
+
}
|
|
100
203
|
/** Restart cadence + expiry timers and re-anchor after a process restart. */
|
|
101
204
|
resumeActiveEpochs() {
|
|
102
205
|
let oldestAnchor = null;
|
|
@@ -114,9 +217,42 @@ export class TuneOutCoordinator {
|
|
|
114
217
|
oldestAnchor = params.startedAtSequence;
|
|
115
218
|
}
|
|
116
219
|
}
|
|
220
|
+
const scope = this.getAllExcept();
|
|
221
|
+
if (scope) {
|
|
222
|
+
if (scope.params.expiresAtMs <= Date.now()) {
|
|
223
|
+
this.cancelAllExcept('duration', 'duration elapsed');
|
|
224
|
+
}
|
|
225
|
+
else {
|
|
226
|
+
this.armScopeTimers(scope.params);
|
|
227
|
+
if (oldestAnchor === null || scope.params.startedAtSequence < oldestAnchor) {
|
|
228
|
+
oldestAnchor = scope.params.startedAtSequence;
|
|
229
|
+
}
|
|
230
|
+
}
|
|
231
|
+
}
|
|
117
232
|
if (oldestAnchor !== null) {
|
|
118
233
|
this.hooks.setSubconsciousAnchor(oldestAnchor);
|
|
119
234
|
}
|
|
235
|
+
// What each held channel's reader hasn't looked at was counted in
|
|
236
|
+
// memory, so it is counted again from the held rows: without it, a
|
|
237
|
+
// channel held across the restart gets no cadence look until something
|
|
238
|
+
// new arrives.
|
|
239
|
+
// Stored and still queued alike: at a quiesced boot, restored writes stay
|
|
240
|
+
// queued until the resume flushes them.
|
|
241
|
+
const held = new Set();
|
|
242
|
+
for (const m of [...this.hooks.getStoredMessages(), ...(this.hooks.getDeferredMessages?.() ?? [])]) {
|
|
243
|
+
const meta = m.metadata;
|
|
244
|
+
const epochId = meta?.tuneOut?.epochId;
|
|
245
|
+
if (!meta || !epochId || !meta.channelId)
|
|
246
|
+
continue;
|
|
247
|
+
const key = this.key(meta.serverId ?? '', meta.channelId);
|
|
248
|
+
if (!held.has(key) && this.holdFor(meta.serverId ?? '', meta.channelId)?.epochId === epochId)
|
|
249
|
+
held.add(key);
|
|
250
|
+
}
|
|
251
|
+
for (const key of held) {
|
|
252
|
+
const [serverId, channelId] = key.split('\0');
|
|
253
|
+
this.rebuildTally(serverId, channelId);
|
|
254
|
+
}
|
|
255
|
+
this.pruneLooks();
|
|
120
256
|
}
|
|
121
257
|
armExpiry(serverId, channelId, params) {
|
|
122
258
|
if (params.expiresAtMs === undefined)
|
|
@@ -169,39 +305,19 @@ export class TuneOutCoordinator {
|
|
|
169
305
|
// ==========================================================================
|
|
170
306
|
// Enter / cancel
|
|
171
307
|
// ==========================================================================
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
+ "conversation, and tune_out won't divert a channel while one is. Calling tune_out on it again won't change "
|
|
186
|
-
+ 'that until the conversation ends, which happens only once the channel has been quiet for a while. Tune '
|
|
187
|
-
+ 'out a different channel, or ask whoever runs this host if this one should be diverted.',
|
|
188
|
-
};
|
|
189
|
-
}
|
|
190
|
-
const current = this.channelRegistry.getTuneOutState(serverId, channelId);
|
|
191
|
-
if (current)
|
|
192
|
-
return { ok: false, error: alreadyTunedOutText(this.shown(serverId, channelId), current.params), alreadyTunedOut: true };
|
|
193
|
-
// A tool's input reaches here as the model wrote it, and the store can't
|
|
194
|
-
// keep a NaN or an Infinity: its append would throw after the registry
|
|
195
|
-
// had marked the channel tuned out. So each option is read as a number
|
|
196
|
-
// before anything changes, a numeric string included, as the sleep tool
|
|
197
|
-
// reads its seconds; null counts as left out. A value that gives no
|
|
198
|
-
// finite number is refused.
|
|
199
|
-
const leftOut = {
|
|
200
|
-
durationSeconds: 'to stay tuned out until you cancel',
|
|
201
|
-
cadenceSeconds: `for the default, ${TUNE_OUT_DEFAULTS.cadenceSeconds}`,
|
|
202
|
-
backlogCap: `for the default, ${TUNE_OUT_DEFAULTS.backlogCap}`,
|
|
203
|
-
maxWakes: `for the default, ${TUNE_OUT_DEFAULTS.maxWakes}`,
|
|
204
|
-
};
|
|
308
|
+
/**
|
|
309
|
+
* The options a tune-out call gives, read as numbers before anything
|
|
310
|
+
* changes (F76). A tool's input reaches here as the model wrote it, and
|
|
311
|
+
* the store can't keep a NaN or an Infinity: its append would throw after
|
|
312
|
+
* the registry had marked the channel tuned out. So each option is read
|
|
313
|
+
* as a number first, a numeric string included, as the sleep tool reads
|
|
314
|
+
* its seconds; null counts as left out. A value that gives no finite
|
|
315
|
+
* number is refused, naming the option and, where it can be left out,
|
|
316
|
+
* what leaving it out means; so is a duration whose end time is too far
|
|
317
|
+
* off to store. `now` is the clock the end time was counted from. One
|
|
318
|
+
* rule for a channel's tune-out and the all-except hold.
|
|
319
|
+
*/
|
|
320
|
+
readOptions(opts, leftOut) {
|
|
205
321
|
const given = {};
|
|
206
322
|
for (const name of Object.keys(leftOut)) {
|
|
207
323
|
const value = opts[name];
|
|
@@ -215,21 +331,63 @@ export class TuneOutCoordinator {
|
|
|
215
331
|
return {
|
|
216
332
|
ok: false,
|
|
217
333
|
error: `Nothing was tuned out: ${name} must be a finite number${name.endsWith('Seconds') ? ' of seconds' : ''}, `
|
|
218
|
-
+ `and it was ${got}
|
|
334
|
+
+ `and it was ${got}.${leftOut[name] ? ` Leave it out ${leftOut[name]}.` : ''}`,
|
|
219
335
|
};
|
|
220
336
|
}
|
|
221
337
|
given[name] = n;
|
|
222
338
|
}
|
|
339
|
+
const now = Date.now();
|
|
223
340
|
const expiresAtMs = given.durationSeconds === undefined
|
|
224
341
|
? undefined
|
|
225
|
-
:
|
|
342
|
+
: now + Math.max(60, given.durationSeconds) * 1000;
|
|
226
343
|
if (expiresAtMs !== undefined && !Number.isFinite(expiresAtMs)) {
|
|
227
344
|
return {
|
|
228
345
|
ok: false,
|
|
229
|
-
error: `Nothing was tuned out: durationSeconds ${given.durationSeconds} is longer than an end time can be kept
|
|
230
|
-
+ `Leave it out ${leftOut.durationSeconds}
|
|
346
|
+
error: `Nothing was tuned out: durationSeconds ${given.durationSeconds} is longer than an end time can be kept.`
|
|
347
|
+
+ (leftOut.durationSeconds ? ` Leave it out ${leftOut.durationSeconds}.` : ''),
|
|
348
|
+
};
|
|
349
|
+
}
|
|
350
|
+
return { ok: true, given, now, expiresAtMs };
|
|
351
|
+
}
|
|
352
|
+
enter(serverId, channelId, opts, source) {
|
|
353
|
+
// No reader (issue #232 §3.3): a silent hold, where the host opted into
|
|
354
|
+
// one. Nothing summarizes, nothing wakes, mentions are still
|
|
355
|
+
// acknowledged, the backlog is released on cancel; the resident is told
|
|
356
|
+
// so in the tool result. A host that didn't opt in has no tune_out
|
|
357
|
+
// without a reader.
|
|
358
|
+
if (!this.readerAvailable() && this.hooks.holdWithoutReader?.() !== true) {
|
|
359
|
+
return {
|
|
360
|
+
ok: false,
|
|
361
|
+
error: 'Nothing was tuned out: this host has no subconscious resident to watch a channel, so tune_out '
|
|
362
|
+
+ "isn't available here, and calling it again won't change that. If you need channels diverted, ask "
|
|
363
|
+
+ 'whoever runs this host.',
|
|
231
364
|
};
|
|
232
365
|
}
|
|
366
|
+
if (this.hooks.isForkBound({ serverId, channelId })) {
|
|
367
|
+
return {
|
|
368
|
+
ok: false,
|
|
369
|
+
error: `Nothing changed: a conversation is bound to ${this.quotedShown(serverId, channelId)}, so its messages go to that `
|
|
370
|
+
+ "conversation, and tune_out won't divert a channel while one is. Calling tune_out on it again won't change "
|
|
371
|
+
+ 'that until the conversation ends, which happens only once the channel has been quiet for a while. Tune '
|
|
372
|
+
+ 'out a different channel, or ask whoever runs this host if this one should be diverted.',
|
|
373
|
+
};
|
|
374
|
+
}
|
|
375
|
+
const current = this.channelRegistry.getTuneOutState(serverId, channelId);
|
|
376
|
+
if (current)
|
|
377
|
+
return { ok: false, error: alreadyTunedOutText(this.quotedShown(serverId, channelId), current.params), alreadyTunedOut: true };
|
|
378
|
+
const scope = this.getAllExcept();
|
|
379
|
+
if (scope && scope.params.except.serverId === serverId && scope.params.except.channelId === channelId) {
|
|
380
|
+
return { ok: false, error: `channel ${this.quotedShown(serverId, channelId)} is the excepted channel of the active all-except hold; cancel that first` };
|
|
381
|
+
}
|
|
382
|
+
const read = this.readOptions(opts, {
|
|
383
|
+
durationSeconds: 'to stay tuned out until you cancel',
|
|
384
|
+
cadenceSeconds: `for the default, ${TUNE_OUT_DEFAULTS.cadenceSeconds}`,
|
|
385
|
+
backlogCap: `for the default, ${TUNE_OUT_DEFAULTS.backlogCap}`,
|
|
386
|
+
maxWakes: `for the default, ${TUNE_OUT_DEFAULTS.maxWakes}`,
|
|
387
|
+
});
|
|
388
|
+
if (!read.ok)
|
|
389
|
+
return read;
|
|
390
|
+
const { given, expiresAtMs } = read;
|
|
233
391
|
const params = {
|
|
234
392
|
epochId: randomUUID(),
|
|
235
393
|
cadenceSeconds: Math.max(30, given.cadenceSeconds ?? TUNE_OUT_DEFAULTS.cadenceSeconds),
|
|
@@ -249,10 +407,17 @@ export class TuneOutCoordinator {
|
|
|
249
407
|
const oldest = this.listActive().reduce((min, e) => Math.min(min, e.params.startedAtSequence), params.startedAtSequence);
|
|
250
408
|
this.hooks.setSubconsciousAnchor(oldest);
|
|
251
409
|
this.divertedSinceInvocation.set(this.key(serverId, channelId), 0);
|
|
252
|
-
this.
|
|
253
|
-
|
|
410
|
+
if (this.readerAvailable())
|
|
411
|
+
this.startCadence(serverId, channelId, params.cadenceSeconds);
|
|
412
|
+
this.hooks.emitTrace({
|
|
413
|
+
type: 'tune-out:entered', serverId, channelId, epochId: params.epochId, reader: this.readerAvailable(),
|
|
414
|
+
});
|
|
254
415
|
return { ok: true, params };
|
|
255
416
|
}
|
|
417
|
+
/** Whether a reader (persistent subconscious or reader forks) attends holds. */
|
|
418
|
+
hasReader() {
|
|
419
|
+
return this.readerAvailable();
|
|
420
|
+
}
|
|
256
421
|
/**
|
|
257
422
|
* End a tune-out: durable flip, system-framed backlog dump into the
|
|
258
423
|
* resident's window (capped), lifecycle notice, one wake for the
|
|
@@ -260,11 +425,15 @@ export class TuneOutCoordinator {
|
|
|
260
425
|
* cancel_tuneout call) — delivered verbatim under its name, never
|
|
261
426
|
* synthesized here.
|
|
262
427
|
*/
|
|
263
|
-
cancel(serverId, channelId, source, reason, subconsciousNote
|
|
264
|
-
|
|
428
|
+
cancel(serverId, channelId, source, reason, subconsciousNote,
|
|
429
|
+
/** `reader: 'forks'`: the reader fork whose note this is. */
|
|
430
|
+
noteAuthor,
|
|
431
|
+
/** The lifecycle state the channel returns to (a tool close ends in 'closed'). */
|
|
432
|
+
nextState = 'open') {
|
|
433
|
+
const ended = this.channelRegistry.cancelTuneOut(serverId, channelId, nextState, source);
|
|
265
434
|
if (!ended) {
|
|
266
435
|
// Its reader is the resident's tune_out: cancel_tuneout finds the channel first.
|
|
267
|
-
return { ok: false, error: this.notTunedOut(this.
|
|
436
|
+
return { ok: false, error: this.notTunedOut(this.quotedShown(serverId, channelId), 'you') };
|
|
268
437
|
}
|
|
269
438
|
this.clearTimers(serverId, channelId);
|
|
270
439
|
this.divertedSinceInvocation.delete(this.key(serverId, channelId));
|
|
@@ -284,22 +453,23 @@ export class TuneOutCoordinator {
|
|
|
284
453
|
// Whole messages: a cap below one shows none, where slice(-0.5) would
|
|
285
454
|
// start at 0 and take them all.
|
|
286
455
|
const cap = Math.floor(ended.params.backlogCap);
|
|
287
|
-
const authorOf = (m) => m.metadata?.author?.name ?? m.participant;
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
};
|
|
456
|
+
const authorOf = (m) => suppliedValue(m.metadata?.author?.name ?? m.participant);
|
|
457
|
+
// A line names its author as the resident knows them and marks what a
|
|
458
|
+
// text line can't carry (`[image]`), so the dump says what it leaves out.
|
|
459
|
+
const lineOf = renderHeldLine;
|
|
460
|
+
// The tool the truncation note names (#232 gap 11): the one the resident
|
|
461
|
+
// has, when the host says; main's `fetch_history` where no host says.
|
|
462
|
+
const historyTool = this.hooks.historyTool ? this.hooks.historyTool() : 'fetch_history';
|
|
295
463
|
// The channel as the resident and the subconscious are shown it.
|
|
296
464
|
const name = this.shown(serverId, channelId);
|
|
297
|
-
const lifecycle = `[
|
|
465
|
+
const lifecycle = `[${NOTICE_TAG.tuneOut}: ${name} cancelled — ${reason}, ${ended.wakeCount} wake${ended.wakeCount === 1 ? '' : 's'}]`;
|
|
298
466
|
const render = (lines, truncated) => {
|
|
299
467
|
const attrs = [
|
|
300
|
-
`channel
|
|
468
|
+
`channel=${this.quotedShown(serverId, channelId)}`,
|
|
301
469
|
`messages=${backlog.length}`,
|
|
302
|
-
...(truncated > 0
|
|
470
|
+
...(truncated > 0
|
|
471
|
+
? [`truncated=${truncated} (oldest; ${historyTool ? `${historyTool} covers the rest` : 'not delivered'})`]
|
|
472
|
+
: []),
|
|
303
473
|
];
|
|
304
474
|
return `${lifecycle}\n\n<tuned-out-backlog ${attrs.join(' ')}>\n${lines.join('\n')}\n</tuned-out-backlog>`;
|
|
305
475
|
};
|
|
@@ -341,7 +511,7 @@ export class TuneOutCoordinator {
|
|
|
341
511
|
// What of the newest line's text fits beside the frame and the mark. A
|
|
342
512
|
// cut shows some of it or none: a room under one character, or one
|
|
343
513
|
// that would split a surrogate pair, leaves the head empty.
|
|
344
|
-
const head =
|
|
514
|
+
const head = cutToFit(lines.at(-1) ?? '', room - frameShowing(1) - CUT_MARK.length);
|
|
345
515
|
if (kept === 0 && head !== '') {
|
|
346
516
|
lines = [head + CUT_MARK];
|
|
347
517
|
shown = shown.slice(-1);
|
|
@@ -365,6 +535,8 @@ export class TuneOutCoordinator {
|
|
|
365
535
|
];
|
|
366
536
|
// Host-framed system artifacts — never voiced as anyone.
|
|
367
537
|
this.hooks.addMessage('user', [{ type: 'text', text: render(lines, truncated) }], { system: true, kind: 'tune-out-cancel', channelId, epochId });
|
|
538
|
+
// The epoch is already ended durably; the release must be as durable.
|
|
539
|
+
this.hooks.commitDeliveries?.();
|
|
368
540
|
// The subconscious's own words, under its own name, verbatim.
|
|
369
541
|
const subName = this.hooks.subconsciousName();
|
|
370
542
|
if (subconsciousNote && subName) {
|
|
@@ -373,6 +545,11 @@ export class TuneOutCoordinator {
|
|
|
373
545
|
// reads (repinChannel), where another server's channel can share the id.
|
|
374
546
|
{ kind: 'subconscious-note', channelId, serverId, epochId });
|
|
375
547
|
}
|
|
548
|
+
else if (subconsciousNote && noteAuthor && this.hooks.deliverFromReader) {
|
|
549
|
+
// A reader fork's note: attributed mail, under the fork's name and
|
|
550
|
+
// incarnation, never the resident's voice.
|
|
551
|
+
this.hooks.deliverFromReader(noteAuthor, [{ type: 'text', text: subconsciousNote }], { kind: 'subconscious-note', channelId, epochId });
|
|
552
|
+
}
|
|
376
553
|
const primary = this.hooks.primaryName();
|
|
377
554
|
if (primary) {
|
|
378
555
|
this.hooks.requestInference(primary, `tune-out cancelled (${reason})`, 'tune-out');
|
|
@@ -394,7 +571,7 @@ export class TuneOutCoordinator {
|
|
|
394
571
|
const heldNote = heldForReport.length > 0
|
|
395
572
|
? ` Still held at the cancel, so your view may not have them yet: the ${heldForReport.length} message${heldForReport.length === 1 ? '' : 's'} after this one.`
|
|
396
573
|
: '';
|
|
397
|
-
this.hooks.addMessage('user', [{ type: 'text', text: `[
|
|
574
|
+
this.hooks.addMessage('user', [{ type: 'text', text: `[${NOTICE_TAG.tuneOutCancelled}: ${this.shown(serverId, channelId)} — ${reason}.${truncNote}${heldNote}]` }], { system: true, kind: 'tune-out-cancel-report', channelId }, subName);
|
|
398
575
|
// Each held message is a row of its own, so a per-message cap cuts each
|
|
399
576
|
// one on its own, its author's label included, not the batch's newest.
|
|
400
577
|
for (const m of heldForReport) {
|
|
@@ -402,6 +579,34 @@ export class TuneOutCoordinator {
|
|
|
402
579
|
}
|
|
403
580
|
this.hooks.requestInference(subName, `tune-out cancelled: ${name}`, 'tune-out');
|
|
404
581
|
}
|
|
582
|
+
else if (!subName && this.forkReader) {
|
|
583
|
+
// Forks are the reader: one last fork for the epoch, handed what no
|
|
584
|
+
// fork has been handed yet, stored or still queued behind the
|
|
585
|
+
// resident's turn, plus the cancel notice; its report follows the dump.
|
|
586
|
+
// Once the epoch ends, a message still queued lands in the store
|
|
587
|
+
// view-filtered, where nothing else reads it, so it goes to this fork
|
|
588
|
+
// now. On a reader's own cancel, the reader has read what it was
|
|
589
|
+
// handed, so a fork follows only when messages arrived after that.
|
|
590
|
+
const stored = this.hooks.getStoredMessages().filter(ofEpoch);
|
|
591
|
+
const queued = this.queuedHeld(ofEpoch);
|
|
592
|
+
const rest = this.unhandedBacklog(this.handOffKey(epochId, serverId, channelId), stored, queued);
|
|
593
|
+
const unread = rest.backlog.length + rest.queued.length;
|
|
594
|
+
if (!selfCancel || unread > 0) {
|
|
595
|
+
const truncNote = truncated > 0
|
|
596
|
+
? ` ${truncated} of ${backlog.length} diverted messages, the oldest, weren't delivered raw to the resident.`
|
|
597
|
+
: '';
|
|
598
|
+
const lateNote = selfCancel
|
|
599
|
+
? ` ${unread === 1 ? 'This message' : `These ${unread} messages`} arrived after the reader that cancelled was handed its own.`
|
|
600
|
+
: '';
|
|
601
|
+
this.invokeReaderFork(serverId, channelId, epochId, 'cancel', `[${NOTICE_TAG.tuneOutCancelled}: ${name} — ${reason}.${truncNote}${lateNote}]`, stored, queued);
|
|
602
|
+
}
|
|
603
|
+
}
|
|
604
|
+
this.dropHandOffs(epochId);
|
|
605
|
+
this.dropLooks(epochId);
|
|
606
|
+
// Where the all-except hold still holds the channel, its own messages
|
|
607
|
+
// there that its reader hasn't looked at are counted again, as the
|
|
608
|
+
// channel's own tune-out's count stood in for theirs.
|
|
609
|
+
this.rebuildTally(serverId, channelId);
|
|
405
610
|
this.hooks.emitTrace({ type: 'tune-out:cancelled', serverId, channelId, epochId, reason, wakeCount: ended.wakeCount });
|
|
406
611
|
return { ok: true };
|
|
407
612
|
}
|
|
@@ -417,9 +622,355 @@ export class TuneOutCoordinator {
|
|
|
417
622
|
* suppression ack, possible auto-cancel).
|
|
418
623
|
*/
|
|
419
624
|
onIncoming(serverId, channelId, messageId, tags, authorId, gatePass = true) {
|
|
420
|
-
const
|
|
421
|
-
if (!
|
|
625
|
+
const hold = this.holdFor(serverId, channelId);
|
|
626
|
+
if (!hold)
|
|
422
627
|
return null;
|
|
628
|
+
this.recordHeld(serverId, channelId, messageId, tags, authorId, gatePass);
|
|
629
|
+
return hold;
|
|
630
|
+
}
|
|
631
|
+
/** The epoch holding this channel, or null. Pure: the admission stage's lookup. */
|
|
632
|
+
holdFor(serverId, channelId) {
|
|
633
|
+
// Precedence: a per-channel epoch keeps its own hold (cadence, budget,
|
|
634
|
+
// stamp); the all-except scope holds whatever else is not the exception.
|
|
635
|
+
const state = this.channelRegistry.getTuneOutState(serverId, channelId);
|
|
636
|
+
if (state)
|
|
637
|
+
return { epochId: state.params.epochId };
|
|
638
|
+
const scope = this.getAllExcept();
|
|
639
|
+
if (scope && !(scope.params.except.serverId === serverId && scope.params.except.channelId === channelId)) {
|
|
640
|
+
return { epochId: scope.params.epochId };
|
|
641
|
+
}
|
|
642
|
+
return null;
|
|
643
|
+
}
|
|
644
|
+
/** The channel unprefixed speech lands in while an all-except hold is active, with its server, else null. */
|
|
645
|
+
focusChannel() {
|
|
646
|
+
const except = this.getAllExcept()?.params.except;
|
|
647
|
+
return except ? { serverId: except.serverId, channelId: except.channelId } : null;
|
|
648
|
+
}
|
|
649
|
+
// ==========================================================================
|
|
650
|
+
// All-except scope
|
|
651
|
+
// ==========================================================================
|
|
652
|
+
get scopeStateId() {
|
|
653
|
+
return `tune-out/${this.hooks.primaryName() ?? 'default'}/all-except`;
|
|
654
|
+
}
|
|
655
|
+
getAllExcept() {
|
|
656
|
+
if (this.scopeCache !== undefined)
|
|
657
|
+
return this.scopeCache;
|
|
658
|
+
// A record that can't be read, or isn't a hold's, is not taken for no
|
|
659
|
+
// hold: the error goes to the caller and nothing is cached, so the next
|
|
660
|
+
// read tries again. At create() that refuses the start, as an
|
|
661
|
+
// unreadable registry does.
|
|
662
|
+
const raw = this.channelRegistry.readCoordinatorState(this.scopeStateId);
|
|
663
|
+
if (raw !== null && raw !== undefined && !(typeof raw === 'object' && raw.params && typeof raw.params.epochId === 'string')) {
|
|
664
|
+
throw new Error(`the all-except hold's stored record (${this.scopeStateId}) is not a hold's record; it was left as it is`);
|
|
665
|
+
}
|
|
666
|
+
this.scopeCache = raw ?? null;
|
|
667
|
+
return this.scopeCache;
|
|
668
|
+
}
|
|
669
|
+
writeScope(state) {
|
|
670
|
+
// Durable first: a write that fails leaves memory as the store has it.
|
|
671
|
+
this.channelRegistry.writeCoordinatorState(this.scopeStateId, state);
|
|
672
|
+
this.scopeCache = state;
|
|
673
|
+
}
|
|
674
|
+
enterAllExcept(except, opts, source) {
|
|
675
|
+
const read = this.readOptions(opts, {
|
|
676
|
+
durationSeconds: null,
|
|
677
|
+
cadenceSeconds: `for the default, ${TUNE_OUT_DEFAULTS.cadenceSeconds}`,
|
|
678
|
+
backlogCap: `for the default, ${TUNE_OUT_DEFAULTS.backlogCap}`,
|
|
679
|
+
maxWakes: `for the default, ${TUNE_OUT_DEFAULTS.maxWakes}`,
|
|
680
|
+
});
|
|
681
|
+
if (!read.ok)
|
|
682
|
+
return read;
|
|
683
|
+
const { given, expiresAtMs } = read;
|
|
684
|
+
if (expiresAtMs === undefined) {
|
|
685
|
+
return { ok: false, error: 'an all-except hold needs `durationSeconds`: it always ends on its own' };
|
|
686
|
+
}
|
|
687
|
+
if (this.getAllExcept()) {
|
|
688
|
+
return { ok: false, error: 'an all-except hold is already active (cancel it first)' };
|
|
689
|
+
}
|
|
690
|
+
if (this.channelRegistry.getTuneOutState(except.serverId, except.channelId)) {
|
|
691
|
+
return { ok: false, error: `channel ${except.channelId} is tuned out; it cannot be the exception` };
|
|
692
|
+
}
|
|
693
|
+
if (this.hooks.isForkBound(except)) {
|
|
694
|
+
return { ok: false, error: `channel ${except.channelId} is bound to a conversation fork` };
|
|
695
|
+
}
|
|
696
|
+
const params = {
|
|
697
|
+
epochId: randomUUID(),
|
|
698
|
+
except,
|
|
699
|
+
cadenceSeconds: Math.max(30, given.cadenceSeconds ?? TUNE_OUT_DEFAULTS.cadenceSeconds),
|
|
700
|
+
// Whole messages, as a channel's cap is counted: a cap below one shows
|
|
701
|
+
// none, where slice(-0.5) would take them all.
|
|
702
|
+
backlogCap: Math.max(0, Math.floor(given.backlogCap ?? TUNE_OUT_DEFAULTS.backlogCap)),
|
|
703
|
+
maxWakes: Math.max(1, given.maxWakes ?? TUNE_OUT_DEFAULTS.maxWakes),
|
|
704
|
+
startedAtSequence: this.hooks.currentSequence(),
|
|
705
|
+
startedAtMs: read.now,
|
|
706
|
+
expiresAtMs,
|
|
707
|
+
source,
|
|
708
|
+
};
|
|
709
|
+
this.writeScope({ params, wakeCount: 0 });
|
|
710
|
+
const oldest = this.listActive().reduce((min, e) => Math.min(min, e.params.startedAtSequence), params.startedAtSequence);
|
|
711
|
+
this.hooks.setSubconsciousAnchor(oldest);
|
|
712
|
+
this.armScopeTimers(params);
|
|
713
|
+
this.hooks.emitTrace({
|
|
714
|
+
type: 'tune-out:entered', serverId: except.serverId, channelId: except.channelId, epochId: params.epochId,
|
|
715
|
+
scope: 'all-except', reader: this.readerAvailable(), expiresAtMs: params.expiresAtMs,
|
|
716
|
+
});
|
|
717
|
+
const minutes = Math.max(1, Math.round((params.expiresAtMs - params.startedAtMs) / 60_000));
|
|
718
|
+
const until = new Date(params.expiresAtMs).toISOString().slice(11, 16);
|
|
719
|
+
this.announce(except, params.epochId, 'entered', `[${NOTICE_TAG.focus}: ${this.hooks.primaryName() ?? 'the resident'} is here for ${minutes} min, until ${until} UTC; other channels are held meanwhile.]`);
|
|
720
|
+
return { ok: true, params };
|
|
721
|
+
}
|
|
722
|
+
/** Whether entry and release of the all-except scope are announced in the excepted channel. */
|
|
723
|
+
announces() {
|
|
724
|
+
return typeof this.hooks.announce === 'function';
|
|
725
|
+
}
|
|
726
|
+
/**
|
|
727
|
+
* The excepted channel hears the scope open and close: one bracketed line
|
|
728
|
+
* under the resident's name, posted through the same path as a publish.
|
|
729
|
+
* Fire-and-forget; the outcome is traced, never awaited by the epoch flip.
|
|
730
|
+
*/
|
|
731
|
+
announce(target, epochId, kind, text) {
|
|
732
|
+
if (!this.hooks.announce)
|
|
733
|
+
return;
|
|
734
|
+
const base = { serverId: target.serverId, channelId: target.channelId, epochId, kind };
|
|
735
|
+
this.hooks.announce(target.serverId, target.channelId, text).then((r) => this.hooks.emitTrace(r.success
|
|
736
|
+
? { type: 'tune-out:announced', ...base }
|
|
737
|
+
: { type: 'tune-out:announce-failed', ...base, error: r.error ?? 'publish failed' }), (err) => this.hooks.emitTrace({ type: 'tune-out:announce-failed', ...base, error: err.message }));
|
|
738
|
+
}
|
|
739
|
+
/** The scope's end time and cadence, on timers no longer than one holds
|
|
740
|
+
* (deadline-timer), as a channel's tune-out arms its own. */
|
|
741
|
+
armScopeTimers(params) {
|
|
742
|
+
const key = TuneOutCoordinator.SCOPE_KEY;
|
|
743
|
+
const expiry = this.expiryTimers.get(key);
|
|
744
|
+
if (expiry)
|
|
745
|
+
clearTimeout(expiry);
|
|
746
|
+
// As a channel's timers: the next turn is armed before this one's work,
|
|
747
|
+
// and a throw is reported (timerFailed) rather than left to end the host.
|
|
748
|
+
const { serverId: exceptServer, channelId: exceptChannel } = params.except;
|
|
749
|
+
const holdExpiry = (timer) => { this.expiryTimers.set(key, timer); };
|
|
750
|
+
const end = () => {
|
|
751
|
+
try {
|
|
752
|
+
holdExpiry(setTimeout(end, EXPIRY_RETRY_MS));
|
|
753
|
+
if (!this.cancelAllExcept('duration', 'duration elapsed').ok)
|
|
754
|
+
this.clearScopeTimers();
|
|
755
|
+
}
|
|
756
|
+
catch (err) {
|
|
757
|
+
this.timerFailed('expiry', exceptServer, exceptChannel, err);
|
|
758
|
+
}
|
|
759
|
+
};
|
|
760
|
+
armAt(params.expiresAtMs, holdExpiry, end);
|
|
761
|
+
if (!this.readerAvailable())
|
|
762
|
+
return;
|
|
763
|
+
const cadence = this.cadenceTimers.get(key);
|
|
764
|
+
if (cadence)
|
|
765
|
+
clearTimeout(cadence);
|
|
766
|
+
const hold = (timer) => { this.cadenceTimers.set(key, timer); };
|
|
767
|
+
const tick = () => {
|
|
768
|
+
try {
|
|
769
|
+
const scope = this.getAllExcept();
|
|
770
|
+
if (!scope)
|
|
771
|
+
return;
|
|
772
|
+
armAfter(params.cadenceSeconds * 1000, hold, tick);
|
|
773
|
+
// One look per held channel with new traffic since the last look.
|
|
774
|
+
for (const [channelKey, diverted] of this.divertedSinceInvocation) {
|
|
775
|
+
if (diverted <= 0)
|
|
776
|
+
continue;
|
|
777
|
+
const [serverId, channelId] = channelKey.split('\0');
|
|
778
|
+
if (this.channelRegistry.getTuneOutState(serverId, channelId))
|
|
779
|
+
continue; // a per-channel epoch's own cadence
|
|
780
|
+
this.invokeSubconscious(serverId, channelId, 'cadence', diverted);
|
|
781
|
+
}
|
|
782
|
+
}
|
|
783
|
+
catch (err) {
|
|
784
|
+
this.timerFailed('cadence', exceptServer, exceptChannel, err);
|
|
785
|
+
}
|
|
786
|
+
};
|
|
787
|
+
armAfter(params.cadenceSeconds * 1000, hold, tick);
|
|
788
|
+
}
|
|
789
|
+
clearScopeTimers() {
|
|
790
|
+
const key = TuneOutCoordinator.SCOPE_KEY;
|
|
791
|
+
const cadence = this.cadenceTimers.get(key);
|
|
792
|
+
if (cadence)
|
|
793
|
+
clearTimeout(cadence);
|
|
794
|
+
this.cadenceTimers.delete(key);
|
|
795
|
+
const expiry = this.expiryTimers.get(key);
|
|
796
|
+
if (expiry)
|
|
797
|
+
clearTimeout(expiry);
|
|
798
|
+
this.expiryTimers.delete(key);
|
|
799
|
+
}
|
|
800
|
+
/** Channels held by the scope (not by their own epoch) with the count held under it. */
|
|
801
|
+
scopeHeldCounts(epochId) {
|
|
802
|
+
const counts = new Map();
|
|
803
|
+
const all = [...this.hooks.getStoredMessages(), ...(this.hooks.getDeferredMessages?.() ?? [])];
|
|
804
|
+
for (const m of all) {
|
|
805
|
+
const meta = m.metadata;
|
|
806
|
+
if (meta?.tuneOut?.epochId !== epochId)
|
|
807
|
+
continue;
|
|
808
|
+
const channelId = typeof meta.channelId === 'string' ? meta.channelId : '(unknown channel)';
|
|
809
|
+
const serverId = typeof meta.serverId === 'string' ? meta.serverId : '';
|
|
810
|
+
const k = this.key(serverId, channelId);
|
|
811
|
+
const entry = counts.get(k) ?? { serverId, channelId, count: 0 };
|
|
812
|
+
entry.count += 1;
|
|
813
|
+
counts.set(k, entry);
|
|
814
|
+
}
|
|
815
|
+
return counts;
|
|
816
|
+
}
|
|
817
|
+
/**
|
|
818
|
+
* End the all-except hold: durable flip, one release notice with a
|
|
819
|
+
* per-channel backlog (each capped), the reader's note if any, one wake
|
|
820
|
+
* for the resident, and the reader's own look at what it had not seen.
|
|
821
|
+
*/
|
|
822
|
+
cancelAllExcept(source, reason, note, noteAuthor) {
|
|
823
|
+
const scope = this.getAllExcept();
|
|
824
|
+
if (!scope)
|
|
825
|
+
return { ok: false, error: 'no all-except hold is active' };
|
|
826
|
+
const { epochId, except, backlogCap } = scope.params;
|
|
827
|
+
const ofEpoch = (m) => m.metadata?.tuneOut?.epochId === epochId;
|
|
828
|
+
const all = [...this.hooks.getStoredMessages().filter(ofEpoch), ...(this.hooks.getDeferredMessages?.() ?? []).filter(ofEpoch)];
|
|
829
|
+
const byChannel = new Map();
|
|
830
|
+
for (const m of all) {
|
|
831
|
+
const meta = m.metadata;
|
|
832
|
+
const serverId = meta?.serverId ?? '';
|
|
833
|
+
const channelId = meta?.channelId ?? '(unknown channel)';
|
|
834
|
+
const k = this.key(serverId, channelId);
|
|
835
|
+
const entry = byChannel.get(k) ?? { serverId, channelId, backlog: [] };
|
|
836
|
+
entry.backlog.push(m);
|
|
837
|
+
byChannel.set(k, entry);
|
|
838
|
+
}
|
|
839
|
+
const historyTool = this.hooks.historyTool?.() ?? null;
|
|
840
|
+
const dumps = [...byChannel.values()].map(({ serverId, channelId, backlog }) => {
|
|
841
|
+
// Floored here too: a hold stored before entry floored its cap can hold
|
|
842
|
+
// a fraction.
|
|
843
|
+
const cap = Math.floor(backlogCap);
|
|
844
|
+
const shown = cap > 0 ? backlog.slice(-cap) : [];
|
|
845
|
+
const truncated = backlog.length - shown.length;
|
|
846
|
+
const attrs = [
|
|
847
|
+
`channel=${quotedValue(this.shown(serverId, channelId))}`,
|
|
848
|
+
`messages=${backlog.length}`,
|
|
849
|
+
...(truncated > 0 ? [`truncated=${truncated} (oldest; ${historyTool ? `${historyTool} covers the rest` : 'not delivered'})`] : []),
|
|
850
|
+
];
|
|
851
|
+
return `<tuned-out-backlog ${attrs.join(' ')}>\n${shown.map(renderHeldLine).join('\n')}\n</tuned-out-backlog>`;
|
|
852
|
+
});
|
|
853
|
+
const summary = byChannel.size === 0
|
|
854
|
+
? 'Nothing was held.'
|
|
855
|
+
: `${all.length} message${all.length === 1 ? '' : 's'} held in ${byChannel.size} channel${byChannel.size === 1 ? '' : 's'}.`;
|
|
856
|
+
if (this.scopeReleased !== epochId) {
|
|
857
|
+
this.hooks.addMessage('user', [{ type: 'text', text: `[${NOTICE_TAG.tuneOut}: all channels except ${this.shown(except.serverId, except.channelId)} released — ${reason}, ${scope.wakeCount} wake${scope.wakeCount === 1 ? '' : 's'}]\n\n${summary}${dumps.length > 0 ? '\n\n' + dumps.join('\n\n') : ''}` }], { system: true, kind: 'tune-out-cancel', scope: 'all-except', channelId: except.channelId, epochId });
|
|
858
|
+
this.hooks.commitDeliveries?.();
|
|
859
|
+
this.scopeReleased = epochId;
|
|
860
|
+
}
|
|
861
|
+
// The release is recorded before the hold is: a failure past this point
|
|
862
|
+
// leaves the hold in force with its release already delivered. A retry in
|
|
863
|
+
// this process records only the hold's end; a restart between the two
|
|
864
|
+
// delivers the release again, where the other order lost it outright.
|
|
865
|
+
this.writeScope(null);
|
|
866
|
+
this.scopeReleased = undefined;
|
|
867
|
+
this.clearScopeTimers();
|
|
868
|
+
for (const [key, pending] of this.pendingWakes) {
|
|
869
|
+
const [serverId, channelId] = key.split('\0');
|
|
870
|
+
if (this.channelRegistry.getTuneOutState(serverId, channelId))
|
|
871
|
+
continue;
|
|
872
|
+
clearTimeout(pending.timer);
|
|
873
|
+
this.pendingWakes.delete(key);
|
|
874
|
+
}
|
|
875
|
+
const subName = this.hooks.subconsciousName();
|
|
876
|
+
if (note && subName) {
|
|
877
|
+
this.hooks.addMessage(subName, [{ type: 'text', text: note }], { kind: 'subconscious-note', epochId });
|
|
878
|
+
}
|
|
879
|
+
else if (note && noteAuthor && this.hooks.deliverFromReader) {
|
|
880
|
+
this.hooks.deliverFromReader(noteAuthor, [{ type: 'text', text: note }], { kind: 'subconscious-note', epochId });
|
|
881
|
+
}
|
|
882
|
+
const primary = this.hooks.primaryName();
|
|
883
|
+
if (primary)
|
|
884
|
+
this.hooks.requestInference(primary, `tune-out cancelled (${reason})`, 'tune-out');
|
|
885
|
+
const notice = `[${NOTICE_TAG.tuneOutCancelled}: all channels except ${this.shown(except.serverId, except.channelId)} — ${reason}.]`;
|
|
886
|
+
if (source !== 'subconscious' && subName) {
|
|
887
|
+
this.hooks.addMessage('user', [{ type: 'text', text: notice }], { system: true, kind: 'tune-out-cancel-report', scope: 'all-except' }, subName);
|
|
888
|
+
this.hooks.requestInference(subName, 'tune-out cancelled: all-except', 'tune-out');
|
|
889
|
+
}
|
|
890
|
+
else if (!subName && this.forkReader) {
|
|
891
|
+
// One last look per channel with messages no fork was handed, stored or
|
|
892
|
+
// still queued behind the resident's turn. That holds for a reader's
|
|
893
|
+
// own release too: the reader that released read one channel's
|
|
894
|
+
// messages, and every other channel's would otherwise reach no reader.
|
|
895
|
+
// A channel is its server and id here, as the readers' bookkeeping is.
|
|
896
|
+
const channels = new Map();
|
|
897
|
+
for (const m of all) {
|
|
898
|
+
const meta = m.metadata;
|
|
899
|
+
const ref = { serverId: meta?.serverId ?? '', channelId: meta?.channelId ?? '(unknown channel)' };
|
|
900
|
+
channels.set(this.key(ref.serverId, ref.channelId), ref);
|
|
901
|
+
}
|
|
902
|
+
for (const { serverId, channelId } of channels.values()) {
|
|
903
|
+
const ofChannel = inChannelOf(serverId, channelId);
|
|
904
|
+
const inChannel = (m) => ofEpoch(m) && ofChannel(m);
|
|
905
|
+
const stored = this.hooks.getStoredMessages().filter(inChannel);
|
|
906
|
+
const queued = this.queuedHeld(inChannel);
|
|
907
|
+
const rest = this.unhandedBacklog(this.handOffKey(epochId, serverId, channelId), stored, queued);
|
|
908
|
+
if (rest.backlog.length + rest.queued.length > 0) {
|
|
909
|
+
this.invokeReaderFork(serverId, channelId, epochId, 'cancel', notice, stored, queued);
|
|
910
|
+
}
|
|
911
|
+
}
|
|
912
|
+
}
|
|
913
|
+
for (const key of this.divertedSinceInvocation.keys()) {
|
|
914
|
+
const [serverId, channelId] = key.split('\0');
|
|
915
|
+
if (!this.channelRegistry.getTuneOutState(serverId, channelId))
|
|
916
|
+
this.divertedSinceInvocation.delete(key);
|
|
917
|
+
}
|
|
918
|
+
this.dropHandOffs(epochId);
|
|
919
|
+
this.dropLooks(epochId);
|
|
920
|
+
this.hooks.emitTrace({ type: 'tune-out:cancelled', serverId: except.serverId, channelId: except.channelId, epochId, scope: 'all-except', reason, wakeCount: scope.wakeCount });
|
|
921
|
+
this.announce(except, epochId, 'released', `[${NOTICE_TAG.focus}: ${primary ?? 'the resident'} released — ${reason}.]`);
|
|
922
|
+
return { ok: true };
|
|
923
|
+
}
|
|
924
|
+
/** What is held right now — per-channel epochs and the scope — without releasing. */
|
|
925
|
+
check(opts = {}) {
|
|
926
|
+
const stored = this.hooks.getStoredMessages();
|
|
927
|
+
const deferred = this.hooks.getDeferredMessages?.() ?? [];
|
|
928
|
+
const countOf = (epochId) => [...stored, ...deferred].filter((m) => m.metadata?.tuneOut?.epochId === epochId).length;
|
|
929
|
+
const channels = this.listActive().map(({ serverId, channelId, params }) => ({
|
|
930
|
+
serverId, channelId, epochId: params.epochId, held: countOf(params.epochId),
|
|
931
|
+
...(params.expiresAtMs !== undefined ? { expiresAtMs: params.expiresAtMs } : {}),
|
|
932
|
+
}));
|
|
933
|
+
const scope = this.getAllExcept();
|
|
934
|
+
let allExcept = null;
|
|
935
|
+
if (scope) {
|
|
936
|
+
const held = {};
|
|
937
|
+
for (const { serverId, channelId, count } of this.scopeHeldCounts(scope.params.epochId).values())
|
|
938
|
+
held[this.shown(serverId, channelId)] = count;
|
|
939
|
+
allExcept = { epochId: scope.params.epochId, except: scope.params.except, expiresAtMs: scope.params.expiresAtMs, wakeCount: scope.wakeCount, held };
|
|
940
|
+
}
|
|
941
|
+
const result = { allExcept, channels };
|
|
942
|
+
if (opts.peek) {
|
|
943
|
+
const limit = Math.max(1, Math.min(50, opts.peekLimit ?? 5));
|
|
944
|
+
// Only what is held NOW: the channel's own epoch, or the scope's. A
|
|
945
|
+
// released epoch's messages are delivered, not held; showing them here
|
|
946
|
+
// would be a false declaration (first live run, 2026-10-12, finding B).
|
|
947
|
+
const active = new Set();
|
|
948
|
+
for (const e of channels) {
|
|
949
|
+
if (e.channelId === opts.peek.channelId && (!opts.peek.serverId || e.serverId === opts.peek.serverId))
|
|
950
|
+
active.add(e.epochId);
|
|
951
|
+
}
|
|
952
|
+
if (scope)
|
|
953
|
+
active.add(scope.params.epochId);
|
|
954
|
+
const lines = [...stored, ...deferred]
|
|
955
|
+
.filter((m) => {
|
|
956
|
+
const meta = m.metadata;
|
|
957
|
+
return typeof meta?.tuneOut?.epochId === 'string' && active.has(meta.tuneOut.epochId)
|
|
958
|
+
&& meta.channelId === opts.peek.channelId
|
|
959
|
+
&& (!opts.peek.serverId || meta.serverId === opts.peek.serverId);
|
|
960
|
+
})
|
|
961
|
+
.slice(-limit)
|
|
962
|
+
.map(renderHeldLine);
|
|
963
|
+
result.peek = lines;
|
|
964
|
+
}
|
|
965
|
+
return result;
|
|
966
|
+
}
|
|
967
|
+
/**
|
|
968
|
+
* Bookkeeping for one held message, after admission decided the hold:
|
|
969
|
+
* the cadence tally, the deterministic acknowledgement of a suppressed
|
|
970
|
+
* mention, and the reader wake when the resident's gate would have woken
|
|
971
|
+
* them (`gatePass` is that verdict, probed without side effects).
|
|
972
|
+
*/
|
|
973
|
+
recordHeld(serverId, channelId, messageId, tags, authorId, gatePass = true) {
|
|
423
974
|
const key = this.key(serverId, channelId);
|
|
424
975
|
this.divertedSinceInvocation.set(key, (this.divertedSinceInvocation.get(key) ?? 0) + 1);
|
|
425
976
|
// Wake classification: the resident's wake gate composes as a
|
|
@@ -439,10 +990,17 @@ export class TuneOutCoordinator {
|
|
|
439
990
|
// standing mute to its subject.
|
|
440
991
|
void this.acknowledgeSuppressed(serverId, channelId, messageId);
|
|
441
992
|
}
|
|
442
|
-
if (gatePass && (addressed || privileged)) {
|
|
993
|
+
if (gatePass && (addressed || privileged) && this.readerAvailable()) {
|
|
443
994
|
this.scheduleWakeInvocation(serverId, channelId);
|
|
444
995
|
}
|
|
445
|
-
|
|
996
|
+
}
|
|
997
|
+
/** Reader forks that reported through `deliver_summary` (so their trailing prose is not a second report). */
|
|
998
|
+
readerReports = new Set();
|
|
999
|
+
readerReported(reader) {
|
|
1000
|
+
return this.readerReports.has(reader);
|
|
1001
|
+
}
|
|
1002
|
+
forgetReader(reader) {
|
|
1003
|
+
this.readerReports.delete(reader);
|
|
446
1004
|
}
|
|
447
1005
|
async acknowledgeSuppressed(serverId, channelId, messageId) {
|
|
448
1006
|
try {
|
|
@@ -524,15 +1082,7 @@ export class TuneOutCoordinator {
|
|
|
524
1082
|
try {
|
|
525
1083
|
const entry = this.pendingWakes.get(key);
|
|
526
1084
|
this.pendingWakes.delete(key);
|
|
527
|
-
|
|
528
|
-
const counted = this.channelRegistry.recordTuneOutWake(serverId, channelId);
|
|
529
|
-
if (!counted)
|
|
530
|
-
return; // cancelled inside the window
|
|
531
|
-
if (counted.wakeCount > counted.params.maxWakes) {
|
|
532
|
-
this.cancel(serverId, channelId, 'tune-out-max-wakes', `wake budget exhausted (${counted.params.maxWakes})`);
|
|
533
|
-
return;
|
|
534
|
-
}
|
|
535
|
-
this.invokeSubconscious(serverId, channelId, 'wake', entry?.count ?? 1);
|
|
1085
|
+
this.fireWake(serverId, channelId, entry?.count ?? 1);
|
|
536
1086
|
}
|
|
537
1087
|
catch (err) {
|
|
538
1088
|
this.timerFailed('wake', serverId, channelId, err);
|
|
@@ -540,6 +1090,37 @@ export class TuneOutCoordinator {
|
|
|
540
1090
|
}, WAKE_COALESCE_MS);
|
|
541
1091
|
this.pendingWakes.set(key, { count: 1, timer });
|
|
542
1092
|
}
|
|
1093
|
+
/** One coalesced wake: counted durably against the epoch that holds the channel. */
|
|
1094
|
+
fireWake(serverId, channelId, count) {
|
|
1095
|
+
if (this.channelRegistry.getTuneOutState(serverId, channelId)) {
|
|
1096
|
+
// Count ONE durable wake per coalesced invocation.
|
|
1097
|
+
const counted = this.channelRegistry.recordTuneOutWake(serverId, channelId);
|
|
1098
|
+
if (!counted)
|
|
1099
|
+
return; // cancelled inside the window
|
|
1100
|
+
if (counted.wakeCount > counted.params.maxWakes) {
|
|
1101
|
+
this.cancel(serverId, channelId, 'tune-out-max-wakes', `wake budget exhausted (${counted.params.maxWakes})`);
|
|
1102
|
+
return;
|
|
1103
|
+
}
|
|
1104
|
+
this.invokeSubconscious(serverId, channelId, 'wake', count);
|
|
1105
|
+
return;
|
|
1106
|
+
}
|
|
1107
|
+
const scope = this.getAllExcept();
|
|
1108
|
+
if (!scope)
|
|
1109
|
+
return; // released inside the window
|
|
1110
|
+
// The all-except scope: exhausting the budget pauses the reader, it does
|
|
1111
|
+
// not end the hold (#232 §3.2 — the hold is the resident's bounded
|
|
1112
|
+
// commitment; the deadline ends it).
|
|
1113
|
+
const wakeCount = scope.wakeCount + 1;
|
|
1114
|
+
this.writeScope({ ...scope, wakeCount });
|
|
1115
|
+
if (wakeCount > scope.params.maxWakes) {
|
|
1116
|
+
this.hooks.emitTrace({
|
|
1117
|
+
type: 'tune-out:wake-budget-paused', epochId: scope.params.epochId, scope: 'all-except',
|
|
1118
|
+
serverId, channelId, wakeCount, maxWakes: scope.params.maxWakes,
|
|
1119
|
+
});
|
|
1120
|
+
return;
|
|
1121
|
+
}
|
|
1122
|
+
this.invokeSubconscious(serverId, channelId, 'wake', count);
|
|
1123
|
+
}
|
|
543
1124
|
/**
|
|
544
1125
|
* One subconscious turn: a system-framed trigger notice (bracket style —
|
|
545
1126
|
* what happened, never what to say) plus standing dispositions, then an
|
|
@@ -547,18 +1128,314 @@ export class TuneOutCoordinator {
|
|
|
547
1128
|
*/
|
|
548
1129
|
invokeSubconscious(serverId, channelId, trigger, count) {
|
|
549
1130
|
const subName = this.hooks.subconsciousName();
|
|
550
|
-
if (!subName)
|
|
1131
|
+
if (!subName && !this.forkReader)
|
|
551
1132
|
return;
|
|
552
1133
|
const key = this.key(serverId, channelId);
|
|
553
1134
|
const shown = this.shown(serverId, channelId);
|
|
554
1135
|
const notice = trigger === 'wake'
|
|
555
|
-
? `[
|
|
556
|
-
: `[
|
|
1136
|
+
? `[${NOTICE_TAG.tuneOutWake}: ${shown} — ${count} addressed message${count === 1 ? '' : 's'}]`
|
|
1137
|
+
: `[${NOTICE_TAG.tuneOutCadence}: ${shown} — ${count} diverted message${count === 1 ? '' : 's'} since your last look]`;
|
|
1138
|
+
if (!subName) {
|
|
1139
|
+
const hold = this.holdFor(serverId, channelId);
|
|
1140
|
+
if (!hold)
|
|
1141
|
+
return;
|
|
1142
|
+
const ofChannel = inChannelOf(serverId, channelId);
|
|
1143
|
+
const inChannel = (m) => m.metadata?.tuneOut?.epochId === hold.epochId && ofChannel(m);
|
|
1144
|
+
// Stored and still-queued alike: while the resident's turn runs, what
|
|
1145
|
+
// arrives waits in the deferred queue, and that is the traffic a reader
|
|
1146
|
+
// is there for.
|
|
1147
|
+
this.invokeReaderFork(serverId, channelId, hold.epochId, trigger, notice, this.hooks.getStoredMessages().filter(inChannel), this.queuedHeld(inChannel));
|
|
1148
|
+
// The count restarts once the fork has been handed what was held, as it
|
|
1149
|
+
// does below once the subconscious's turn has been asked for. Otherwise
|
|
1150
|
+
// every later cadence period still sees this one's count and derives a
|
|
1151
|
+
// fork with nothing new to read.
|
|
1152
|
+
this.divertedSinceInvocation.set(key, 0);
|
|
1153
|
+
return;
|
|
1154
|
+
}
|
|
557
1155
|
this.hooks.addMessage('user', [{ type: 'text', text: notice }], { system: true, kind: `tune-out-${trigger}`, channelId }, subName);
|
|
558
1156
|
this.hooks.requestInference(subName, `tune-out ${trigger}: ${shown}`, 'tune-out');
|
|
559
1157
|
// Counted from here only once the turn has been asked for, so a turn that
|
|
560
1158
|
// throws leaves its messages for the next period's turn.
|
|
561
1159
|
this.divertedSinceInvocation.set(key, 0);
|
|
1160
|
+
const epochId = this.holdFor(serverId, channelId)?.epochId;
|
|
1161
|
+
if (epochId)
|
|
1162
|
+
this.markLook(epochId, serverId, channelId);
|
|
1163
|
+
}
|
|
1164
|
+
/**
|
|
1165
|
+
* Count again, from the held messages, stored or still queued behind the
|
|
1166
|
+
* resident's turn, those the reader of the epoch holding this channel now
|
|
1167
|
+
* hasn't looked at: for reader forks, those no fork was handed; for the
|
|
1168
|
+
* persistent subconscious, the stored ones held since its last look
|
|
1169
|
+
* (lastLooks) and every queued one, which no view of it can show yet.
|
|
1170
|
+
* Nothing holding the channel leaves no count.
|
|
1171
|
+
*/
|
|
1172
|
+
rebuildTally(serverId, channelId) {
|
|
1173
|
+
const key = this.key(serverId, channelId);
|
|
1174
|
+
const hold = this.holdFor(serverId, channelId);
|
|
1175
|
+
if (!hold || !this.readerAvailable()) {
|
|
1176
|
+
this.divertedSinceInvocation.delete(key);
|
|
1177
|
+
return;
|
|
1178
|
+
}
|
|
1179
|
+
const ofChannel = inChannelOf(serverId, channelId);
|
|
1180
|
+
const inEpoch = (m) => m.metadata?.tuneOut?.epochId === hold.epochId && ofChannel(m);
|
|
1181
|
+
const rows = this.hooks.getStoredMessages().filter(inEpoch);
|
|
1182
|
+
const queued = this.queuedHeld(inEpoch);
|
|
1183
|
+
let count;
|
|
1184
|
+
if (this.forkReader) {
|
|
1185
|
+
const unread = this.unhandedBacklog(this.handOffKey(hold.epochId, serverId, channelId), rows, queued);
|
|
1186
|
+
count = unread.backlog.length + unread.queued.length;
|
|
1187
|
+
}
|
|
1188
|
+
else {
|
|
1189
|
+
const mark = this.lastLooks()?.[hold.epochId]?.[key];
|
|
1190
|
+
count = (mark === undefined ? rows.length : rows.filter((m) => m.sequence > mark).length) + queued.length;
|
|
1191
|
+
}
|
|
1192
|
+
this.divertedSinceInvocation.set(key, count);
|
|
1193
|
+
}
|
|
1194
|
+
get lastLooksStateId() {
|
|
1195
|
+
return `tune-out/${this.hooks.primaryName() ?? 'default'}/last-looks`;
|
|
1196
|
+
}
|
|
1197
|
+
/**
|
|
1198
|
+
* The stored last looks. Where they can't be read, none: every held row
|
|
1199
|
+
* counts, and nothing is cached, so the next read tries again. Nor is
|
|
1200
|
+
* anything written back over the stored record then (markLook, dropLooks,
|
|
1201
|
+
* pruneLooks), which would erase the other epochs' and channels' looks.
|
|
1202
|
+
*/
|
|
1203
|
+
lastLooks() {
|
|
1204
|
+
if (this.lastLooksCache !== undefined)
|
|
1205
|
+
return this.lastLooksCache;
|
|
1206
|
+
let raw;
|
|
1207
|
+
try {
|
|
1208
|
+
raw = this.channelRegistry.readCoordinatorState(this.lastLooksStateId);
|
|
1209
|
+
}
|
|
1210
|
+
catch (error) {
|
|
1211
|
+
console.error(`[tune-out] the subconscious's last looks (${this.lastLooksStateId}) could not be read:`, error);
|
|
1212
|
+
return undefined;
|
|
1213
|
+
}
|
|
1214
|
+
const looks = {};
|
|
1215
|
+
if (raw && typeof raw === 'object' && !Array.isArray(raw)) {
|
|
1216
|
+
for (const [epochId, channels] of Object.entries(raw)) {
|
|
1217
|
+
if (!channels || typeof channels !== 'object' || Array.isArray(channels))
|
|
1218
|
+
continue;
|
|
1219
|
+
const marks = Object.entries(channels).filter((e) => typeof e[1] === 'number');
|
|
1220
|
+
if (marks.length > 0)
|
|
1221
|
+
looks[epochId] = Object.fromEntries(marks);
|
|
1222
|
+
}
|
|
1223
|
+
}
|
|
1224
|
+
this.lastLooksCache = looks;
|
|
1225
|
+
return looks;
|
|
1226
|
+
}
|
|
1227
|
+
writeLooks(looks) {
|
|
1228
|
+
this.lastLooksCache = looks;
|
|
1229
|
+
try {
|
|
1230
|
+
this.channelRegistry.writeCoordinatorState(this.lastLooksStateId, looks);
|
|
1231
|
+
}
|
|
1232
|
+
catch (error) {
|
|
1233
|
+
// The look itself stands. After a restart, this look's messages would
|
|
1234
|
+
// count as unseen at the next one.
|
|
1235
|
+
console.error(`[tune-out] the subconscious's last looks (${this.lastLooksStateId}) could not be stored:`, error);
|
|
1236
|
+
}
|
|
1237
|
+
}
|
|
1238
|
+
markLook(epochId, serverId, channelId) {
|
|
1239
|
+
const looks = this.lastLooks();
|
|
1240
|
+
if (!looks)
|
|
1241
|
+
return;
|
|
1242
|
+
this.writeLooks({ ...looks, [epochId]: { ...looks[epochId], [this.key(serverId, channelId)]: this.hooks.currentSequence() } });
|
|
1243
|
+
}
|
|
1244
|
+
/** An ended epoch's last looks go with it. */
|
|
1245
|
+
dropLooks(epochId) {
|
|
1246
|
+
if (this.hooks.subconsciousName() == null)
|
|
1247
|
+
return;
|
|
1248
|
+
const looks = this.lastLooks();
|
|
1249
|
+
if (!looks || !(epochId in looks))
|
|
1250
|
+
return;
|
|
1251
|
+
const { [epochId]: _ended, ...rest } = looks;
|
|
1252
|
+
this.writeLooks(rest);
|
|
1253
|
+
}
|
|
1254
|
+
/** At boot: the last looks of epochs no longer active go. */
|
|
1255
|
+
pruneLooks() {
|
|
1256
|
+
if (this.hooks.subconsciousName() == null)
|
|
1257
|
+
return;
|
|
1258
|
+
const looks = this.lastLooks();
|
|
1259
|
+
if (!looks)
|
|
1260
|
+
return;
|
|
1261
|
+
const active = new Set(this.listActive().map((e) => e.params.epochId));
|
|
1262
|
+
const scope = this.getAllExcept();
|
|
1263
|
+
if (scope)
|
|
1264
|
+
active.add(scope.params.epochId);
|
|
1265
|
+
const kept = Object.fromEntries(Object.entries(looks).filter(([epochId]) => active.has(epochId)));
|
|
1266
|
+
if (Object.keys(kept).length !== Object.keys(looks).length)
|
|
1267
|
+
this.writeLooks(kept);
|
|
1268
|
+
}
|
|
1269
|
+
/**
|
|
1270
|
+
* `reader: 'forks'`: hand the framework one invocation. The backlog is
|
|
1271
|
+
* the epoch's held messages not yet handed to any fork — each is
|
|
1272
|
+
* delivered to exactly one reader — stored ones first, then those still
|
|
1273
|
+
* queued behind the resident's turn, plus the standing dispositions. A
|
|
1274
|
+
* cadence look with nothing new is skipped. True when a fork was asked for.
|
|
1275
|
+
*/
|
|
1276
|
+
invokeReaderFork(serverId, channelId, epochId, trigger, notice, epochBacklog, epochQueued = []) {
|
|
1277
|
+
if (!this.hooks.invokeReader)
|
|
1278
|
+
return false;
|
|
1279
|
+
const key = this.handOffKey(epochId, serverId, channelId);
|
|
1280
|
+
const { backlog, queued } = this.unhandedBacklog(key, epochBacklog, epochQueued);
|
|
1281
|
+
if (trigger === 'cadence' && backlog.length === 0 && queued.length === 0)
|
|
1282
|
+
return false;
|
|
1283
|
+
// The cursor only moves forward: a returned row handed again can be
|
|
1284
|
+
// behind it.
|
|
1285
|
+
const cursor = Math.max(this.readerCursor.get(key) ?? -1, ...backlog.map((m) => m.sequence));
|
|
1286
|
+
if (backlog.length > 0)
|
|
1287
|
+
this.readerCursor.set(key, cursor);
|
|
1288
|
+
const handed = this.readerHandedWrites.get(key) ?? new Set();
|
|
1289
|
+
for (const m of queued)
|
|
1290
|
+
handed.add(m.writeId);
|
|
1291
|
+
// A handed write whose row has landed behind the cursor can no longer be
|
|
1292
|
+
// handed by sequence, so its id has done its work.
|
|
1293
|
+
for (const m of epochBacklog) {
|
|
1294
|
+
const writeId = writeIdOf(m);
|
|
1295
|
+
if (writeId !== undefined && m.sequence <= cursor)
|
|
1296
|
+
handed.delete(writeId);
|
|
1297
|
+
}
|
|
1298
|
+
if (handed.size > 0)
|
|
1299
|
+
this.readerHandedWrites.set(key, handed);
|
|
1300
|
+
else
|
|
1301
|
+
this.readerHandedWrites.delete(key);
|
|
1302
|
+
const returned = this.readerReturned.get(key);
|
|
1303
|
+
if (returned) {
|
|
1304
|
+
for (const m of backlog) {
|
|
1305
|
+
returned.ids.delete(m.id);
|
|
1306
|
+
const writeId = writeIdOf(m);
|
|
1307
|
+
if (writeId !== undefined)
|
|
1308
|
+
returned.writeIds.delete(writeId);
|
|
1309
|
+
}
|
|
1310
|
+
for (const m of queued)
|
|
1311
|
+
returned.writeIds.delete(m.writeId);
|
|
1312
|
+
if (returned.ids.size === 0 && returned.writeIds.size === 0)
|
|
1313
|
+
this.readerReturned.delete(key);
|
|
1314
|
+
}
|
|
1315
|
+
const entries = Object.entries(this.readDispositions());
|
|
1316
|
+
this.hooks.invokeReader({
|
|
1317
|
+
serverId,
|
|
1318
|
+
channelId,
|
|
1319
|
+
epochId,
|
|
1320
|
+
trigger,
|
|
1321
|
+
notice,
|
|
1322
|
+
backlog,
|
|
1323
|
+
queued,
|
|
1324
|
+
dispositions: entries.length > 0 ? entries.map(([k, v]) => `- ${k}: ${v}`).join('\n') : null,
|
|
1325
|
+
});
|
|
1326
|
+
return true;
|
|
1327
|
+
}
|
|
1328
|
+
/**
|
|
1329
|
+
* What no reader fork has read yet, of the given held messages: the stored
|
|
1330
|
+
* ones past the epoch's cursor for the channel, less those a fork was handed while they
|
|
1331
|
+
* were still queued, plus those a failed fork returned, oldest first; then
|
|
1332
|
+
* the queued ones no fork was handed, or a failed fork returned.
|
|
1333
|
+
*/
|
|
1334
|
+
unhandedBacklog(key, stored, queued) {
|
|
1335
|
+
const cursor = this.readerCursor.get(key) ?? -1;
|
|
1336
|
+
const handed = this.readerHandedWrites.get(key);
|
|
1337
|
+
const returned = this.readerReturned.get(key);
|
|
1338
|
+
const wasReturned = (id, writeId) => returned !== undefined && ((id !== undefined && returned.ids.has(id)) || (writeId !== undefined && returned.writeIds.has(writeId)));
|
|
1339
|
+
const unread = (m) => {
|
|
1340
|
+
const writeId = writeIdOf(m);
|
|
1341
|
+
if (wasReturned(m.id, writeId))
|
|
1342
|
+
return true;
|
|
1343
|
+
return m.sequence > cursor && !(handed !== undefined && writeId !== undefined && handed.has(writeId));
|
|
1344
|
+
};
|
|
1345
|
+
return {
|
|
1346
|
+
backlog: stored.filter(unread).sort((a, b) => a.sequence - b.sequence),
|
|
1347
|
+
queued: queued.filter((m) => !handed?.has(m.writeId) || wasReturned(undefined, m.writeId)),
|
|
1348
|
+
};
|
|
1349
|
+
}
|
|
1350
|
+
/**
|
|
1351
|
+
* A reader fork that never read what it was handed: its derive failed, or
|
|
1352
|
+
* its run threw before it reported. While the epoch that held the
|
|
1353
|
+
* messages is still active, they go back to that epoch's backlog for the
|
|
1354
|
+
* channel, and its next invocation for the channel is handed them: the
|
|
1355
|
+
* scope's while the scope is active, though the channel's own tune-out
|
|
1356
|
+
* has taken the channel meanwhile, and a channel's own tune-out's while it
|
|
1357
|
+
* holds the channel. Once the epoch has ended, its cancel's last fork was
|
|
1358
|
+
* handed only what no fork had been, so a fork still running then is the
|
|
1359
|
+
* only reader its messages had: one late fork is handed them instead
|
|
1360
|
+
* (lateFork). Returns how many went back or to the late fork.
|
|
1361
|
+
*/
|
|
1362
|
+
readerFailed(invocation) {
|
|
1363
|
+
const { serverId, channelId, epochId } = invocation;
|
|
1364
|
+
const active = this.getAllExcept()?.params.epochId === epochId
|
|
1365
|
+
|| this.channelRegistry.getTuneOutState(serverId, channelId)?.params.epochId === epochId;
|
|
1366
|
+
if (!active)
|
|
1367
|
+
return this.lateFork(invocation);
|
|
1368
|
+
const key = this.handOffKey(epochId, serverId, channelId);
|
|
1369
|
+
const returned = this.readerReturned.get(key) ?? { ids: new Set(), writeIds: new Set() };
|
|
1370
|
+
for (const m of invocation.backlog)
|
|
1371
|
+
returned.ids.add(m.id);
|
|
1372
|
+
for (const m of invocation.queued)
|
|
1373
|
+
returned.writeIds.add(m.writeId);
|
|
1374
|
+
const count = invocation.backlog.length + invocation.queued.length;
|
|
1375
|
+
if (count > 0) {
|
|
1376
|
+
this.readerReturned.set(key, returned);
|
|
1377
|
+
// They count again toward the next cadence look of the epoch holding
|
|
1378
|
+
// the channel, which hands them back. Where another epoch holds it
|
|
1379
|
+
// now, they're counted again when the channel comes back to theirs
|
|
1380
|
+
// (rebuildTally), and its release hands them in any case.
|
|
1381
|
+
const tally = this.key(serverId, channelId);
|
|
1382
|
+
if (this.holdFor(serverId, channelId)?.epochId === epochId) {
|
|
1383
|
+
this.divertedSinceInvocation.set(tally, (this.divertedSinceInvocation.get(tally) ?? 0) + count);
|
|
1384
|
+
}
|
|
1385
|
+
}
|
|
1386
|
+
return count;
|
|
1387
|
+
}
|
|
1388
|
+
/**
|
|
1389
|
+
* A fork that failed after its epoch ended: one late fork is handed what it
|
|
1390
|
+
* was, with a notice saying a reader handed them failed after the tune-out
|
|
1391
|
+
* ended. Those still queued when it was handed that have landed since are
|
|
1392
|
+
* handed as stored. A late fork's own failure derives no other, so a
|
|
1393
|
+
* reader that keeps failing costs one more fork, not a chain of them.
|
|
1394
|
+
* Returns how many the late fork was handed.
|
|
1395
|
+
*/
|
|
1396
|
+
lateFork(invocation) {
|
|
1397
|
+
if (!this.hooks.invokeReader || this.lateForks.has(invocation))
|
|
1398
|
+
return 0;
|
|
1399
|
+
const { serverId, channelId, epochId } = invocation;
|
|
1400
|
+
const landed = new Map();
|
|
1401
|
+
for (const m of this.hooks.getStoredMessages()) {
|
|
1402
|
+
const writeId = writeIdOf(m);
|
|
1403
|
+
if (writeId !== undefined)
|
|
1404
|
+
landed.set(writeId, m);
|
|
1405
|
+
}
|
|
1406
|
+
const backlog = [...invocation.backlog, ...invocation.queued.flatMap((m) => landed.get(m.writeId) ?? [])]
|
|
1407
|
+
.sort((a, b) => a.sequence - b.sequence);
|
|
1408
|
+
const queued = invocation.queued.filter((m) => !landed.has(m.writeId));
|
|
1409
|
+
const count = backlog.length + queued.length;
|
|
1410
|
+
if (count === 0)
|
|
1411
|
+
return 0;
|
|
1412
|
+
const these = count === 1 ? 'This message was' : `These ${count} messages were`;
|
|
1413
|
+
const notice = `[${NOTICE_TAG.tuneOutCancelled}: ${this.shown(serverId, channelId)} — ${these} handed to a reader that `
|
|
1414
|
+
+ `failed after the tune-out ended, so no reader has read ${count === 1 ? 'it' : 'them'} yet.]`;
|
|
1415
|
+
const entries = Object.entries(this.readDispositions());
|
|
1416
|
+
const late = {
|
|
1417
|
+
serverId,
|
|
1418
|
+
channelId,
|
|
1419
|
+
epochId,
|
|
1420
|
+
trigger: 'cancel',
|
|
1421
|
+
notice,
|
|
1422
|
+
backlog,
|
|
1423
|
+
queued,
|
|
1424
|
+
dispositions: entries.length > 0 ? entries.map(([k, v]) => `- ${k}: ${v}`).join('\n') : null,
|
|
1425
|
+
};
|
|
1426
|
+
this.lateForks.add(late);
|
|
1427
|
+
this.hooks.invokeReader(late);
|
|
1428
|
+
return count;
|
|
1429
|
+
}
|
|
1430
|
+
/**
|
|
1431
|
+
* The held messages still queued behind the resident's turn that `keep`
|
|
1432
|
+
* keeps, oldest first, with their write ids. One the host gives no id for
|
|
1433
|
+
* is left to reach a reader once it is stored: without the id, its stored
|
|
1434
|
+
* row couldn't be told from a message no reader has had.
|
|
1435
|
+
*/
|
|
1436
|
+
queuedHeld(keep) {
|
|
1437
|
+
return (this.hooks.getDeferredMessages?.() ?? [])
|
|
1438
|
+
.filter((m) => typeof m.writeId === 'string' && keep(m));
|
|
562
1439
|
}
|
|
563
1440
|
// ==========================================================================
|
|
564
1441
|
// Dispositions (standing notes, snapshot slot)
|
|
@@ -585,7 +1462,7 @@ export class TuneOutCoordinator {
|
|
|
585
1462
|
position: 'system',
|
|
586
1463
|
content: [{
|
|
587
1464
|
type: 'text',
|
|
588
|
-
text: `[
|
|
1465
|
+
text: `[${NOTICE_TAG.standingDispositions}]\n${entries.map(([k, v]) => `- ${k}: ${v}`).join('\n')}`,
|
|
589
1466
|
}],
|
|
590
1467
|
};
|
|
591
1468
|
}
|
|
@@ -629,7 +1506,12 @@ export class TuneOutCoordinator {
|
|
|
629
1506
|
// ==========================================================================
|
|
630
1507
|
async handleSubconsciousTool(name, input,
|
|
631
1508
|
/** The calling turn's own channels, for a call made inside it (the framework's callOwnChannels). */
|
|
632
|
-
own = []
|
|
1509
|
+
own = [],
|
|
1510
|
+
/** The calling agent: the persistent subconscious, or a reader fork. */
|
|
1511
|
+
caller,
|
|
1512
|
+
/** A reader fork, with the epoch it was derived to read, if any: it ends and posts only through that epoch's
|
|
1513
|
+
* hold (forkRefusal). The persistent subconscious, which reads every epoch, passes none. */
|
|
1514
|
+
fork) {
|
|
633
1515
|
switch (name) {
|
|
634
1516
|
case 'deliver_summary': {
|
|
635
1517
|
const text = String(input.text ?? '').trim();
|
|
@@ -643,20 +1525,22 @@ export class TuneOutCoordinator {
|
|
|
643
1525
|
};
|
|
644
1526
|
}
|
|
645
1527
|
const subName = this.hooks.subconsciousName();
|
|
646
|
-
|
|
1528
|
+
// Verbatim, under its own participant name, into the resident's window
|
|
1529
|
+
// (or, from a reader fork, as its attributed mail), tagged with the
|
|
1530
|
+
// channel the name means and its server, since the framework reads a
|
|
1531
|
+
// conversational row's channel (repinChannel). The name means what it
|
|
1532
|
+
// means to every channel tool: inside the calling turn, the id of one
|
|
1533
|
+
// of the turn's own channels means that channel, refused where its
|
|
1534
|
+
// server no longer registers it or the turn has channels with that id
|
|
1535
|
+
// on two servers (ownChannelFor); otherwise a name several registered
|
|
1536
|
+
// channels answer to is refused with them (sharedNameRefusalFor). So
|
|
1537
|
+
// no row is left for a re-pin to read as another server's channel. A
|
|
1538
|
+
// name no registered channel answers to is kept as given, with no
|
|
1539
|
+
// server, which a re-pin reads by name when it weighs the row, as it
|
|
1540
|
+
// reads any message without its server.
|
|
1541
|
+
if (!subName && !(caller && this.hooks.deliverFromReader)) {
|
|
647
1542
|
return { success: false, error: 'subconscious not configured', isError: true };
|
|
648
|
-
|
|
649
|
-
// tagged with the channel the name means and its server, since the
|
|
650
|
-
// framework reads a conversational row's channel (repinChannel). The
|
|
651
|
-
// name means what it means to every channel tool: inside the calling
|
|
652
|
-
// turn, the id of one of the turn's own channels means that channel,
|
|
653
|
-
// refused where its server no longer registers it or the turn has
|
|
654
|
-
// channels with that id on two servers (ownChannelFor); otherwise a
|
|
655
|
-
// name several registered channels answer to is refused with them
|
|
656
|
-
// (sharedNameRefusalFor). So no row is left for a re-pin to read as
|
|
657
|
-
// another server's channel. A name no registered channel answers to
|
|
658
|
-
// is kept as given, with no server, which a re-pin reads by name when
|
|
659
|
-
// it weighs the row, as it reads any message without its server.
|
|
1543
|
+
}
|
|
660
1544
|
const mine = this.channelRegistry.ownChannelFor(channelId, own, 'deliver');
|
|
661
1545
|
if (mine && 'error' in mine)
|
|
662
1546
|
return { success: false, error: mine.error, isError: true };
|
|
@@ -664,33 +1548,87 @@ export class TuneOutCoordinator {
|
|
|
664
1548
|
if (shared)
|
|
665
1549
|
return { success: false, error: shared, isError: true };
|
|
666
1550
|
const [named] = mine ? [mine.channel] : this.channelRegistry.channelsNamed(channelId);
|
|
667
|
-
|
|
1551
|
+
const metadata = {
|
|
668
1552
|
kind: 'subconscious-summary',
|
|
669
1553
|
...(named ? { channelId: named.channelId, serverId: named.serverId } : { channelId }),
|
|
670
|
-
}
|
|
1554
|
+
};
|
|
1555
|
+
if (subName) {
|
|
1556
|
+
this.hooks.addMessage(subName, [{ type: 'text', text }], metadata);
|
|
1557
|
+
return { success: true, data: { delivered: true } };
|
|
1558
|
+
}
|
|
1559
|
+
// A reader fork's report: attributed mail under its own name. The fork
|
|
1560
|
+
// counts as having reported only once the mail is held: a delivery
|
|
1561
|
+
// that throws is an error result to the fork, and its prose is then
|
|
1562
|
+
// still delivered as its report when it ends (#546, probe R14).
|
|
1563
|
+
this.hooks.deliverFromReader(caller, [{ type: 'text', text }], metadata);
|
|
1564
|
+
this.readerReports.add(caller);
|
|
671
1565
|
return { success: true, data: { delivered: true } };
|
|
672
1566
|
}
|
|
673
1567
|
case 'cancel_tuneout': {
|
|
674
1568
|
const name = String(input.channelId ?? '');
|
|
1569
|
+
const note = typeof input.text === 'string' && input.text.trim() ? input.text.trim() : undefined;
|
|
1570
|
+
const endScope = () => {
|
|
1571
|
+
const scope = this.getAllExcept();
|
|
1572
|
+
const refused = fork && scope
|
|
1573
|
+
? this.forkRefusal(fork, { epochId: scope.params.epochId }, 'cancel', "the all-except hold isn't the hold you were started to read")
|
|
1574
|
+
: undefined;
|
|
1575
|
+
if (refused)
|
|
1576
|
+
return { success: false, error: refused, isError: true };
|
|
1577
|
+
const result = this.cancelAllExcept('subconscious', 'subconscious judgment', note, caller);
|
|
1578
|
+
return result.ok
|
|
1579
|
+
? { success: true, data: { cancelled: true, scope: 'all-except' } }
|
|
1580
|
+
: { success: false, error: result.error, isError: true };
|
|
1581
|
+
};
|
|
1582
|
+
// A call naming the all-except scope ends that hold outright, as the
|
|
1583
|
+
// tool describes it and as the resident's tune_out cancel does: the
|
|
1584
|
+
// channel it names, tuned out on its own or not, doesn't turn it
|
|
1585
|
+
// into that channel's cancel, and with no hold it ends nothing.
|
|
1586
|
+
if (input.scope === 'all-except')
|
|
1587
|
+
return endScope();
|
|
1588
|
+
const serverId = typeof input.serverId === 'string' && input.serverId ? input.serverId : undefined;
|
|
675
1589
|
// The name means what it means to every channel tool, the
|
|
676
|
-
// resident's tune_out included:
|
|
677
|
-
//
|
|
678
|
-
//
|
|
1590
|
+
// resident's tune_out included: with a serverId, that server's
|
|
1591
|
+
// channel with the id; inside the calling turn, the id of one of the
|
|
1592
|
+
// turn's own channels means that channel (ownChannelFor); otherwise a
|
|
1593
|
+
// name several registered channels answer to picks none of them
|
|
679
1594
|
// (channelsNamed), whichever of them is tuned out, never taken to be
|
|
680
|
-
// the tuned-out one.
|
|
681
|
-
|
|
682
|
-
|
|
683
|
-
|
|
684
|
-
const
|
|
685
|
-
const
|
|
686
|
-
|
|
687
|
-
|
|
688
|
-
|
|
1595
|
+
// the tuned-out one. A name that picks no channel, such a name or one
|
|
1596
|
+
// of the turn's own channels that ownChannelFor refuses, is refused,
|
|
1597
|
+
// unless the call names the all-except scope, which ends that hold
|
|
1598
|
+
// below.
|
|
1599
|
+
const mine = serverId ? undefined : this.channelRegistry.ownChannelFor(name, own);
|
|
1600
|
+
const refusal = mine && 'error' in mine ? mine.error
|
|
1601
|
+
: serverId || mine ? undefined : this.channelRegistry.sharedNameRefusalFor(name);
|
|
1602
|
+
const named = serverId ? [{ serverId, channelId: name }]
|
|
1603
|
+
: mine && 'channel' in mine ? [mine.channel] : this.channelRegistry.channelsNamed(name);
|
|
1604
|
+
const channel = refusal ? undefined : named[0];
|
|
689
1605
|
if (!channel || !this.channelRegistry.getTuneOutState(channel.serverId, channel.channelId)) {
|
|
690
|
-
|
|
1606
|
+
// The reader keeps its latitude over the all-except hold too: a
|
|
1607
|
+
// channel it holds (or the scope named as the channel) ends the
|
|
1608
|
+
// scope. A call naming the scope "channel" ends only a channel's
|
|
1609
|
+
// own tune-out, so on a channel only the scope holds it ends
|
|
1610
|
+
// nothing.
|
|
1611
|
+
const scope = this.getAllExcept();
|
|
1612
|
+
const heldByScope = scope && (name === 'all-except'
|
|
1613
|
+
|| (channel !== undefined && this.holdFor(channel.serverId, channel.channelId)?.epochId === scope.params.epochId));
|
|
1614
|
+
if (!heldByScope)
|
|
1615
|
+
return { success: false, error: refusal ?? this.notTunedOut(JSON.stringify(name), 'the resident'), isError: true };
|
|
1616
|
+
if (input.scope === 'channel') {
|
|
1617
|
+
const shown = channel ? this.quotedShown(channel.serverId, channel.channelId) : JSON.stringify(name);
|
|
1618
|
+
return {
|
|
1619
|
+
success: false,
|
|
1620
|
+
error: `Nothing was cancelled: ${shown} isn't tuned out on its own, and scope "channel" ends only a channel's own `
|
|
1621
|
+
+ 'tune-out. The all-except hold holds it, and calling cancel_tuneout with scope "all-except" ends that hold.',
|
|
1622
|
+
isError: true,
|
|
1623
|
+
};
|
|
1624
|
+
}
|
|
1625
|
+
return endScope();
|
|
691
1626
|
}
|
|
692
|
-
const
|
|
693
|
-
const
|
|
1627
|
+
const held = this.channelRegistry.getTuneOutState(channel.serverId, channel.channelId);
|
|
1628
|
+
const refused = fork && this.forkRefusal(fork, { epochId: held.params.epochId }, 'cancel', `the tune-out on ${this.quotedShown(channel.serverId, channel.channelId)} isn't the hold you were started to read`);
|
|
1629
|
+
if (refused)
|
|
1630
|
+
return { success: false, error: refused, isError: true };
|
|
1631
|
+
const result = this.cancel(channel.serverId, channel.channelId, 'subconscious', 'subconscious judgment', note, caller);
|
|
694
1632
|
return result.ok
|
|
695
1633
|
? { success: true, data: { cancelled: true } }
|
|
696
1634
|
: { success: false, error: result.error, isError: true };
|
|
@@ -746,14 +1684,44 @@ export class TuneOutCoordinator {
|
|
|
746
1684
|
const mine = this.channelRegistry.ownChannelFor(channelId, own, 'publish');
|
|
747
1685
|
if (mine && 'error' in mine)
|
|
748
1686
|
return { success: false, error: mine.error, isError: true };
|
|
749
|
-
|
|
1687
|
+
if (fork) {
|
|
1688
|
+
const named = mine ? [mine.channel] : this.channelRegistry.channelsNamed(channelId);
|
|
1689
|
+
const at = named.length === 1 ? named[0] : undefined;
|
|
1690
|
+
const hold = at ? this.holdFor(at.serverId, at.channelId) : null;
|
|
1691
|
+
const shown = at ? this.quotedShown(at.serverId, at.channelId) : JSON.stringify(channelId);
|
|
1692
|
+
const refused = (at || fork.epochId === undefined) && this.forkRefusal(fork, hold, 'speech', hold
|
|
1693
|
+
? `${shown} is held by a hold other than the one you were started to read`
|
|
1694
|
+
: `${shown} isn't held now`);
|
|
1695
|
+
if (refused)
|
|
1696
|
+
return { success: false, error: refused, isError: true };
|
|
1697
|
+
}
|
|
1698
|
+
return this.channelRegistry.publishForAgent(mine ? mine.channel : channelId, text, this.hooks.subconsciousName() ?? caller ?? 'Subconscious');
|
|
750
1699
|
}
|
|
751
1700
|
default:
|
|
752
1701
|
return { success: false, error: `unknown subconscious tool: ${name}`, isError: true };
|
|
753
1702
|
}
|
|
754
1703
|
}
|
|
755
1704
|
/**
|
|
756
|
-
*
|
|
1705
|
+
* Why a reader fork may not act through `hold` (the epoch holding what its
|
|
1706
|
+
* call names, or null): a fork ends and posts only through the hold of the
|
|
1707
|
+
* epoch it was derived to read, and one derived for none acts through no
|
|
1708
|
+
* hold. Undefined where the hold is its own. `why` says, for the fork, how
|
|
1709
|
+
* what its call names isn't its own hold; its reports stay open to it.
|
|
1710
|
+
*/
|
|
1711
|
+
forkRefusal(fork, hold, act, why) {
|
|
1712
|
+
if (fork.epochId !== undefined && hold?.epochId === fork.epochId)
|
|
1713
|
+
return undefined;
|
|
1714
|
+
const nothing = act === 'cancel' ? 'Nothing was cancelled' : 'Nothing was posted';
|
|
1715
|
+
const report = `Your report can say what you would ${act === 'cancel' ? 'judge of it' : 'have posted'}, and the resident reads it.`;
|
|
1716
|
+
if (fork.epochId === undefined) {
|
|
1717
|
+
return `${nothing}: you weren't started to read a tune-out, so there's no hold you can `
|
|
1718
|
+
+ `${act === 'cancel' ? 'end' : 'post through'}. ${report}`;
|
|
1719
|
+
}
|
|
1720
|
+
const rule = act === 'cancel' ? 'a reader ends only its own' : 'a reader posts only into a channel its own hold holds';
|
|
1721
|
+
return `${nothing}: ${why}, and ${rule}. ${report}`;
|
|
1722
|
+
}
|
|
1723
|
+
/**
|
|
1724
|
+
* A cancel of a channel that isn't tuned out, by the name, quoted, the caller gave
|
|
757
1725
|
* or knows it by: which channels are, so the next call can name one, and
|
|
758
1726
|
* how a tune-out ends without one. `backlogTo`
|
|
759
1727
|
* names the resident as the message's reader knows it: "you" to the
|
|
@@ -763,15 +1731,28 @@ export class TuneOutCoordinator {
|
|
|
763
1731
|
* neither this list nor the name's lookup (channelsNamed, which reads the
|
|
764
1732
|
* registered channels too), and the text claims nothing about it.
|
|
765
1733
|
*/
|
|
766
|
-
notTunedOut(
|
|
767
|
-
const active = this.listActive().map((e) =>
|
|
1734
|
+
notTunedOut(quoted, backlogTo) {
|
|
1735
|
+
const active = this.listActive().map((e) => this.quotedShown(e.serverId, e.channelId));
|
|
768
1736
|
const opening = active.length === 0
|
|
769
1737
|
? 'no connected channel is tuned out now.'
|
|
770
|
-
: `no connected channel ${
|
|
1738
|
+
: `no connected channel ${quoted} is tuned out. Connected channels tuned out now: `
|
|
771
1739
|
+ `${active.join(', ')}.`;
|
|
772
1740
|
return `Nothing was cancelled: ${opening} A tune-out also ends by itself when its duration runs out, or at the `
|
|
773
1741
|
+ `first wake past its wake budget, and its backlog goes to ${backlogTo} then.`;
|
|
774
1742
|
}
|
|
1743
|
+
/**
|
|
1744
|
+
* The reader ended, not the framework: its turns stop (cadence and
|
|
1745
|
+
* coalescing wakes), and every hold keeps its end time, which releases it
|
|
1746
|
+
* to the resident with no reader.
|
|
1747
|
+
*/
|
|
1748
|
+
stopReader() {
|
|
1749
|
+
for (const timer of this.cadenceTimers.values())
|
|
1750
|
+
clearTimeout(timer);
|
|
1751
|
+
this.cadenceTimers.clear();
|
|
1752
|
+
for (const { timer } of this.pendingWakes.values())
|
|
1753
|
+
clearTimeout(timer);
|
|
1754
|
+
this.pendingWakes.clear();
|
|
1755
|
+
}
|
|
775
1756
|
/** Stop all timers (framework shutdown). */
|
|
776
1757
|
stop() {
|
|
777
1758
|
for (const timer of this.cadenceTimers.values())
|