@animalabs/agent-framework 0.29.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/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 +43 -6
- package/dist/src/agent.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/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 +684 -33
- package/dist/src/framework.d.ts.map +1 -1
- package/dist/src/framework.js +2998 -350
- package/dist/src/framework.js.map +1 -1
- package/dist/src/gate/event-gate.d.ts +12 -4
- package/dist/src/gate/event-gate.d.ts.map +1 -1
- package/dist/src/gate/event-gate.js +25 -5
- package/dist/src/gate/event-gate.js.map +1 -1
- package/dist/src/host-presentation.d.ts +4 -0
- package/dist/src/host-presentation.d.ts.map +1 -1
- package/dist/src/host-presentation.js +7 -3
- package/dist/src/host-presentation.js.map +1 -1
- package/dist/src/index.d.ts +5 -2
- package/dist/src/index.d.ts.map +1 -1
- package/dist/src/index.js +6 -1
- package/dist/src/index.js.map +1 -1
- package/dist/src/mcpl/channel-registry.d.ts +84 -9
- package/dist/src/mcpl/channel-registry.d.ts.map +1 -1
- package/dist/src/mcpl/channel-registry.js +136 -58
- package/dist/src/mcpl/channel-registry.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/toolsets-module.d.ts.map +1 -1
- package/dist/src/mcpl/toolsets-module.js +7 -0
- package/dist/src/mcpl/toolsets-module.js.map +1 -1
- package/dist/src/notice-tags.d.ts +2 -0
- package/dist/src/notice-tags.d.ts.map +1 -1
- package/dist/src/notice-tags.js +2 -0
- package/dist/src/notice-tags.js.map +1 -1
- package/dist/src/silent-heartbeat.d.ts +4 -2
- package/dist/src/silent-heartbeat.d.ts.map +1 -1
- package/dist/src/silent-heartbeat.js +7 -4
- 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/tune-out/coordinator.d.ts +379 -9
- package/dist/src/tune-out/coordinator.d.ts.map +1 -1
- package/dist/src/tune-out/coordinator.js +1080 -97
- 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 +25 -0
- package/dist/src/types/agent.d.ts.map +1 -1
- package/dist/src/types/framework.d.ts +99 -0
- package/dist/src/types/framework.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 +48 -6
- package/src/author-presentation.ts +81 -0
- 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 +3239 -369
- package/src/gate/event-gate.ts +31 -5
- package/src/host-presentation.ts +10 -3
- package/src/index.ts +15 -2
- package/src/mcpl/channel-registry.ts +170 -60
- package/src/mcpl/push-coalescer.ts +19 -0
- package/src/mcpl/toolsets-module.ts +7 -0
- package/src/notice-tags.ts +2 -0
- package/src/silent-heartbeat.ts +7 -4
- package/src/stored-injections.ts +7 -0
- package/src/tune-out/coordinator.ts +1229 -98
- package/src/tune-out/tools.ts +152 -11
- package/src/types/agent.ts +28 -0
- package/src/types/framework.ts +102 -0
- package/src/types/trace.ts +150 -0
|
@@ -15,8 +15,9 @@
|
|
|
15
15
|
* lifecycle facts (the [Gate: …] precedent).
|
|
16
16
|
*/
|
|
17
17
|
import { NOTICE_TAG } from '../notice-tags.js';
|
|
18
|
-
import { cutToFit, suppliedValue } from '../supplied-text.js';
|
|
18
|
+
import { cutToFit, quotedValue, suppliedValue } from '../supplied-text.js';
|
|
19
19
|
import { randomUUID } from 'node:crypto';
|
|
20
|
+
import { authorLine, authorNamed, beginsWithAuthorLine } from '../author-presentation.js';
|
|
20
21
|
import { CapabilityGrant } from '../mcpl/capability-grant.js';
|
|
21
22
|
import { armAfter, armAt } from '../deadline-timer.js';
|
|
22
23
|
/** Defaults for tune_out tool params. */
|
|
@@ -28,6 +29,38 @@ export const TUNE_OUT_DEFAULTS = {
|
|
|
28
29
|
/** Coalescing window for wake invocations: a mention storm becomes one
|
|
29
30
|
* subconscious turn, and max-wakes counts invocations, not messages. */
|
|
30
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
|
+
}
|
|
31
64
|
/** How long after an end time whose cancel threw the cancel is tried again. */
|
|
32
65
|
const EXPIRY_RETRY_MS = 60_000;
|
|
33
66
|
/** Ends a backlog line cut to fit in one of the residents' messages. */
|
|
@@ -74,8 +107,60 @@ export class TuneOutCoordinator {
|
|
|
74
107
|
expiryTimers = new Map();
|
|
75
108
|
/** Channels with a wake invocation pending inside the coalescing window. */
|
|
76
109
|
pendingWakes = new Map();
|
|
77
|
-
/**
|
|
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
|
+
*/
|
|
78
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';
|
|
79
164
|
constructor(channelRegistry, serverRegistry, hooks) {
|
|
80
165
|
this.channelRegistry = channelRegistry;
|
|
81
166
|
this.serverRegistry = serverRegistry;
|
|
@@ -84,6 +169,26 @@ export class TuneOutCoordinator {
|
|
|
84
169
|
key(serverId, channelId) {
|
|
85
170
|
return `${serverId}\0${channelId}`;
|
|
86
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
|
+
}
|
|
87
192
|
/** A channel as the resident and the subconscious are shown it
|
|
88
193
|
* (ChannelRegistry.nameShown): its id, or, where another server registers
|
|
89
194
|
* the same id, its server-qualified name, which tune_out and
|
|
@@ -112,9 +217,42 @@ export class TuneOutCoordinator {
|
|
|
112
217
|
oldestAnchor = params.startedAtSequence;
|
|
113
218
|
}
|
|
114
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
|
+
}
|
|
115
232
|
if (oldestAnchor !== null) {
|
|
116
233
|
this.hooks.setSubconsciousAnchor(oldestAnchor);
|
|
117
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();
|
|
118
256
|
}
|
|
119
257
|
armExpiry(serverId, channelId, params) {
|
|
120
258
|
if (params.expiresAtMs === undefined)
|
|
@@ -167,39 +305,19 @@ export class TuneOutCoordinator {
|
|
|
167
305
|
// ==========================================================================
|
|
168
306
|
// Enter / cancel
|
|
169
307
|
// ==========================================================================
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
+ "conversation, and tune_out won't divert a channel while one is. Calling tune_out on it again won't change "
|
|
184
|
-
+ 'that until the conversation ends, which happens only once the channel has been quiet for a while. Tune '
|
|
185
|
-
+ 'out a different channel, or ask whoever runs this host if this one should be diverted.',
|
|
186
|
-
};
|
|
187
|
-
}
|
|
188
|
-
const current = this.channelRegistry.getTuneOutState(serverId, channelId);
|
|
189
|
-
if (current)
|
|
190
|
-
return { ok: false, error: alreadyTunedOutText(this.quotedShown(serverId, channelId), current.params), alreadyTunedOut: true };
|
|
191
|
-
// A tool's input reaches here as the model wrote it, and the store can't
|
|
192
|
-
// keep a NaN or an Infinity: its append would throw after the registry
|
|
193
|
-
// had marked the channel tuned out. So each option is read as a number
|
|
194
|
-
// before anything changes, a numeric string included, as the sleep tool
|
|
195
|
-
// reads its seconds; null counts as left out. A value that gives no
|
|
196
|
-
// finite number is refused.
|
|
197
|
-
const leftOut = {
|
|
198
|
-
durationSeconds: 'to stay tuned out until you cancel',
|
|
199
|
-
cadenceSeconds: `for the default, ${TUNE_OUT_DEFAULTS.cadenceSeconds}`,
|
|
200
|
-
backlogCap: `for the default, ${TUNE_OUT_DEFAULTS.backlogCap}`,
|
|
201
|
-
maxWakes: `for the default, ${TUNE_OUT_DEFAULTS.maxWakes}`,
|
|
202
|
-
};
|
|
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) {
|
|
203
321
|
const given = {};
|
|
204
322
|
for (const name of Object.keys(leftOut)) {
|
|
205
323
|
const value = opts[name];
|
|
@@ -213,21 +331,63 @@ export class TuneOutCoordinator {
|
|
|
213
331
|
return {
|
|
214
332
|
ok: false,
|
|
215
333
|
error: `Nothing was tuned out: ${name} must be a finite number${name.endsWith('Seconds') ? ' of seconds' : ''}, `
|
|
216
|
-
+ `and it was ${got}
|
|
334
|
+
+ `and it was ${got}.${leftOut[name] ? ` Leave it out ${leftOut[name]}.` : ''}`,
|
|
217
335
|
};
|
|
218
336
|
}
|
|
219
337
|
given[name] = n;
|
|
220
338
|
}
|
|
339
|
+
const now = Date.now();
|
|
221
340
|
const expiresAtMs = given.durationSeconds === undefined
|
|
222
341
|
? undefined
|
|
223
|
-
:
|
|
342
|
+
: now + Math.max(60, given.durationSeconds) * 1000;
|
|
224
343
|
if (expiresAtMs !== undefined && !Number.isFinite(expiresAtMs)) {
|
|
225
344
|
return {
|
|
226
345
|
ok: false,
|
|
227
|
-
error: `Nothing was tuned out: durationSeconds ${given.durationSeconds} is longer than an end time can be kept
|
|
228
|
-
+ `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.',
|
|
364
|
+
};
|
|
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.',
|
|
229
373
|
};
|
|
230
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;
|
|
231
391
|
const params = {
|
|
232
392
|
epochId: randomUUID(),
|
|
233
393
|
cadenceSeconds: Math.max(30, given.cadenceSeconds ?? TUNE_OUT_DEFAULTS.cadenceSeconds),
|
|
@@ -247,10 +407,17 @@ export class TuneOutCoordinator {
|
|
|
247
407
|
const oldest = this.listActive().reduce((min, e) => Math.min(min, e.params.startedAtSequence), params.startedAtSequence);
|
|
248
408
|
this.hooks.setSubconsciousAnchor(oldest);
|
|
249
409
|
this.divertedSinceInvocation.set(this.key(serverId, channelId), 0);
|
|
250
|
-
this.
|
|
251
|
-
|
|
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
|
+
});
|
|
252
415
|
return { ok: true, params };
|
|
253
416
|
}
|
|
417
|
+
/** Whether a reader (persistent subconscious or reader forks) attends holds. */
|
|
418
|
+
hasReader() {
|
|
419
|
+
return this.readerAvailable();
|
|
420
|
+
}
|
|
254
421
|
/**
|
|
255
422
|
* End a tune-out: durable flip, system-framed backlog dump into the
|
|
256
423
|
* resident's window (capped), lifecycle notice, one wake for the
|
|
@@ -258,8 +425,12 @@ export class TuneOutCoordinator {
|
|
|
258
425
|
* cancel_tuneout call) — delivered verbatim under its name, never
|
|
259
426
|
* synthesized here.
|
|
260
427
|
*/
|
|
261
|
-
cancel(serverId, channelId, source, reason, subconsciousNote
|
|
262
|
-
|
|
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);
|
|
263
434
|
if (!ended) {
|
|
264
435
|
// Its reader is the resident's tune_out: cancel_tuneout finds the channel first.
|
|
265
436
|
return { ok: false, error: this.notTunedOut(this.quotedShown(serverId, channelId), 'you') };
|
|
@@ -283,13 +454,12 @@ export class TuneOutCoordinator {
|
|
|
283
454
|
// start at 0 and take them all.
|
|
284
455
|
const cap = Math.floor(ended.params.backlogCap);
|
|
285
456
|
const authorOf = (m) => suppliedValue(m.metadata?.author?.name ?? m.participant);
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
};
|
|
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';
|
|
293
463
|
// The channel as the resident and the subconscious are shown it.
|
|
294
464
|
const name = this.shown(serverId, channelId);
|
|
295
465
|
const lifecycle = `[${NOTICE_TAG.tuneOut}: ${name} cancelled — ${reason}, ${ended.wakeCount} wake${ended.wakeCount === 1 ? '' : 's'}]`;
|
|
@@ -297,7 +467,9 @@ export class TuneOutCoordinator {
|
|
|
297
467
|
const attrs = [
|
|
298
468
|
`channel=${this.quotedShown(serverId, channelId)}`,
|
|
299
469
|
`messages=${backlog.length}`,
|
|
300
|
-
...(truncated > 0
|
|
470
|
+
...(truncated > 0
|
|
471
|
+
? [`truncated=${truncated} (oldest; ${historyTool ? `${historyTool} covers the rest` : 'not delivered'})`]
|
|
472
|
+
: []),
|
|
301
473
|
];
|
|
302
474
|
return `${lifecycle}\n\n<tuned-out-backlog ${attrs.join(' ')}>\n${lines.join('\n')}\n</tuned-out-backlog>`;
|
|
303
475
|
};
|
|
@@ -363,6 +535,8 @@ export class TuneOutCoordinator {
|
|
|
363
535
|
];
|
|
364
536
|
// Host-framed system artifacts — never voiced as anyone.
|
|
365
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?.();
|
|
366
540
|
// The subconscious's own words, under its own name, verbatim.
|
|
367
541
|
const subName = this.hooks.subconsciousName();
|
|
368
542
|
if (subconsciousNote && subName) {
|
|
@@ -371,6 +545,11 @@ export class TuneOutCoordinator {
|
|
|
371
545
|
// reads (repinChannel), where another server's channel can share the id.
|
|
372
546
|
{ kind: 'subconscious-note', channelId, serverId, epochId });
|
|
373
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
|
+
}
|
|
374
553
|
const primary = this.hooks.primaryName();
|
|
375
554
|
if (primary) {
|
|
376
555
|
this.hooks.requestInference(primary, `tune-out cancelled (${reason})`, 'tune-out');
|
|
@@ -400,6 +579,34 @@ export class TuneOutCoordinator {
|
|
|
400
579
|
}
|
|
401
580
|
this.hooks.requestInference(subName, `tune-out cancelled: ${name}`, 'tune-out');
|
|
402
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);
|
|
403
610
|
this.hooks.emitTrace({ type: 'tune-out:cancelled', serverId, channelId, epochId, reason, wakeCount: ended.wakeCount });
|
|
404
611
|
return { ok: true };
|
|
405
612
|
}
|
|
@@ -415,9 +622,355 @@ export class TuneOutCoordinator {
|
|
|
415
622
|
* suppression ack, possible auto-cancel).
|
|
416
623
|
*/
|
|
417
624
|
onIncoming(serverId, channelId, messageId, tags, authorId, gatePass = true) {
|
|
418
|
-
const
|
|
419
|
-
if (!
|
|
625
|
+
const hold = this.holdFor(serverId, channelId);
|
|
626
|
+
if (!hold)
|
|
420
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) {
|
|
421
974
|
const key = this.key(serverId, channelId);
|
|
422
975
|
this.divertedSinceInvocation.set(key, (this.divertedSinceInvocation.get(key) ?? 0) + 1);
|
|
423
976
|
// Wake classification: the resident's wake gate composes as a
|
|
@@ -437,10 +990,17 @@ export class TuneOutCoordinator {
|
|
|
437
990
|
// standing mute to its subject.
|
|
438
991
|
void this.acknowledgeSuppressed(serverId, channelId, messageId);
|
|
439
992
|
}
|
|
440
|
-
if (gatePass && (addressed || privileged)) {
|
|
993
|
+
if (gatePass && (addressed || privileged) && this.readerAvailable()) {
|
|
441
994
|
this.scheduleWakeInvocation(serverId, channelId);
|
|
442
995
|
}
|
|
443
|
-
|
|
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);
|
|
444
1004
|
}
|
|
445
1005
|
async acknowledgeSuppressed(serverId, channelId, messageId) {
|
|
446
1006
|
try {
|
|
@@ -522,15 +1082,7 @@ export class TuneOutCoordinator {
|
|
|
522
1082
|
try {
|
|
523
1083
|
const entry = this.pendingWakes.get(key);
|
|
524
1084
|
this.pendingWakes.delete(key);
|
|
525
|
-
|
|
526
|
-
const counted = this.channelRegistry.recordTuneOutWake(serverId, channelId);
|
|
527
|
-
if (!counted)
|
|
528
|
-
return; // cancelled inside the window
|
|
529
|
-
if (counted.wakeCount > counted.params.maxWakes) {
|
|
530
|
-
this.cancel(serverId, channelId, 'tune-out-max-wakes', `wake budget exhausted (${counted.params.maxWakes})`);
|
|
531
|
-
return;
|
|
532
|
-
}
|
|
533
|
-
this.invokeSubconscious(serverId, channelId, 'wake', entry?.count ?? 1);
|
|
1085
|
+
this.fireWake(serverId, channelId, entry?.count ?? 1);
|
|
534
1086
|
}
|
|
535
1087
|
catch (err) {
|
|
536
1088
|
this.timerFailed('wake', serverId, channelId, err);
|
|
@@ -538,6 +1090,37 @@ export class TuneOutCoordinator {
|
|
|
538
1090
|
}, WAKE_COALESCE_MS);
|
|
539
1091
|
this.pendingWakes.set(key, { count: 1, timer });
|
|
540
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
|
+
}
|
|
541
1124
|
/**
|
|
542
1125
|
* One subconscious turn: a system-framed trigger notice (bracket style —
|
|
543
1126
|
* what happened, never what to say) plus standing dispositions, then an
|
|
@@ -545,18 +1128,314 @@ export class TuneOutCoordinator {
|
|
|
545
1128
|
*/
|
|
546
1129
|
invokeSubconscious(serverId, channelId, trigger, count) {
|
|
547
1130
|
const subName = this.hooks.subconsciousName();
|
|
548
|
-
if (!subName)
|
|
1131
|
+
if (!subName && !this.forkReader)
|
|
549
1132
|
return;
|
|
550
1133
|
const key = this.key(serverId, channelId);
|
|
551
1134
|
const shown = this.shown(serverId, channelId);
|
|
552
1135
|
const notice = trigger === 'wake'
|
|
553
1136
|
? `[${NOTICE_TAG.tuneOutWake}: ${shown} — ${count} addressed message${count === 1 ? '' : 's'}]`
|
|
554
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
|
+
}
|
|
555
1155
|
this.hooks.addMessage('user', [{ type: 'text', text: notice }], { system: true, kind: `tune-out-${trigger}`, channelId }, subName);
|
|
556
1156
|
this.hooks.requestInference(subName, `tune-out ${trigger}: ${shown}`, 'tune-out');
|
|
557
1157
|
// Counted from here only once the turn has been asked for, so a turn that
|
|
558
1158
|
// throws leaves its messages for the next period's turn.
|
|
559
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));
|
|
560
1439
|
}
|
|
561
1440
|
// ==========================================================================
|
|
562
1441
|
// Dispositions (standing notes, snapshot slot)
|
|
@@ -627,7 +1506,12 @@ export class TuneOutCoordinator {
|
|
|
627
1506
|
// ==========================================================================
|
|
628
1507
|
async handleSubconsciousTool(name, input,
|
|
629
1508
|
/** The calling turn's own channels, for a call made inside it (the framework's callOwnChannels). */
|
|
630
|
-
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) {
|
|
631
1515
|
switch (name) {
|
|
632
1516
|
case 'deliver_summary': {
|
|
633
1517
|
const text = String(input.text ?? '').trim();
|
|
@@ -641,20 +1525,22 @@ export class TuneOutCoordinator {
|
|
|
641
1525
|
};
|
|
642
1526
|
}
|
|
643
1527
|
const subName = this.hooks.subconsciousName();
|
|
644
|
-
|
|
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)) {
|
|
645
1542
|
return { success: false, error: 'subconscious not configured', isError: true };
|
|
646
|
-
|
|
647
|
-
// tagged with the channel the name means and its server, since the
|
|
648
|
-
// framework reads a conversational row's channel (repinChannel). The
|
|
649
|
-
// name means what it means to every channel tool: inside the calling
|
|
650
|
-
// turn, the id of one of the turn's own channels means that channel,
|
|
651
|
-
// refused where its server no longer registers it or the turn has
|
|
652
|
-
// channels with that id on two servers (ownChannelFor); otherwise a
|
|
653
|
-
// name several registered channels answer to is refused with them
|
|
654
|
-
// (sharedNameRefusalFor). So no row is left for a re-pin to read as
|
|
655
|
-
// another server's channel. A name no registered channel answers to
|
|
656
|
-
// is kept as given, with no server, which a re-pin reads by name when
|
|
657
|
-
// it weighs the row, as it reads any message without its server.
|
|
1543
|
+
}
|
|
658
1544
|
const mine = this.channelRegistry.ownChannelFor(channelId, own, 'deliver');
|
|
659
1545
|
if (mine && 'error' in mine)
|
|
660
1546
|
return { success: false, error: mine.error, isError: true };
|
|
@@ -662,33 +1548,87 @@ export class TuneOutCoordinator {
|
|
|
662
1548
|
if (shared)
|
|
663
1549
|
return { success: false, error: shared, isError: true };
|
|
664
1550
|
const [named] = mine ? [mine.channel] : this.channelRegistry.channelsNamed(channelId);
|
|
665
|
-
|
|
1551
|
+
const metadata = {
|
|
666
1552
|
kind: 'subconscious-summary',
|
|
667
1553
|
...(named ? { channelId: named.channelId, serverId: named.serverId } : { channelId }),
|
|
668
|
-
}
|
|
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);
|
|
669
1565
|
return { success: true, data: { delivered: true } };
|
|
670
1566
|
}
|
|
671
1567
|
case 'cancel_tuneout': {
|
|
672
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;
|
|
673
1589
|
// The name means what it means to every channel tool, the
|
|
674
|
-
// resident's tune_out included:
|
|
675
|
-
//
|
|
676
|
-
//
|
|
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
|
|
677
1594
|
// (channelsNamed), whichever of them is tuned out, never taken to be
|
|
678
|
-
// the tuned-out one.
|
|
679
|
-
|
|
680
|
-
|
|
681
|
-
|
|
682
|
-
const
|
|
683
|
-
const
|
|
684
|
-
|
|
685
|
-
|
|
686
|
-
|
|
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];
|
|
687
1605
|
if (!channel || !this.channelRegistry.getTuneOutState(channel.serverId, channel.channelId)) {
|
|
688
|
-
|
|
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();
|
|
689
1626
|
}
|
|
690
|
-
const
|
|
691
|
-
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);
|
|
692
1632
|
return result.ok
|
|
693
1633
|
? { success: true, data: { cancelled: true } }
|
|
694
1634
|
: { success: false, error: result.error, isError: true };
|
|
@@ -744,12 +1684,42 @@ export class TuneOutCoordinator {
|
|
|
744
1684
|
const mine = this.channelRegistry.ownChannelFor(channelId, own, 'publish');
|
|
745
1685
|
if (mine && 'error' in mine)
|
|
746
1686
|
return { success: false, error: mine.error, isError: true };
|
|
747
|
-
|
|
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');
|
|
748
1699
|
}
|
|
749
1700
|
default:
|
|
750
1701
|
return { success: false, error: `unknown subconscious tool: ${name}`, isError: true };
|
|
751
1702
|
}
|
|
752
1703
|
}
|
|
1704
|
+
/**
|
|
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
|
+
}
|
|
753
1723
|
/**
|
|
754
1724
|
* A cancel of a channel that isn't tuned out, by the name, quoted, the caller gave
|
|
755
1725
|
* or knows it by: which channels are, so the next call can name one, and
|
|
@@ -770,6 +1740,19 @@ export class TuneOutCoordinator {
|
|
|
770
1740
|
return `Nothing was cancelled: ${opening} A tune-out also ends by itself when its duration runs out, or at the `
|
|
771
1741
|
+ `first wake past its wake budget, and its backlog goes to ${backlogTo} then.`;
|
|
772
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
|
+
}
|
|
773
1756
|
/** Stop all timers (framework shutdown). */
|
|
774
1757
|
stop() {
|
|
775
1758
|
for (const timer of this.cadenceTimers.values())
|