@animalabs/agent-framework 0.23.1 → 0.24.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 +212 -42
- package/dist/src/agent.d.ts +60 -9
- package/dist/src/agent.d.ts.map +1 -1
- package/dist/src/agent.js +92 -12
- package/dist/src/agent.js.map +1 -1
- package/dist/src/api/server.d.ts.map +1 -1
- package/dist/src/api/server.js +14 -12
- package/dist/src/api/server.js.map +1 -1
- package/dist/src/code-execution/engine.d.ts +177 -0
- package/dist/src/code-execution/engine.d.ts.map +1 -0
- package/dist/src/code-execution/engine.js +494 -0
- package/dist/src/code-execution/engine.js.map +1 -0
- package/dist/src/code-execution/index.d.ts +5 -10
- package/dist/src/code-execution/index.d.ts.map +1 -1
- package/dist/src/code-execution/index.js +5 -9
- package/dist/src/code-execution/index.js.map +1 -1
- package/dist/src/code-execution/isolate/calls.d.ts +114 -0
- package/dist/src/code-execution/isolate/calls.d.ts.map +1 -0
- package/dist/src/code-execution/isolate/calls.js +145 -0
- package/dist/src/code-execution/isolate/calls.js.map +1 -0
- package/dist/src/code-execution/isolate/child-entry.d.ts +2 -0
- package/dist/src/code-execution/isolate/child-entry.d.ts.map +1 -0
- package/dist/src/code-execution/isolate/child-entry.js +5 -0
- package/dist/src/code-execution/isolate/child-entry.js.map +1 -0
- package/dist/src/code-execution/isolate/child-main.d.ts +26 -0
- package/dist/src/code-execution/isolate/child-main.d.ts.map +1 -0
- package/dist/src/code-execution/isolate/child-main.js +132 -0
- package/dist/src/code-execution/isolate/child-main.js.map +1 -0
- package/dist/src/code-execution/isolate/child.d.ts +44 -0
- package/dist/src/code-execution/isolate/child.d.ts.map +1 -0
- package/dist/src/code-execution/isolate/child.js +315 -0
- package/dist/src/code-execution/isolate/child.js.map +1 -0
- package/dist/src/code-execution/isolate/frames.d.ts +80 -0
- package/dist/src/code-execution/isolate/frames.d.ts.map +1 -0
- package/dist/src/code-execution/isolate/frames.js +210 -0
- package/dist/src/code-execution/isolate/frames.js.map +1 -0
- package/dist/src/code-execution/isolate/output.d.ts +68 -0
- package/dist/src/code-execution/isolate/output.d.ts.map +1 -0
- package/dist/src/code-execution/isolate/output.js +143 -0
- package/dist/src/code-execution/isolate/output.js.map +1 -0
- package/dist/src/code-execution/isolate/prelude.d.ts +109 -0
- package/dist/src/code-execution/isolate/prelude.d.ts.map +1 -0
- package/dist/src/code-execution/isolate/prelude.js +401 -0
- package/dist/src/code-execution/isolate/prelude.js.map +1 -0
- package/dist/src/code-execution/isolate/protocol.d.ts +151 -0
- package/dist/src/code-execution/isolate/protocol.d.ts.map +1 -0
- package/dist/src/code-execution/isolate/protocol.js +150 -0
- package/dist/src/code-execution/isolate/protocol.js.map +1 -0
- package/dist/src/code-execution/isolate/render.d.ts +57 -0
- package/dist/src/code-execution/isolate/render.d.ts.map +1 -0
- package/dist/src/code-execution/isolate/render.js +214 -0
- package/dist/src/code-execution/isolate/render.js.map +1 -0
- package/dist/src/code-execution/isolate/runner.d.ts +250 -0
- package/dist/src/code-execution/isolate/runner.d.ts.map +1 -0
- package/dist/src/code-execution/isolate/runner.js +854 -0
- package/dist/src/code-execution/isolate/runner.js.map +1 -0
- package/dist/src/code-execution/isolate/scripts.d.ts +175 -0
- package/dist/src/code-execution/isolate/scripts.d.ts.map +1 -0
- package/dist/src/code-execution/isolate/scripts.js +357 -0
- package/dist/src/code-execution/isolate/scripts.js.map +1 -0
- package/dist/src/code-execution/quickjs.wasm +0 -0
- package/dist/src/code-execution/tool-definition.d.ts +93 -43
- package/dist/src/code-execution/tool-definition.d.ts.map +1 -1
- package/dist/src/code-execution/tool-definition.js +176 -142
- package/dist/src/code-execution/tool-definition.js.map +1 -1
- package/dist/src/deadline-timer.d.ts +3 -0
- package/dist/src/deadline-timer.d.ts.map +1 -1
- package/dist/src/deadline-timer.js +1 -1
- package/dist/src/deadline-timer.js.map +1 -1
- package/dist/src/framework.d.ts +1036 -440
- package/dist/src/framework.d.ts.map +1 -1
- package/dist/src/framework.js +4131 -2228
- package/dist/src/framework.js.map +1 -1
- package/dist/src/gate/event-gate.d.ts +28 -1
- package/dist/src/gate/event-gate.d.ts.map +1 -1
- package/dist/src/gate/event-gate.js +88 -10
- package/dist/src/gate/event-gate.js.map +1 -1
- package/dist/src/held-writes.d.ts +16 -3
- package/dist/src/held-writes.d.ts.map +1 -1
- package/dist/src/held-writes.js +16 -3
- package/dist/src/held-writes.js.map +1 -1
- package/dist/src/index.d.ts +6 -6
- package/dist/src/index.d.ts.map +1 -1
- package/dist/src/index.js +9 -8
- package/dist/src/index.js.map +1 -1
- package/dist/src/mcpl/channel-registry.d.ts +471 -75
- package/dist/src/mcpl/channel-registry.d.ts.map +1 -1
- package/dist/src/mcpl/channel-registry.js +1673 -337
- package/dist/src/mcpl/channel-registry.js.map +1 -1
- package/dist/src/mcpl/conversation-router.d.ts +12 -7
- package/dist/src/mcpl/conversation-router.d.ts.map +1 -1
- package/dist/src/mcpl/conversation-router.js +12 -7
- package/dist/src/mcpl/conversation-router.js.map +1 -1
- package/dist/src/mcpl/convert-block.d.ts.map +1 -1
- package/dist/src/mcpl/convert-block.js +9 -5
- package/dist/src/mcpl/convert-block.js.map +1 -1
- package/dist/src/mcpl/inbound-source.d.ts +50 -0
- package/dist/src/mcpl/inbound-source.d.ts.map +1 -1
- package/dist/src/mcpl/inbound-source.js +130 -0
- package/dist/src/mcpl/inbound-source.js.map +1 -1
- package/dist/src/mcpl/index.d.ts +2 -1
- package/dist/src/mcpl/index.d.ts.map +1 -1
- package/dist/src/mcpl/index.js +3 -2
- package/dist/src/mcpl/index.js.map +1 -1
- package/dist/src/mcpl/log-value.d.ts +6 -0
- package/dist/src/mcpl/log-value.d.ts.map +1 -1
- package/dist/src/mcpl/log-value.js +8 -0
- package/dist/src/mcpl/log-value.js.map +1 -1
- package/dist/src/mcpl/modern-connection.d.ts +15 -6
- package/dist/src/mcpl/modern-connection.d.ts.map +1 -1
- package/dist/src/mcpl/modern-connection.js +168 -53
- package/dist/src/mcpl/modern-connection.js.map +1 -1
- package/dist/src/mcpl/prose-grammar.d.ts +4 -5
- package/dist/src/mcpl/prose-grammar.d.ts.map +1 -1
- package/dist/src/mcpl/prose-grammar.js +4 -5
- package/dist/src/mcpl/prose-grammar.js.map +1 -1
- package/dist/src/mcpl/protocol-family.d.ts +97 -10
- package/dist/src/mcpl/protocol-family.d.ts.map +1 -1
- package/dist/src/mcpl/protocol-family.js +173 -16
- package/dist/src/mcpl/protocol-family.js.map +1 -1
- package/dist/src/mcpl/push-coalescer.d.ts +132 -14
- package/dist/src/mcpl/push-coalescer.d.ts.map +1 -1
- package/dist/src/mcpl/push-coalescer.js +227 -50
- package/dist/src/mcpl/push-coalescer.js.map +1 -1
- package/dist/src/mcpl/push-handler.d.ts +6 -1
- package/dist/src/mcpl/push-handler.d.ts.map +1 -1
- package/dist/src/mcpl/push-handler.js +4 -1
- package/dist/src/mcpl/push-handler.js.map +1 -1
- package/dist/src/mcpl/reference-fetcher.d.ts +2 -2
- package/dist/src/mcpl/reference-fetcher.d.ts.map +1 -1
- package/dist/src/mcpl/reference-fetcher.js +4 -4
- package/dist/src/mcpl/reference-fetcher.js.map +1 -1
- package/dist/src/mcpl/server-connection.d.ts +50 -21
- package/dist/src/mcpl/server-connection.d.ts.map +1 -1
- package/dist/src/mcpl/server-connection.js +158 -74
- package/dist/src/mcpl/server-connection.js.map +1 -1
- package/dist/src/mcpl/tags.d.ts +24 -0
- package/dist/src/mcpl/tags.d.ts.map +1 -1
- package/dist/src/mcpl/tags.js +33 -0
- package/dist/src/mcpl/tags.js.map +1 -1
- package/dist/src/mcpl/tool-result-normalize.d.ts +2 -1
- package/dist/src/mcpl/tool-result-normalize.d.ts.map +1 -1
- package/dist/src/mcpl/tool-result-normalize.js.map +1 -1
- package/dist/src/mcpl/transport.d.ts +55 -7
- package/dist/src/mcpl/transport.d.ts.map +1 -1
- package/dist/src/mcpl/transport.js +163 -34
- package/dist/src/mcpl/transport.js.map +1 -1
- package/dist/src/mcpl/types.d.ts +22 -6
- 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 +4 -2
- package/dist/src/module-registry.d.ts.map +1 -1
- package/dist/src/module-registry.js +100 -13
- package/dist/src/module-registry.js.map +1 -1
- package/dist/src/modules/discord/index.d.ts.map +1 -1
- package/dist/src/modules/discord/index.js +8 -13
- package/dist/src/modules/discord/index.js.map +1 -1
- package/dist/src/modules/history/index.d.ts.map +1 -1
- package/dist/src/modules/history/index.js +27 -4
- package/dist/src/modules/history/index.js.map +1 -1
- package/dist/src/modules/history/semantic.d.ts +15 -3
- package/dist/src/modules/history/semantic.d.ts.map +1 -1
- package/dist/src/modules/history/semantic.js +27 -5
- package/dist/src/modules/history/semantic.js.map +1 -1
- package/dist/src/modules/index.d.ts +1 -1
- package/dist/src/modules/index.d.ts.map +1 -1
- package/dist/src/modules/index.js.map +1 -1
- package/dist/src/modules/unknown-tool.d.ts +4 -1
- package/dist/src/modules/unknown-tool.d.ts.map +1 -1
- package/dist/src/modules/unknown-tool.js +4 -1
- package/dist/src/modules/unknown-tool.js.map +1 -1
- package/dist/src/modules/workspace/branch-intent.d.ts +3 -1
- package/dist/src/modules/workspace/branch-intent.d.ts.map +1 -1
- package/dist/src/modules/workspace/branch-intent.js +3 -1
- package/dist/src/modules/workspace/branch-intent.js.map +1 -1
- package/dist/src/modules/workspace/edit-plan.d.ts +265 -0
- package/dist/src/modules/workspace/edit-plan.d.ts.map +1 -0
- package/dist/src/modules/workspace/edit-plan.js +794 -0
- package/dist/src/modules/workspace/edit-plan.js.map +1 -0
- package/dist/src/modules/workspace/edit-text.d.ts +117 -0
- package/dist/src/modules/workspace/edit-text.d.ts.map +1 -0
- package/dist/src/modules/workspace/edit-text.js +584 -0
- package/dist/src/modules/workspace/edit-text.js.map +1 -0
- package/dist/src/modules/workspace/effects.d.ts +5 -4
- package/dist/src/modules/workspace/effects.d.ts.map +1 -1
- package/dist/src/modules/workspace/effects.js +78 -25
- package/dist/src/modules/workspace/effects.js.map +1 -1
- package/dist/src/modules/workspace/index.d.ts +484 -61
- package/dist/src/modules/workspace/index.d.ts.map +1 -1
- package/dist/src/modules/workspace/index.js +2173 -645
- package/dist/src/modules/workspace/index.js.map +1 -1
- package/dist/src/modules/workspace/observe.d.ts +213 -38
- package/dist/src/modules/workspace/observe.d.ts.map +1 -1
- package/dist/src/modules/workspace/observe.js +416 -36
- package/dist/src/modules/workspace/observe.js.map +1 -1
- package/dist/src/modules/workspace/reconcile.d.ts.map +1 -1
- package/dist/src/modules/workspace/reconcile.js +15 -8
- package/dist/src/modules/workspace/reconcile.js.map +1 -1
- package/dist/src/modules/workspace/text.d.ts +32 -0
- package/dist/src/modules/workspace/text.d.ts.map +1 -0
- package/dist/src/modules/workspace/text.js +67 -0
- package/dist/src/modules/workspace/text.js.map +1 -0
- package/dist/src/modules/workspace/types.d.ts +210 -6
- package/dist/src/modules/workspace/types.d.ts.map +1 -1
- package/dist/src/modules/workspace/types.js.map +1 -1
- package/dist/src/modules/workspace/watcher.d.ts +3 -2
- package/dist/src/modules/workspace/watcher.d.ts.map +1 -1
- package/dist/src/modules/workspace/watcher.js.map +1 -1
- package/dist/src/operator-log.d.ts +52 -24
- package/dist/src/operator-log.d.ts.map +1 -1
- package/dist/src/operator-log.js.map +1 -1
- package/dist/src/recovery/discord-awareness-outbox.d.ts +496 -72
- package/dist/src/recovery/discord-awareness-outbox.d.ts.map +1 -1
- package/dist/src/recovery/discord-awareness-outbox.js +1196 -289
- package/dist/src/recovery/discord-awareness-outbox.js.map +1 -1
- package/dist/src/recovery/offline-branch.d.ts +26 -1
- package/dist/src/recovery/offline-branch.d.ts.map +1 -1
- package/dist/src/recovery/offline-branch.js +164 -39
- package/dist/src/recovery/offline-branch.js.map +1 -1
- package/dist/src/recovery/recover-cli.js +23 -4
- package/dist/src/recovery/recover-cli.js.map +1 -1
- package/dist/src/send-tools.d.ts +11 -0
- package/dist/src/send-tools.d.ts.map +1 -0
- package/dist/src/send-tools.js +11 -0
- package/dist/src/send-tools.js.map +1 -0
- package/dist/src/tool-result-guard.d.ts +4 -3
- package/dist/src/tool-result-guard.d.ts.map +1 -1
- package/dist/src/tool-result-guard.js +5 -4
- package/dist/src/tool-result-guard.js.map +1 -1
- package/dist/src/tool-result-history.d.ts +1 -1
- package/dist/src/tool-result-history.js +1 -1
- package/dist/src/tune-out/coordinator.d.ts +21 -0
- package/dist/src/tune-out/coordinator.d.ts.map +1 -1
- package/dist/src/tune-out/coordinator.js +139 -37
- package/dist/src/tune-out/coordinator.js.map +1 -1
- package/dist/src/types/agent.d.ts +4 -0
- package/dist/src/types/agent.d.ts.map +1 -1
- package/dist/src/types/events.d.ts +62 -9
- package/dist/src/types/events.d.ts.map +1 -1
- package/dist/src/types/framework.d.ts +62 -58
- package/dist/src/types/framework.d.ts.map +1 -1
- package/dist/src/types/module.d.ts +40 -8
- package/dist/src/types/module.d.ts.map +1 -1
- package/dist/src/types/trace.d.ts +111 -10
- package/dist/src/types/trace.d.ts.map +1 -1
- package/dist/src/usage/types.d.ts +16 -0
- package/dist/src/usage/types.d.ts.map +1 -1
- package/dist/src/usage/usage-tracker.d.ts +14 -1
- package/dist/src/usage/usage-tracker.d.ts.map +1 -1
- package/dist/src/usage/usage-tracker.js +81 -41
- package/dist/src/usage/usage-tracker.js.map +1 -1
- package/package.json +6 -5
- package/src/agent.ts +93 -12
- package/src/api/server.ts +14 -12
- package/src/code-execution/engine.ts +595 -0
- package/src/code-execution/index.ts +5 -17
- package/src/code-execution/isolate/calls.ts +199 -0
- package/src/code-execution/isolate/child-entry.ts +5 -0
- package/src/code-execution/isolate/child-main.ts +132 -0
- package/src/code-execution/isolate/child.ts +327 -0
- package/src/code-execution/isolate/frames.ts +209 -0
- package/src/code-execution/isolate/output.ts +161 -0
- package/src/code-execution/isolate/prelude.ts +409 -0
- package/src/code-execution/isolate/protocol.ts +240 -0
- package/src/code-execution/isolate/render.ts +230 -0
- package/src/code-execution/isolate/runner.ts +911 -0
- package/src/code-execution/isolate/scripts.ts +479 -0
- package/src/code-execution/quickjs.wasm +0 -0
- package/src/code-execution/quickjs.wasm.LICENSES +149 -0
- package/src/code-execution/tool-definition.ts +236 -167
- package/src/deadline-timer.ts +1 -1
- package/src/framework.ts +4507 -2406
- package/src/gate/event-gate.ts +78 -11
- package/src/held-writes.ts +17 -3
- package/src/index.ts +30 -22
- package/src/mcpl/channel-registry.ts +1825 -368
- package/src/mcpl/conversation-router.ts +12 -7
- package/src/mcpl/convert-block.ts +9 -5
- package/src/mcpl/inbound-source.ts +131 -0
- package/src/mcpl/index.ts +4 -2
- package/src/mcpl/log-value.ts +9 -0
- package/src/mcpl/modern-connection.ts +162 -53
- package/src/mcpl/prose-grammar.ts +4 -5
- package/src/mcpl/protocol-family.ts +199 -21
- package/src/mcpl/push-coalescer.ts +306 -62
- package/src/mcpl/push-handler.ts +10 -2
- package/src/mcpl/reference-fetcher.ts +4 -4
- package/src/mcpl/server-connection.ts +180 -79
- package/src/mcpl/tags.ts +36 -0
- package/src/mcpl/tool-result-normalize.ts +2 -1
- package/src/mcpl/transport.ts +162 -33
- package/src/mcpl/types.ts +23 -6
- package/src/module-registry.ts +92 -13
- package/src/modules/discord/index.ts +8 -13
- package/src/modules/history/index.ts +25 -3
- package/src/modules/history/semantic.ts +29 -6
- package/src/modules/index.ts +1 -0
- package/src/modules/unknown-tool.ts +4 -1
- package/src/modules/workspace/branch-intent.ts +3 -1
- package/src/modules/workspace/edit-plan.ts +954 -0
- package/src/modules/workspace/edit-text.ts +618 -0
- package/src/modules/workspace/effects.ts +70 -19
- package/src/modules/workspace/index.ts +2247 -642
- package/src/modules/workspace/observe.ts +465 -56
- package/src/modules/workspace/reconcile.ts +14 -7
- package/src/modules/workspace/text.ts +68 -0
- package/src/modules/workspace/types.ts +211 -6
- package/src/modules/workspace/watcher.ts +3 -2
- package/src/operator-log.ts +47 -19
- package/src/recovery/discord-awareness-outbox.ts +1500 -356
- package/src/recovery/offline-branch.ts +189 -55
- package/src/recovery/recover-cli.ts +25 -4
- package/src/send-tools.ts +11 -0
- package/src/tool-result-guard.ts +6 -5
- package/src/tool-result-history.ts +1 -1
- package/src/tune-out/coordinator.ts +163 -42
- package/src/types/agent.ts +4 -0
- package/src/types/events.ts +62 -9
- package/src/types/framework.ts +62 -58
- package/src/types/module.ts +40 -8
- package/src/types/trace.ts +121 -15
- package/src/usage/types.ts +16 -0
- package/src/usage/usage-tracker.ts +86 -43
- package/dist/src/code-execution/py-runner.d.ts +0 -191
- package/dist/src/code-execution/py-runner.d.ts.map +0 -1
- package/dist/src/code-execution/py-runner.js +0 -655
- package/dist/src/code-execution/py-runner.js.map +0 -1
- package/dist/src/code-execution/runtime-py.d.ts +0 -50
- package/dist/src/code-execution/runtime-py.d.ts.map +0 -1
- package/dist/src/code-execution/runtime-py.js +0 -677
- package/dist/src/code-execution/runtime-py.js.map +0 -1
- package/dist/src/mcpl/prose-stream-router.d.ts +0 -88
- package/dist/src/mcpl/prose-stream-router.d.ts.map +0 -1
- package/dist/src/mcpl/prose-stream-router.js +0 -291
- package/dist/src/mcpl/prose-stream-router.js.map +0 -1
- package/src/code-execution/py-runner.ts +0 -791
- package/src/code-execution/runtime-py.ts +0 -677
- package/src/mcpl/prose-stream-router.ts +0 -268
|
@@ -15,7 +15,7 @@
|
|
|
15
15
|
import { convertBlock } from './convert-block.js';
|
|
16
16
|
import { isDeepStrictEqual } from 'node:util';
|
|
17
17
|
import { ensureStateRegistered } from '../module-registry.js';
|
|
18
|
-
import { expandCoreTags } from './tags.js';
|
|
18
|
+
import { expandCoreTags, isMarkerTagged } from './tags.js';
|
|
19
19
|
import { coalesceRejectionReason, EmptyContentError, validateCoalescedContent } from './push-coalescer.js';
|
|
20
20
|
import { isVisiblyEmptyConversion } from './visible-content.js';
|
|
21
21
|
import { logDetail, logValue } from './log-value.js';
|
|
@@ -28,16 +28,52 @@ import { readSkipReplyWake } from './skip-reply-wake.js';
|
|
|
28
28
|
// ============================================================================
|
|
29
29
|
const TYPING_INTERVAL_MS = 7_000;
|
|
30
30
|
const MAX_CHANNEL_LIFECYCLE_ATTEMPTS = 5;
|
|
31
|
-
/**
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
31
|
+
/**
|
|
32
|
+
* A channel's lifecycle operation, or a delivery waiting on one, that didn't
|
|
33
|
+
* complete. Its message is a clause in the agent's words, which its traces
|
|
34
|
+
* carry too, so the two never drift apart; `kind` says what the agent can do
|
|
35
|
+
* next, and `reach` where the server stood, for `unreachable`.
|
|
36
|
+
* - `unreachable`: its server isn't up (ServerReach).
|
|
37
|
+
* - `not-permitted`: its server is up, and its grant lacks channels.lifecycle.
|
|
38
|
+
* - `cancelled`: queued for a server whose registrations were removed.
|
|
39
|
+
* - `unlisted`: the server no longer lists the channel.
|
|
40
|
+
* - `superseded`: a later decision about the channel came first.
|
|
41
|
+
* - `converge`: a successful RPC kept failing to establish the latest target.
|
|
42
|
+
* - `substituted`: a channels/open answered for a channel other than the one
|
|
43
|
+
* it named.
|
|
44
|
+
* - `removed`, `not-open`: a delivery's wait (waitForOpenChannel) ended with
|
|
45
|
+
* the channel's registration gone, or with its close standing
|
|
46
|
+
* (closeStands) or its open not confirmed. These are whole reasons for
|
|
47
|
+
* words that didn't go out, said as they are.
|
|
48
|
+
* - `unrecorded`: the decision couldn't be written to the lifecycle log
|
|
49
|
+
* (appendLifecycleEvent), so nothing changed and nothing was sent.
|
|
50
|
+
* - `overtaken`, `put-back-unrecorded`, `selected-again`: an open by speech
|
|
51
|
+
* or a reply that failed (openChannelNow), carrying its own failure's
|
|
52
|
+
* clause. `overtaken`: a decision made during its round-trip, such as the
|
|
53
|
+
* agent's own close or channel_open, replaced the one the open wrote; that
|
|
54
|
+
* decision stands, and nothing is put back. `put-back-unrecorded`: the
|
|
55
|
+
* decision it replaced couldn't be put back on record, so the decision to
|
|
56
|
+
* open stays, the channel stays selected for opening, and reconciliation
|
|
57
|
+
* may open it later. `selected-again`: the pure default it put back is
|
|
58
|
+
* lifted by the channel's current descriptor or the subscription policy,
|
|
59
|
+
* so the channel is selected for opening again; `by` says which.
|
|
60
|
+
*/
|
|
61
|
+
class ChannelLifecycleError extends Error {
|
|
62
|
+
kind;
|
|
63
|
+
reach;
|
|
64
|
+
by;
|
|
65
|
+
constructor(message, kind, reach, options) {
|
|
66
|
+
super(message, options && 'cause' in options ? { cause: options.cause } : undefined);
|
|
67
|
+
this.kind = kind;
|
|
68
|
+
this.reach = reach;
|
|
69
|
+
this.name = 'ChannelLifecycleError';
|
|
70
|
+
this.by = options?.by;
|
|
71
|
+
}
|
|
39
72
|
}
|
|
40
73
|
const CHANNEL_LIFECYCLE_LOG_ID = 'mcpl/channel-lifecycle';
|
|
74
|
+
/** The sources of a decision the agent itself made: channel_open and
|
|
75
|
+
* channel_close, and channel_decline. */
|
|
76
|
+
const AGENT_DECISION_SOURCES = new Set(['agent-tool', 'invitation-declined']);
|
|
41
77
|
/**
|
|
42
78
|
* What a channels/open answer says about which channel the server opened:
|
|
43
79
|
* its `channel.id`, or else the `channelId` of a history item. Each is
|
|
@@ -74,6 +110,43 @@ function substitutedChannel(result, requested) {
|
|
|
74
110
|
* `resolveProseTargetDurable`.
|
|
75
111
|
*/
|
|
76
112
|
const CHANNEL_LABEL_HISTORY_LOG_ID = 'mcpl/channel-label-history';
|
|
113
|
+
/** A lifecycle-log item as a desired-state decision, or null when it isn't
|
|
114
|
+
* one this build reads: the one rule the registry's replay
|
|
115
|
+
* (initializeLifecycleStore) and desiredStateInLog read the log by. */
|
|
116
|
+
function desiredStateRecord(item) {
|
|
117
|
+
const event = item;
|
|
118
|
+
if (event?.kind !== 'desired-state' || typeof event.serverId !== 'string' || typeof event.channelId !== 'string')
|
|
119
|
+
return null;
|
|
120
|
+
if (!(event.desired === 'open' || event.desired === 'closed' || (event.desired === 'tuned-out' && event.tuneOut)))
|
|
121
|
+
return null;
|
|
122
|
+
return {
|
|
123
|
+
serverId: event.serverId,
|
|
124
|
+
channelId: event.channelId,
|
|
125
|
+
state: event.desired,
|
|
126
|
+
source: typeof event.source === 'string' ? event.source : 'unknown',
|
|
127
|
+
...(event.desired === 'tuned-out' ? { tuneOut: event.tuneOut } : {}),
|
|
128
|
+
};
|
|
129
|
+
}
|
|
130
|
+
/**
|
|
131
|
+
* The desired state `store`'s lifecycle log records for `channelId` on
|
|
132
|
+
* `serverId`, for a reader with no registry yet, as a serving boot's
|
|
133
|
+
* deferred-write flush is, before initializeMcpl: the last decision wins, as
|
|
134
|
+
* the registry's replay reads it (getDesiredState answers once there is a
|
|
135
|
+
* registry). undefined when no decision names it.
|
|
136
|
+
*/
|
|
137
|
+
export function desiredStateInLog(store, serverId, channelId) {
|
|
138
|
+
ensureStateRegistered(store, { id: CHANNEL_LIFECYCLE_LOG_ID, strategy: 'append_log' });
|
|
139
|
+
const raw = store.getStateJson(CHANNEL_LIFECYCLE_LOG_ID);
|
|
140
|
+
if (!Array.isArray(raw))
|
|
141
|
+
return undefined;
|
|
142
|
+
let state;
|
|
143
|
+
for (const item of raw) {
|
|
144
|
+
const decision = desiredStateRecord(item);
|
|
145
|
+
if (decision?.serverId === serverId && decision.channelId === channelId)
|
|
146
|
+
state = decision.state;
|
|
147
|
+
}
|
|
148
|
+
return state;
|
|
149
|
+
}
|
|
77
150
|
/** Extract a DM's identity/classification fields from a descriptor's
|
|
78
151
|
* metadata, if present — mirrors `resolveProseTarget()`'s own local
|
|
79
152
|
* `dmMeta()` read (`recipientId`, `recipientName`, `channelType`). Used
|
|
@@ -121,6 +194,25 @@ function shallowEqualRecord(a, b) {
|
|
|
121
194
|
}
|
|
122
195
|
return true;
|
|
123
196
|
}
|
|
197
|
+
/**
|
|
198
|
+
* A channel its server declared inbound-only (SPEC §14.2 `direction`): its
|
|
199
|
+
* messages come in, and the host publishes nothing into it. No publish, from
|
|
200
|
+
* plain speech, `channel_publish` or `publishForAgent`, and no outgoing
|
|
201
|
+
* stream starts there, though one the channel took before the declaration
|
|
202
|
+
* ends there (sendOutgoingChunk). Typing and acknowledgements, which carry
|
|
203
|
+
* no content, still go (SPEC §14.5: "Delivery occurs only via
|
|
204
|
+
* `channels/publish`"). A channel declared `outbound` or `bidirectional`, or
|
|
205
|
+
* with no direction, isn't one.
|
|
206
|
+
*/
|
|
207
|
+
function isInboundOnly(entry) {
|
|
208
|
+
return entry.descriptor.direction === 'inbound';
|
|
209
|
+
}
|
|
210
|
+
/** Why the host sends nothing into an inbound-only channel, as the resident
|
|
211
|
+
* reads it in a send-failure marker or a tool error. */
|
|
212
|
+
function inboundOnlyReason(entry) {
|
|
213
|
+
return (`inbound-only: server "${entry.serverId}" declared this channel's direction "inbound", ` +
|
|
214
|
+
'so the host publishes nothing into it; to speak there, use that server\'s own tools');
|
|
215
|
+
}
|
|
124
216
|
function sameChannelTarget(a, b) {
|
|
125
217
|
return a.type === b.type && isDeepStrictEqual(a.address, b.address);
|
|
126
218
|
}
|
|
@@ -140,6 +232,30 @@ export function journalToolDescription(canSkipReply) {
|
|
|
140
232
|
'why, notes for later. It does not end your turn and does not affect where ordinary ' +
|
|
141
233
|
'text is routed' + (canSkipReply ? '; to end the turn without replying, call skip_reply afterwards.' : '.');
|
|
142
234
|
}
|
|
235
|
+
/**
|
|
236
|
+
* channel_open's and channel_close's descriptions for an agent whose window doesn't hold a channel's traffic: an
|
|
237
|
+
* ephemeral run, whose store is its own unless it's where channel messages are stored (on a host with no residents,
|
|
238
|
+
* the first registered agent), and on a host that routes conversations every agent but a fork, since a channel's
|
|
239
|
+
* messages go to its fork or, unrouted, nowhere. The descriptions in CHANNEL_TOOL_DEFINITIONS, written for the agents
|
|
240
|
+
* that read a channel, promised such an agent what it never gets: "Messages that address you still reach you", and
|
|
241
|
+
* history "preceding the message that invited you" when nothing invites it. Given per agent (AgentFramework's
|
|
242
|
+
* getToolsForAgent), so a holder's cached tool list doesn't change.
|
|
243
|
+
*
|
|
244
|
+
* Both say the call is for every agent: the decision is recorded per server and channel (setDesiredState), so a run's
|
|
245
|
+
* close closes the channel for the agents whose windows hold it, which "its messages don't come to you" alone could
|
|
246
|
+
* read as costing nothing. They claim only what holds on both lanes: a push that names a channel is stored in the
|
|
247
|
+
* residents' shared slot whether or not the channel is open (handleMcplPushEvent), so on a routed host the residents
|
|
248
|
+
* get the channel's pushes, and a server may push while a channel is closed and send channels/incoming once it's
|
|
249
|
+
* open. So opening brings the caller none of the channel's messages, and closing stops none reaching it. The history
|
|
250
|
+
* channel_open asks for comes back in its result (handleToolOpen), so that clause is true for anyone.
|
|
251
|
+
*/
|
|
252
|
+
export const NON_HOLDER_CHANNEL_DESCRIPTIONS = {
|
|
253
|
+
channel_open: 'Open a channel for every agent on this host. Opening it brings you none of its messages; for the agents they do ' +
|
|
254
|
+
'come to, its server decides what it delivers. Optionally request some of its history, which comes back to you in ' +
|
|
255
|
+
'this call.',
|
|
256
|
+
channel_close: 'Close a channel for every agent on this host. Closing it stops none of its messages reaching you; for the agents ' +
|
|
257
|
+
'they do come to, its server decides what closing it stops.',
|
|
258
|
+
};
|
|
143
259
|
const CHANNEL_TOOL_DEFINITIONS = [
|
|
144
260
|
{
|
|
145
261
|
name: 'channel_list',
|
|
@@ -201,11 +317,11 @@ const CHANNEL_TOOL_DEFINITIONS = [
|
|
|
201
317
|
},
|
|
202
318
|
{
|
|
203
319
|
name: 'channel_publish',
|
|
204
|
-
description:
|
|
320
|
+
description: "Publish a message to a channel. If channelId is omitted, publishes to your conversation's channel if you are bound to one; otherwise to the channel of the most recent incoming message this host received on any channel, whether or not you've been shown it. Reactions, reaction removals, deletions and edits don't set it, though an edit of a message you hadn't been shown can count as that message. A message pushed to you rather than posted on a channel never sets it. A subagent has neither default, so it must name a channel.",
|
|
205
321
|
inputSchema: {
|
|
206
322
|
type: 'object',
|
|
207
323
|
properties: {
|
|
208
|
-
channelId: { type: 'string', description:
|
|
324
|
+
channelId: { type: 'string', description: "ID of the channel to publish to (defaults to your conversation's channel if you are bound to one; otherwise the channel of the most recent incoming message this host received on any channel, whether or not you've been shown it, other than a reaction, reaction removal, deletion or edit, though an edit of a message you hadn't been shown can count; a message pushed to you rather than posted on a channel never sets it; required of a subagent)" },
|
|
209
325
|
content: { type: 'string', description: 'Text content to publish' },
|
|
210
326
|
text: { type: 'string', description: 'Alias for content' },
|
|
211
327
|
},
|
|
@@ -275,7 +391,8 @@ const CHANNEL_TOOL_DEFINITIONS = [
|
|
|
275
391
|
// Constructor Options
|
|
276
392
|
// ============================================================================
|
|
277
393
|
/** Bound connector values for notices, logs and an outcome's reason. A
|
|
278
|
-
* PublishOutcome keeps the connector's structured data (`detail`)
|
|
394
|
+
* PublishOutcome keeps the connector's structured data (`detail`) as the
|
|
395
|
+
* connection gives it, its strings redacted (redactedData). */
|
|
279
396
|
export function connectorText(value) {
|
|
280
397
|
let text;
|
|
281
398
|
try {
|
|
@@ -288,6 +405,140 @@ export function connectorText(value) {
|
|
|
288
405
|
const suffix = '… [truncated]';
|
|
289
406
|
return text.length > limit ? text.slice(0, limit - suffix.length) + suffix : text;
|
|
290
407
|
}
|
|
408
|
+
/** One key per destination, its server and channel: unlike joining the two
|
|
409
|
+
* with a separator, no two destinations share one, whatever their ids hold. */
|
|
410
|
+
export function destinationKey(to) {
|
|
411
|
+
return JSON.stringify([to.serverId, to.channelId]);
|
|
412
|
+
}
|
|
413
|
+
/**
|
|
414
|
+
* A failed request's words, bounded, for a reason that a caller composes.
|
|
415
|
+
* This host's own words, for a request that wasn't sent or wasn't answered
|
|
416
|
+
* or for an error of its own, such as its store's, are sentences, and every
|
|
417
|
+
* composition of a reason adds its own ending, so one final period comes
|
|
418
|
+
* off them. A server's error answer keeps its words as they came.
|
|
419
|
+
*/
|
|
420
|
+
function requestErrorText(err) {
|
|
421
|
+
const text = connectorText(err instanceof Error ? err.message : String(err));
|
|
422
|
+
return err instanceof McplRequestError && err.outcome === 'error-response' ? text : text.replace(/(?<!\.)\.$/, '');
|
|
423
|
+
}
|
|
424
|
+
/** A server that isn't up (ServerReach), as a clause the agent reads. */
|
|
425
|
+
function unreachableClause(serverId, reach) {
|
|
426
|
+
switch (reach) {
|
|
427
|
+
case 'gone': return `the "${serverId}" server isn't connected, and this host won't reconnect to it on its own`;
|
|
428
|
+
case 'connecting': return `this host is connecting to the "${serverId}" server`;
|
|
429
|
+
case 'down': return `the "${serverId}" server isn't connected, and this host is reconnecting to it`;
|
|
430
|
+
}
|
|
431
|
+
}
|
|
432
|
+
/** What helps when a server isn't up (ServerReach), as the end of the
|
|
433
|
+
* clause that says so. */
|
|
434
|
+
function unreachableRemedy(reach) {
|
|
435
|
+
switch (reach) {
|
|
436
|
+
case 'gone': return '; if you need it, ask whoever runs this host';
|
|
437
|
+
case 'connecting': return ', so try again in a moment';
|
|
438
|
+
case 'down': return ', so try again later';
|
|
439
|
+
}
|
|
440
|
+
}
|
|
441
|
+
/** Whether an entry's descriptor carries the key a push's placeholder has
|
|
442
|
+
* (ensureChannelRegistered's lazyRegistered metadata), as main reads it for
|
|
443
|
+
* whether the server has declared the channel: a registration or a
|
|
444
|
+
* channels/changed update brings the server's own descriptor, which
|
|
445
|
+
* doesn't normally carry it. The traffic rule doesn't read it, since a
|
|
446
|
+
* server's descriptor can (untargetedPushEntries). */
|
|
447
|
+
function pushPlaceholder(entry) {
|
|
448
|
+
return entry.descriptor.metadata?.lazyRegistered === true;
|
|
449
|
+
}
|
|
450
|
+
/** When reconciling applies a recorded decision: at the server's next
|
|
451
|
+
* registration of the channel, where this host directs its channels'
|
|
452
|
+
* lifecycle then (reconcileChannels, §14.1). A channel made from a push
|
|
453
|
+
* may never be registered at all, so for one the text says "if". */
|
|
454
|
+
function laterClause(entry) {
|
|
455
|
+
return pushPlaceholder(entry)
|
|
456
|
+
? `if the "${entry.serverId}" server registers this channel at a time this host may open and close its channels`
|
|
457
|
+
: `when the "${entry.serverId}" server next registers this channel, if this host may open and close its channels then`;
|
|
458
|
+
}
|
|
459
|
+
/** A channel decision the lifecycle log refused to append, as on a full
|
|
460
|
+
* disk: nothing changed (appendLifecycleEvent). */
|
|
461
|
+
function unrecordedDecision(err) {
|
|
462
|
+
return new ChannelLifecycleError(`this host couldn't record the decision: ${requestErrorText(err)}`, 'unrecorded');
|
|
463
|
+
}
|
|
464
|
+
/** A failure's clause, then more said of the same failure. A server's own
|
|
465
|
+
* words keep their final stop (requestErrorText), so after them the rest
|
|
466
|
+
* is a sentence of its own. */
|
|
467
|
+
function afterClause(clause, more) {
|
|
468
|
+
return /[.!?]$/.test(clause) ? `${clause} ${more.charAt(0).toUpperCase()}${more.slice(1)}` : `${clause}; ${more}`;
|
|
469
|
+
}
|
|
470
|
+
/** A lifecycle failure as a clause: its own words, or its request's. */
|
|
471
|
+
function lifecycleClause(err) {
|
|
472
|
+
return err instanceof ChannelLifecycleError ? err.message : requestErrorText(err);
|
|
473
|
+
}
|
|
474
|
+
/** Why words didn't go out when their channel's registration went away
|
|
475
|
+
* first, at a delivery's wait or at its last check. */
|
|
476
|
+
const CHANNEL_REMOVED_CLAUSE = 'the channel was removed before these words went out';
|
|
477
|
+
/** A tune-out's open answered for a tune-out that ended, or that a later
|
|
478
|
+
* decision or a later tune-out replaced, while the open was out: by
|
|
479
|
+
* openForTuneOut, and by a repeated tune_out whose tune-out isn't the one it
|
|
480
|
+
* read before it waited. */
|
|
481
|
+
export const TUNE_OUT_REPLACED = "The tune-out was recorded, but it isn't in effect any more: it ended, or a later " +
|
|
482
|
+
'decision about the channel or a later tune-out replaced it, while its transport was being opened.';
|
|
483
|
+
/**
|
|
484
|
+
* Why words a send opened their channel for didn't go out. The delivery's
|
|
485
|
+
* wait after the open says it whole (`removed`, `not-open`). The open's own
|
|
486
|
+
* failure is said as one, with what helps where there's a step to take. It
|
|
487
|
+
* names no state of the channel's transport: one decided closed can still
|
|
488
|
+
* be open, after a close that failed.
|
|
489
|
+
*/
|
|
490
|
+
function openFailedReason(err) {
|
|
491
|
+
if (err instanceof ChannelLifecycleError && (err.kind === 'removed' || err.kind === 'not-open'))
|
|
492
|
+
return err.message;
|
|
493
|
+
return `opening the channel for these words didn't complete: ${lifecycleClause(err)}${refusalRemedy(err)}`;
|
|
494
|
+
}
|
|
495
|
+
/** What helps after a lifecycle failure, as the end of the clause that says
|
|
496
|
+
* it: the server state's remedy, whom to ask for a grant, or another try
|
|
497
|
+
* where the channel's target kept changing or the decision couldn't be
|
|
498
|
+
* recorded. Nothing for any other failure. */
|
|
499
|
+
function refusalRemedy(err) {
|
|
500
|
+
if (!(err instanceof ChannelLifecycleError))
|
|
501
|
+
return '';
|
|
502
|
+
if (err.kind === 'unreachable' && err.reach)
|
|
503
|
+
return unreachableRemedy(err.reach);
|
|
504
|
+
if (err.kind === 'not-permitted')
|
|
505
|
+
return '; if you need it, ask whoever runs this host';
|
|
506
|
+
if (err.kind === 'converge')
|
|
507
|
+
return ', so try again';
|
|
508
|
+
if (err.kind === 'unrecorded')
|
|
509
|
+
return ', so try again; if it fails the same way, ask whoever runs this host';
|
|
510
|
+
return '';
|
|
511
|
+
}
|
|
512
|
+
/** Why an open or a close doesn't stand when a later decision about the
|
|
513
|
+
* channel came first (`now`, its desired state since). */
|
|
514
|
+
function supersededClause(action, now) {
|
|
515
|
+
if (now === 'tuned-out')
|
|
516
|
+
return 'it was tuned out meanwhile';
|
|
517
|
+
return action === 'close' ? 'a later decision to keep it open came first' : 'a later decision to close it came first';
|
|
518
|
+
}
|
|
519
|
+
/** A channel tool's refusal of a tuned-out channel, whose cancel is what ends
|
|
520
|
+
* the tune-out, with the backlog it delivers. As an error result the agent
|
|
521
|
+
* reads the pointer itself; `data` names the refusal for an in-process
|
|
522
|
+
* caller. */
|
|
523
|
+
function tunedOutRefusal(tool, channelId) {
|
|
524
|
+
return {
|
|
525
|
+
success: false,
|
|
526
|
+
isError: true,
|
|
527
|
+
error: `Channel "${channelId}" is tuned out: its messages go to the subconscious, and ${tool} doesn't change that. ` +
|
|
528
|
+
`Call tune_out with channelId "${channelId}" and mode "cancel" for it to resume normal attention; cancelling ` +
|
|
529
|
+
'delivers the diverted backlog.',
|
|
530
|
+
data: { refusal: 'tuned-out', channelId },
|
|
531
|
+
};
|
|
532
|
+
}
|
|
533
|
+
/** A clause as the start of a sentence. */
|
|
534
|
+
function sentenceStart(clause) {
|
|
535
|
+
return clause.charAt(0).toUpperCase() + clause.slice(1);
|
|
536
|
+
}
|
|
537
|
+
/** Words as a sentence's end: a stop, unless they end in one already, as a
|
|
538
|
+
* server's own words may. */
|
|
539
|
+
function withStop(text) {
|
|
540
|
+
return /[.!?]$/.test(text) ? text : `${text}.`;
|
|
541
|
+
}
|
|
291
542
|
/**
|
|
292
543
|
* What a channels/publish request that threw establishes. Only a request
|
|
293
544
|
* that never left the host proves nothing was posted. An error response may
|
|
@@ -297,12 +548,7 @@ export function connectorText(value) {
|
|
|
297
548
|
* a failed request this way.
|
|
298
549
|
*/
|
|
299
550
|
function publishErrorOutcome(err, destination, at) {
|
|
300
|
-
|
|
301
|
-
// are sentences, and every composition of the reason adds its own ending,
|
|
302
|
-
// so one final period comes off them. A server's error answer keeps its
|
|
303
|
-
// words as they came.
|
|
304
|
-
const text = connectorText(err instanceof Error ? err.message : String(err));
|
|
305
|
-
const message = err instanceof McplRequestError && err.outcome !== 'error-response' ? text.replace(/(?<!\.)\.$/, '') : text;
|
|
551
|
+
const message = requestErrorText(err);
|
|
306
552
|
const notSent = err instanceof McplRequestError && err.outcome === 'not-sent';
|
|
307
553
|
const detail = err instanceof McplRequestError ? err.data : undefined;
|
|
308
554
|
return {
|
|
@@ -330,16 +576,17 @@ function publishReceiptOutcome(result, destination, at) {
|
|
|
330
576
|
}
|
|
331
577
|
if (receipt.delivered === false) {
|
|
332
578
|
if (receipt.messageId === undefined || receipt.messageId === null) {
|
|
333
|
-
return { status: 'failed', destination, reason: `
|
|
579
|
+
return { status: 'failed', destination, reason: `the "${destination.serverId}" server said it didn't post the message`, at };
|
|
334
580
|
}
|
|
335
581
|
return {
|
|
336
582
|
status: 'unknown',
|
|
337
583
|
destination,
|
|
338
584
|
...(messageId ? { messageId } : {}),
|
|
339
585
|
reason: messageId
|
|
340
|
-
? `
|
|
341
|
-
|
|
342
|
-
|
|
586
|
+
? `the "${destination.serverId}" server said it didn't post the message, yet named message ` +
|
|
587
|
+
`${connectorText(messageId)} as posted (delivery uncertain)`
|
|
588
|
+
: `the "${destination.serverId}" server said it didn't post the message, along with a message id that ` +
|
|
589
|
+
`isn't valid (${connectorText(receipt.messageId)}) (delivery uncertain)`,
|
|
343
590
|
at,
|
|
344
591
|
};
|
|
345
592
|
}
|
|
@@ -347,7 +594,7 @@ function publishReceiptOutcome(result, destination, at) {
|
|
|
347
594
|
status: 'unknown',
|
|
348
595
|
destination,
|
|
349
596
|
...(messageId ? { messageId } : {}),
|
|
350
|
-
reason: `
|
|
597
|
+
reason: `the "${destination.serverId}" server's answer didn't say whether it posted the message (delivery uncertain)`,
|
|
351
598
|
at,
|
|
352
599
|
};
|
|
353
600
|
}
|
|
@@ -367,9 +614,17 @@ export class ChannelRegistry {
|
|
|
367
614
|
homeChannelResolver;
|
|
368
615
|
activeChannelResolver;
|
|
369
616
|
takesGlobalFallback;
|
|
617
|
+
serverConnecting;
|
|
370
618
|
store;
|
|
371
619
|
/** Registered channels, keyed by `{serverId}:{channelId}`. */
|
|
372
620
|
channels = new Map();
|
|
621
|
+
/**
|
|
622
|
+
* Each outgoing stream, by `inferenceId`, with the destinations it has
|
|
623
|
+
* started at (destinationKey): the rest of the stream there goes on there,
|
|
624
|
+
* and its `complete` goes only there (sendOutgoingChunk). An entry goes
|
|
625
|
+
* with the stream's `complete` for its destination.
|
|
626
|
+
*/
|
|
627
|
+
takenStreams = new Map();
|
|
373
628
|
/** Holds back repeats of the line for a message refused because its
|
|
374
629
|
* channel isn't registered (RefusalLines). */
|
|
375
630
|
unknownChannelLines = new RefusalLines();
|
|
@@ -418,9 +673,12 @@ export class ChannelRegistry {
|
|
|
418
673
|
* sent at all.
|
|
419
674
|
*/
|
|
420
675
|
dmClassified = new Map();
|
|
421
|
-
/**
|
|
676
|
+
/** The channel of the most recent incoming message that isn't a reaction,
|
|
677
|
+
* reaction removal, edit or deletion marker, apart from an edit the
|
|
678
|
+
* coalescer delivers on acceptance as the agent's first view: used for
|
|
679
|
+
* speech routing and the default publish. */
|
|
422
680
|
defaultPublishChannel = null;
|
|
423
|
-
/**
|
|
681
|
+
/** The same message's id and thread, used for buildChannelContext. */
|
|
424
682
|
defaultPublishMessageId = null;
|
|
425
683
|
defaultPublishThreadId = undefined;
|
|
426
684
|
/** Per-channel typing indicator timers. */
|
|
@@ -447,9 +705,31 @@ export class ChannelRegistry {
|
|
|
447
705
|
// target before confirming anything. Unlike the tail, which settles a few
|
|
448
706
|
// microtasks after its operation's last check, this drops at that check.
|
|
449
707
|
lifecycleOutstanding = new Map();
|
|
708
|
+
// The removal count each channel's newest outstanding operation was queued
|
|
709
|
+
// under. Where it's older than its server's, every operation still
|
|
710
|
+
// outstanding for the channel cancels when it would run.
|
|
711
|
+
lifecycleQueuedRemovals = new Map();
|
|
450
712
|
// Losing an open receipt does not confirm closure. Keep that distinction
|
|
451
713
|
// private while preserving the public open:boolean availability projection.
|
|
452
714
|
unconfirmedChannelTargets = new WeakSet();
|
|
715
|
+
// Marked entries a close failed for since a receipt or traffic last
|
|
716
|
+
// confirmed them, cleared where the mark is: a failed request's outcome is
|
|
717
|
+
// unknown, so such a close may have closed the channel, where an open,
|
|
718
|
+
// failed or not, can't have. Only a tune-out reads it (openForTuneOut),
|
|
719
|
+
// since its success says the channel's traffic will arrive.
|
|
720
|
+
failedCloseTargets = new WeakSet();
|
|
721
|
+
// Each tune-out's open in flight, by channel and epoch, so tune_out
|
|
722
|
+
// repeated meanwhile waits for that open's answer rather than send another.
|
|
723
|
+
tuneOutOpens = new Map();
|
|
724
|
+
// Entries ensureChannelRegistered made from a push, until a channels/changed
|
|
725
|
+
// update gives one a target (handleChanged's retarget). A registration makes
|
|
726
|
+
// a new entry, which isn't here. Kept by the host, not read from the
|
|
727
|
+
// descriptor, whose metadata a server's own registration supplies.
|
|
728
|
+
untargetedPushEntries = new WeakSet();
|
|
729
|
+
// How many times each server's transport has closed (transportClosed).
|
|
730
|
+
// handleIncoming reads it as a batch arrives, so traffic admitted after a
|
|
731
|
+
// close it arrived before confirms nothing.
|
|
732
|
+
transportCloses = new Map();
|
|
453
733
|
invalidateTransportConfirmation(entry) {
|
|
454
734
|
entry.open = false;
|
|
455
735
|
this.unconfirmedChannelTargets.add(entry);
|
|
@@ -460,12 +740,195 @@ export class ChannelRegistry {
|
|
|
460
740
|
directsLifecycle(serverId) {
|
|
461
741
|
return CapabilityGrant.of(this.serverRegistry.getServer(serverId)).has('channels.lifecycle');
|
|
462
742
|
}
|
|
463
|
-
/**
|
|
464
|
-
*
|
|
743
|
+
/** Whether a decided close holds words back from a channel: only where
|
|
744
|
+
* the host directs the server's lifecycle. Without that grant the host
|
|
745
|
+
* can't close the channel, and words go into a transport that is open,
|
|
746
|
+
* as the open step's engagesDecidedClosed reads it too. */
|
|
747
|
+
closeStands(entry) {
|
|
748
|
+
return this.getDesiredState(entry.serverId, entry.descriptor.id) === 'closed' &&
|
|
749
|
+
this.directsLifecycle(entry.serverId);
|
|
750
|
+
}
|
|
751
|
+
/** Where this server stands for a request this host would make of it
|
|
752
|
+
* (ServerReach). One without a connection's state reads as connected.
|
|
753
|
+
* A closed connection the host is restarting reads as connecting, as
|
|
754
|
+
* one being connected does. */
|
|
755
|
+
serverReach(serverId) {
|
|
756
|
+
const server = this.serverRegistry.getServer(serverId);
|
|
757
|
+
const connecting = this.serverConnecting?.(serverId) ?? false;
|
|
758
|
+
if (!server)
|
|
759
|
+
return connecting ? 'connecting' : 'gone';
|
|
760
|
+
if (server.isConnected === false)
|
|
761
|
+
return connecting ? 'connecting' : server.willReconnect ? 'down' : 'gone';
|
|
762
|
+
return connecting ? 'connecting' : 'up';
|
|
763
|
+
}
|
|
764
|
+
/**
|
|
765
|
+
* Why this host won't open or close this server's channels, for a caller
|
|
766
|
+
* that found its grant without channels.lifecycle (§14.1), which decides:
|
|
767
|
+
* the server's state says why. It isn't up, or it's up without that grant.
|
|
768
|
+
* Neither the grant's name, which is the operator's, nor an empty grant's
|
|
769
|
+
* refusal, which needn't be the server's, reaches the agent.
|
|
770
|
+
*/
|
|
771
|
+
lifecycleRefusal(serverId) {
|
|
772
|
+
const reach = this.serverReach(serverId);
|
|
773
|
+
if (reach !== 'up')
|
|
774
|
+
return new ChannelLifecycleError(unreachableClause(serverId, reach), 'unreachable', reach);
|
|
775
|
+
return new ChannelLifecycleError(`this host isn't permitted to open or close the "${serverId}" server's channels`, 'not-permitted');
|
|
776
|
+
}
|
|
777
|
+
/**
|
|
778
|
+
* Why a send to this server's channels is refused before anything goes
|
|
779
|
+
* out, as one clause with what works from there, for a caller that found
|
|
780
|
+
* no server or a grant without channels.publish (§14.1), which decides:
|
|
781
|
+
* the server's state says why. Plain speech gives it as its reason, and
|
|
782
|
+
* channel_publish and speak_in_channel as theirs, so one refusal has one
|
|
783
|
+
* wording. `checked` is the connection whose grant refused, where that
|
|
784
|
+
* was read before the words waited: one the registry has replaced since
|
|
785
|
+
* says nothing about the server that stands now.
|
|
786
|
+
*/
|
|
787
|
+
sendRefusal(serverId, checked) {
|
|
788
|
+
const now = this.serverRegistry.getServer(serverId);
|
|
789
|
+
const reach = this.serverReach(serverId);
|
|
790
|
+
// A replacement that would take the words is worth another try; one
|
|
791
|
+
// that wouldn't is worded as it stands.
|
|
792
|
+
if (checked && now && now !== checked && reach === 'up' && CapabilityGrant.of(now).has('channels.publish')) {
|
|
793
|
+
return `the "${serverId}" server's connection was replaced while these words waited, so try again`;
|
|
794
|
+
}
|
|
795
|
+
if (reach !== 'up')
|
|
796
|
+
return unreachableClause(serverId, reach) + unreachableRemedy(reach);
|
|
797
|
+
return `this host isn't permitted to post to the "${serverId}" server's channels, and trying again won't change that; ` +
|
|
798
|
+
'if you need it, ask whoever runs this host';
|
|
799
|
+
}
|
|
800
|
+
/**
|
|
801
|
+
* What a failed channel_open or channel_close tells the agent. Its
|
|
802
|
+
* decision was recorded before the server was asked, and reconciling
|
|
803
|
+
* applies it when the server next registers the channel (for a push's
|
|
804
|
+
* placeholder, if it ever does), if this host directs their lifecycle then
|
|
805
|
+
* (laterClause). A decision the log refused changed nothing, so that comes
|
|
806
|
+
* first. A channel no longer registered
|
|
807
|
+
* can't be reached by any channel tool, so its text names none. A later
|
|
808
|
+
* decision that came first is what stands, so that comes next. Then the
|
|
809
|
+
* server's state: one that isn't up gets the change when it's back, though
|
|
810
|
+
* not a backscroll's history. For the request's own failure, its state is
|
|
811
|
+
* read now, since a request out when the server dropped may have taken
|
|
812
|
+
* effect, and reconciling settles it either way. A decision already in
|
|
813
|
+
* effect, with no other work for the channel under way, says so, as one
|
|
814
|
+
* whose backscroll alone failed is. Then the failure's kind, since each
|
|
815
|
+
* has its own next step (ChannelLifecycleError). A request's own failure
|
|
816
|
+
* is in the connection's words.
|
|
817
|
+
*/
|
|
818
|
+
lifecycleFailureText(action, entry, err, opts) {
|
|
819
|
+
const channel = `"${entry.descriptor.id}"`;
|
|
820
|
+
const tool = action === 'open' ? 'channel_open' : 'channel_close';
|
|
821
|
+
const done = action === 'open' ? 'opened' : 'closed';
|
|
822
|
+
const later = laterClause(entry);
|
|
823
|
+
// A decision never recorded is no decision a later one overtook, and
|
|
824
|
+
// nothing about the channel changed, whatever its transport's state.
|
|
825
|
+
if (err instanceof ChannelLifecycleError && err.kind === 'unrecorded') {
|
|
826
|
+
return `Nothing changed for channel ${channel}: ${err.message}, so nothing was sent to the server. ` +
|
|
827
|
+
`Calling ${tool} again tries again; if it fails the same way, ask whoever runs this host.`;
|
|
828
|
+
}
|
|
829
|
+
const failure = err instanceof ChannelLifecycleError ? err : undefined;
|
|
830
|
+
const now = this.getDesiredState(entry.serverId, entry.descriptor.id);
|
|
831
|
+
const current = this.channels.get(`${entry.serverId}:${entry.descriptor.id}`);
|
|
832
|
+
if (!current) {
|
|
833
|
+
// Its registration may have gone at the server's word or at this
|
|
834
|
+
// host's (removeServer). Only a failure that says which (cancelled,
|
|
835
|
+
// unlisted) names it; otherwise the server's state where it isn't up,
|
|
836
|
+
// and a request's own words where it failed with them. Another
|
|
837
|
+
// failure's words are about a request whose channel is gone.
|
|
838
|
+
const reach = this.serverReach(entry.serverId);
|
|
839
|
+
const why = failure?.kind === 'cancelled' || failure?.kind === 'unlisted' ? `: ${failure.message}`
|
|
840
|
+
: reach !== 'up' ? `: ${unreachableClause(entry.serverId, reach)}` : '';
|
|
841
|
+
// A tune-out is in effect already: only its transport waits for the
|
|
842
|
+
// server's next registration.
|
|
843
|
+
const stays = now === 'tuned-out' ? 'It was tuned out meanwhile, and that stays recorded.'
|
|
844
|
+
: `Its ${now === 'closed' ? 'close' : 'open'} stays recorded, and happens ${later}.`;
|
|
845
|
+
return `Channel ${channel} isn't registered here any more${why}. ${stays}` +
|
|
846
|
+
(reach === 'gone' ? ' If you need the server back, ask whoever runs this host.' : '') +
|
|
847
|
+
(failure === undefined ? ` ${withStop(lifecycleClause(err))}` : '');
|
|
848
|
+
}
|
|
849
|
+
// A tune-out sends the channel's messages to the subconscious, and
|
|
850
|
+
// channel_open refuses a tuned-out channel.
|
|
851
|
+
if (action === 'open' ? now !== 'open' : now !== 'closed') {
|
|
852
|
+
if (action === 'open' && now === 'tuned-out') {
|
|
853
|
+
return `Channel ${channel} was tuned out meanwhile: its messages go to the subconscious, and channel_open doesn't ` +
|
|
854
|
+
`change that. Call tune_out with channelId ${channel} and mode "cancel" for it to resume normal attention.`;
|
|
855
|
+
}
|
|
856
|
+
// The later decision's own work settles the transport, and its call
|
|
857
|
+
// says what became of it, so this says only that this call's change
|
|
858
|
+
// doesn't stand.
|
|
859
|
+
return `Channel ${channel}: ${supersededClause(action, now)}, so this ${action} doesn't stand. Call ${tool} again to ` +
|
|
860
|
+
`${action} it.`;
|
|
861
|
+
}
|
|
862
|
+
const reach = failure ? (failure.kind === 'unreachable' ? failure.reach : undefined) : this.serverReach(entry.serverId);
|
|
863
|
+
if (reach !== undefined && reach !== 'up') {
|
|
864
|
+
// Reconciling opens a channel, but asks for no history.
|
|
865
|
+
const history = action === 'open' && opts?.history;
|
|
866
|
+
return `${sentenceStart(unreachableClause(entry.serverId, reach))}, so channel ${channel} may not be ` +
|
|
867
|
+
`${action === 'open' ? 'open' : 'closed'} there yet. The ${action} is recorded and happens ${later}` +
|
|
868
|
+
(history
|
|
869
|
+
? ', but the history you asked for doesn\'t come with it: calling channel_open with backscroll once the server is ' +
|
|
870
|
+
'connected asks for it.'
|
|
871
|
+
: `, so there's no need to call ${tool} again.`) +
|
|
872
|
+
(reach === 'gone' ? ' If you need the server back, ask whoever runs this host.' : '') +
|
|
873
|
+
(action === 'open' ? ' channel_close withdraws it.' : '');
|
|
874
|
+
}
|
|
875
|
+
const said = lifecycleClause(err);
|
|
876
|
+
// Other work for the channel still under way (lifecycleOutstanding,
|
|
877
|
+
// released as each operation's last look ends) may change its state.
|
|
878
|
+
const settled = !this.lifecycleOutstanding.has(this.lifecycleKey(entry.serverId, entry.descriptor.id));
|
|
879
|
+
// The registry's own reading, as its checks make it (channel_open's
|
|
880
|
+
// already-open return, the decline's refusal, delivery): a request that
|
|
881
|
+
// failed leaves the open flag as it was, and the unconfirmed mark counts
|
|
882
|
+
// only while the channel isn't open (runLifecycleOperation).
|
|
883
|
+
const inEffect = current !== undefined && settled && (action === 'open'
|
|
884
|
+
? current.open
|
|
885
|
+
: !current.open && !this.unconfirmedChannelTargets.has(current));
|
|
886
|
+
if (inEffect) {
|
|
887
|
+
// What was asked already holds. Without the grant, nothing more can be
|
|
888
|
+
// asked of the server, so calling again won't change anything.
|
|
889
|
+
const state = `Channel ${channel} is ${action === 'open' ? 'open' : 'closed'}`;
|
|
890
|
+
if (action === 'open' && opts?.history) {
|
|
891
|
+
return failure?.kind === 'not-permitted'
|
|
892
|
+
? `${state}, but the history you asked for didn't come: ${failure.message}, so calling channel_open again ` +
|
|
893
|
+
"won't change that. If you need it, ask whoever runs this host."
|
|
894
|
+
: withStop(`${state}, but the history you asked for didn't come: ${said}`) +
|
|
895
|
+
' Calling channel_open again with backscroll tries once more.';
|
|
896
|
+
}
|
|
897
|
+
return failure?.kind === 'not-permitted'
|
|
898
|
+
? `${state}. ${sentenceStart(failure.message)}, so it sent the server nothing.`
|
|
899
|
+
: withStop(`${state}, though this call didn't complete: ${said}`);
|
|
900
|
+
}
|
|
901
|
+
switch (failure?.kind) {
|
|
902
|
+
case 'not-permitted':
|
|
903
|
+
// The decision was recorded before the refusal, and reconciling
|
|
904
|
+
// applies it at a registration whose grant allows it.
|
|
905
|
+
return `${sentenceStart(failure.message)}, so this ${action} of channel ${channel} didn't go through, and calling ${tool} ` +
|
|
906
|
+
`again won't change that. The ${action} stays recorded, and happens ${later}. If you need it, ask whoever runs this host.`;
|
|
907
|
+
case 'cancelled':
|
|
908
|
+
case 'unlisted':
|
|
909
|
+
return `Channel ${channel} wasn't ${done}: ${failure.message}. The ${action} stays recorded, and happens ${later}.`;
|
|
910
|
+
case 'converge':
|
|
911
|
+
return `Channel ${channel} wasn't ${done}: ${failure.message}. The ${action} stays recorded, and calling ${tool} again ` +
|
|
912
|
+
'tries once more.';
|
|
913
|
+
case 'substituted':
|
|
914
|
+
// Only an open is answered for another channel.
|
|
915
|
+
return `Channel ${channel} wasn't ${done}: ${failure.message}. The ${action} stays recorded, and this host tries it ` +
|
|
916
|
+
`again ${later}; calling ${tool} again is likely to get the same answer. channel_close withdraws it.`;
|
|
917
|
+
}
|
|
918
|
+
return `${action === 'open' ? 'Opening' : 'Closing'} channel ${channel} didn't complete; the ${action} stays recorded, and this ` +
|
|
919
|
+
`host tries it again ${later}, or now if you call ${tool} again. ${withStop(said)}`;
|
|
920
|
+
}
|
|
921
|
+
/** A registration's entry, or a push's (ensureChannelRegistered): nothing
|
|
922
|
+
* about its transport is known until a receipt for its target confirms it
|
|
923
|
+
* open or closed, or the channel's traffic shows it open, which it does
|
|
924
|
+
* where the host doesn't direct the lifecycle, and for a push's entry
|
|
925
|
+
* decided open or tuned out that no update has given a target
|
|
926
|
+
* (handleIncoming). */
|
|
465
927
|
registerEntry(key, serverId, descriptor) {
|
|
466
928
|
const entry = { serverId, descriptor, open: false };
|
|
467
929
|
this.channels.set(key, entry);
|
|
468
930
|
this.unconfirmedChannelTargets.add(entry);
|
|
931
|
+
return entry;
|
|
469
932
|
}
|
|
470
933
|
hasPendingLifecycle(entry) {
|
|
471
934
|
return this.channelLifecycleTails.has(this.lifecycleKey(entry.serverId, entry.descriptor.id));
|
|
@@ -498,6 +961,7 @@ export class ChannelRegistry {
|
|
|
498
961
|
this.homeChannelResolver = options?.homeChannelResolver;
|
|
499
962
|
this.activeChannelResolver = options?.activeChannelResolver;
|
|
500
963
|
this.takesGlobalFallback = options?.takesGlobalFallback;
|
|
964
|
+
this.serverConnecting = options?.serverConnecting;
|
|
501
965
|
this.store = options?.store;
|
|
502
966
|
this.initializeLifecycleStore();
|
|
503
967
|
this.initializeLabelHistoryStore();
|
|
@@ -600,13 +1064,16 @@ export class ChannelRegistry {
|
|
|
600
1064
|
// channel decided open (or tuned out) is opened at its new target.
|
|
601
1065
|
if (!sameChannelTarget(existing.descriptor, channel)) {
|
|
602
1066
|
this.invalidateTransportConfirmation(existing);
|
|
1067
|
+
this.untargetedPushEntries.delete(existing);
|
|
603
1068
|
// An operation queued or running for this channel reads its target
|
|
604
1069
|
// again before it confirms anything, and after a failed RPC, so it
|
|
605
|
-
// opens the new one
|
|
606
|
-
//
|
|
1070
|
+
// opens the new one, unless it was queued before its server's
|
|
1071
|
+
// registrations were last removed: that one cancels when it would
|
|
1072
|
+
// run. So a channel decided open (or tuned out) is reconciled here
|
|
1073
|
+
// unless work queued since then is outstanding.
|
|
607
1074
|
const desired = this.getDesiredState(serverId, channel.id);
|
|
608
1075
|
if ((desired === 'open' || desired === 'tuned-out') &&
|
|
609
|
-
!this.
|
|
1076
|
+
!this.outstandingWorkCarriesOut(serverId, this.lifecycleKey(serverId, channel.id))) {
|
|
610
1077
|
retargeted.push(channel);
|
|
611
1078
|
}
|
|
612
1079
|
}
|
|
@@ -689,6 +1156,9 @@ export class ChannelRegistry {
|
|
|
689
1156
|
*/
|
|
690
1157
|
async handleIncoming(serverId, params, responder) {
|
|
691
1158
|
const results = [];
|
|
1159
|
+
// The batch came on the transport open now: a close after this point
|
|
1160
|
+
// (transportClosed) leaves its traffic nothing to confirm.
|
|
1161
|
+
const closesAtArrival = this.transportCloses.get(serverId) ?? 0;
|
|
692
1162
|
for (const message of params.messages) {
|
|
693
1163
|
if (!message || typeof message.channelId !== 'string' || !message.channelId
|
|
694
1164
|
|| typeof message.messageId !== 'string' || !message.messageId) {
|
|
@@ -714,17 +1184,6 @@ export class ChannelRegistry {
|
|
|
714
1184
|
// conversion — decoding an unregistered sender's payload (including
|
|
715
1185
|
// inline base64) is allocation and parsing work done for a message
|
|
716
1186
|
// that must be rejected (Sol, PR #79 re-review blocker 2).
|
|
717
|
-
// Lazy-register the channel if we've never seen it. A channel can deliver
|
|
718
|
-
// an incoming message before its channels/register (boot enumeration) or
|
|
719
|
-
// channels/changed (post-boot create / View-permission grant) round-trip
|
|
720
|
-
// lands — or the registration event can be missed entirely (e.g. the bot
|
|
721
|
-
// gains visibility in a way that fires neither `channelCreate` nor a
|
|
722
|
-
// View-permission transition). Without a registry entry, routeSpeech()
|
|
723
|
-
// can't resolve this channel as an outbound locus and the agent's reply
|
|
724
|
-
// is silently dropped, even though this very message proves the channel
|
|
725
|
-
// is reachable. The inbound message carries enough to make it publishable,
|
|
726
|
-
// so register it here; a later authoritative channels/register or
|
|
727
|
-
// channels/changed will overwrite this descriptor with the richer one.
|
|
728
1187
|
// §14.5: channels/incoming is validated against the ACTUALLY
|
|
729
1188
|
// REGISTERED channel. An unknown claimed channelId is rejected
|
|
730
1189
|
// per-message with an itemized result — never minted by its first
|
|
@@ -732,8 +1191,8 @@ export class ChannelRegistry {
|
|
|
732
1191
|
// self-attest a channel identity without ever passing
|
|
733
1192
|
// channels/register authorization). A server whose channel genuinely
|
|
734
1193
|
// exists registers it first; discord's DM case goes through
|
|
735
|
-
// ensureChannelRegistered on push/event, which creates a
|
|
736
|
-
//
|
|
1194
|
+
// ensureChannelRegistered on push/event, which creates a routable
|
|
1195
|
+
// entry that isn't open, rather than an open self-attested one.
|
|
737
1196
|
const incomingKey = `${serverId}:${message.channelId}`;
|
|
738
1197
|
if (!this.channels.has(incomingKey)) {
|
|
739
1198
|
// Loud, coalesced or not, like every other refusal of a message, but
|
|
@@ -809,32 +1268,50 @@ export class ChannelRegistry {
|
|
|
809
1268
|
// A coalesced item is "accepted" only once the coalescer admits it, so
|
|
810
1269
|
// for those this runs after the hook (below).
|
|
811
1270
|
const incomingEntry = this.channels.get(incomingKey);
|
|
812
|
-
const markAccepted = () => {
|
|
813
|
-
|
|
814
|
-
|
|
815
|
-
|
|
816
|
-
//
|
|
817
|
-
// the
|
|
818
|
-
|
|
819
|
-
|
|
820
|
-
|
|
821
|
-
|
|
822
|
-
|
|
823
|
-
//
|
|
1271
|
+
const markAccepted = (firstView = false) => {
|
|
1272
|
+
// Non-conversational markers (a reaction added or removed, an edit, a
|
|
1273
|
+
// deletion) are ABOUT a message, not one the agent replies to: they
|
|
1274
|
+
// must not retarget the default publish locus or become
|
|
1275
|
+
// `context.incoming`'s reply anchor. An edit the coalescer delivered
|
|
1276
|
+
// as the agent's first view counts as the message it replaced.
|
|
1277
|
+
if (!isMarkerTagged(message.tags, firstView)) {
|
|
1278
|
+
this.defaultPublishChannel = message.channelId;
|
|
1279
|
+
this.defaultPublishMessageId = message.messageId;
|
|
1280
|
+
this.defaultPublishThreadId = message.threadId;
|
|
1281
|
+
}
|
|
1282
|
+
// Where the host directs this server's lifecycle, traffic shows the
|
|
1283
|
+
// transport open only for a channel still decided open or tuned out,
|
|
1284
|
+
// and, but for one exception, only for a confirmed target: after a
|
|
1285
|
+
// retarget, traffic for this id may still come from the old
|
|
1286
|
+
// subscription, and a close receipt that landed first (or during the
|
|
1287
|
+
// coalescer's await) stands. The exception is an entry made from a
|
|
1288
|
+
// push that no update has given a target (untargetedPushEntries):
|
|
1289
|
+
// there's no earlier target its traffic could come from, so for the
|
|
1290
|
+
// receipt rule's own reason its traffic shows the transport open. It
|
|
1291
|
+
// stops being one when a registration replaces it (registerEntry) or
|
|
1292
|
+
// a channels/changed update gives it a target (handleChanged's
|
|
1293
|
+
// retarget), and the receipt rule holds from then. Where the host
|
|
1294
|
+
// doesn't direct the lifecycle, the server opens its own channels and
|
|
1295
|
+
// its traffic is the only evidence the host gets, so it marks the
|
|
824
1296
|
// channel open, as it always has. The entry is the one the message
|
|
825
1297
|
// was accepted for: one a re-registration put in its place meanwhile
|
|
826
|
-
// waits for its own evidence.
|
|
827
|
-
//
|
|
1298
|
+
// waits for its own evidence. Traffic from a transport that has closed
|
|
1299
|
+
// since its batch arrived (here after the coalescer's await, or behind
|
|
1300
|
+
// a sibling's) is no evidence either: the close withdrew what that
|
|
1301
|
+
// transport confirmed, and its connection's grant is empty until the
|
|
1302
|
+
// next one's. Durable desired state still changes exclusively through
|
|
1303
|
+
// lifecycle operations. A marker is evidence like any other message.
|
|
1304
|
+
if ((this.transportCloses.get(serverId) ?? 0) !== closesAtArrival)
|
|
1305
|
+
return;
|
|
828
1306
|
if (this.directsLifecycle(serverId)) {
|
|
829
|
-
if (this.unconfirmedChannelTargets.has(incomingEntry))
|
|
1307
|
+
if (this.unconfirmedChannelTargets.has(incomingEntry) && !this.untargetedPushEntries.has(incomingEntry))
|
|
830
1308
|
return;
|
|
831
1309
|
const desired = this.getDesiredState(serverId, message.channelId);
|
|
832
1310
|
if (desired !== 'open' && desired !== 'tuned-out')
|
|
833
1311
|
return;
|
|
834
1312
|
}
|
|
835
|
-
|
|
836
|
-
|
|
837
|
-
}
|
|
1313
|
+
this.unconfirmedChannelTargets.delete(incomingEntry);
|
|
1314
|
+
this.failedCloseTargets.delete(incomingEntry);
|
|
838
1315
|
incomingEntry.open = true;
|
|
839
1316
|
};
|
|
840
1317
|
if (!coalesced)
|
|
@@ -881,9 +1358,9 @@ export class ChannelRegistry {
|
|
|
881
1358
|
// the coalescer, which replaces, appends or withdraws. Malformed
|
|
882
1359
|
// `coalesce` is a per-message failure; siblings are unaffected.
|
|
883
1360
|
try {
|
|
884
|
-
const result = await this.handleCoalescedIncoming(serverId, message, event);
|
|
1361
|
+
const { firstView, ...result } = await this.handleCoalescedIncoming(serverId, message, event);
|
|
885
1362
|
if (result.accepted)
|
|
886
|
-
markAccepted();
|
|
1363
|
+
markAccepted(firstView === true);
|
|
887
1364
|
results.push(result);
|
|
888
1365
|
}
|
|
889
1366
|
catch (error) {
|
|
@@ -929,15 +1406,17 @@ export class ChannelRegistry {
|
|
|
929
1406
|
* locus. A push event from a closed channel must never mutate lifecycle
|
|
930
1407
|
* state: direct-address events are intentionally usable without subscribing.
|
|
931
1408
|
*
|
|
932
|
-
*
|
|
933
|
-
*
|
|
934
|
-
*
|
|
935
|
-
*
|
|
936
|
-
*
|
|
937
|
-
*
|
|
938
|
-
*
|
|
939
|
-
*
|
|
940
|
-
*
|
|
1409
|
+
* For channels that only ever arrive as push/events rather than
|
|
1410
|
+
* channels/incoming — the motivating case is Discord DMs, which
|
|
1411
|
+
* discord-mcpl forwards via push/event with the channel closed
|
|
1412
|
+
* (`channelIsOpen:false`). Such a channel is never registered, so
|
|
1413
|
+
* routeSpeech() can't resolve it and the agent's reply is silently dropped
|
|
1414
|
+
* even though the inbound message proves the channel is reachable (item-3
|
|
1415
|
+
* redux, DM sub-case). Its entry starts with its transport unknown, as a
|
|
1416
|
+
* registration's does. Its traffic shows it open, for a channel decided
|
|
1417
|
+
* open or tuned out, until an update gives it a target (handleIncoming).
|
|
1418
|
+
* Idempotent: a later authoritative channels/register or channels/changed
|
|
1419
|
+
* overwrites this descriptor with the richer one.
|
|
941
1420
|
*/
|
|
942
1421
|
ensureChannelRegistered(serverId, channelId, label, extraMetadata) {
|
|
943
1422
|
const existing = this.findChannelEntry(channelId);
|
|
@@ -945,7 +1424,7 @@ export class ChannelRegistry {
|
|
|
945
1424
|
// Backfill identity onto a bare lazy registration: a DM that first
|
|
946
1425
|
// arrived with no label/recipient info gets a usable name the next
|
|
947
1426
|
// time a message reveals it (labels must show people, not ids).
|
|
948
|
-
if (existing
|
|
1427
|
+
if (pushPlaceholder(existing) &&
|
|
949
1428
|
label && existing.descriptor.label === channelId) {
|
|
950
1429
|
const metadata = extraMetadata
|
|
951
1430
|
? { ...existing.descriptor.metadata, ...extraMetadata }
|
|
@@ -975,18 +1454,19 @@ export class ChannelRegistry {
|
|
|
975
1454
|
// an append that throws registers nothing, so the next push tries again.
|
|
976
1455
|
if (label)
|
|
977
1456
|
this.appendLabelSighting(channelId, label, extractDmMeta(extraMetadata));
|
|
978
|
-
|
|
979
|
-
|
|
980
|
-
|
|
981
|
-
|
|
982
|
-
|
|
983
|
-
|
|
984
|
-
|
|
985
|
-
|
|
986
|
-
|
|
987
|
-
|
|
988
|
-
|
|
1457
|
+
// Its transport is as unknown as a registration's (registerEntry). After
|
|
1458
|
+
// a restart, a push for a channel no registration has comes here, and
|
|
1459
|
+
// the server may still hold a channel an earlier process opened. Counting
|
|
1460
|
+
// it confirmed closed would answer a close or a decline as already done
|
|
1461
|
+
// and send nothing, even where the server still delivers.
|
|
1462
|
+
const entry = this.registerEntry(`${serverId}:${channelId}`, serverId, {
|
|
1463
|
+
id: channelId,
|
|
1464
|
+
type: serverId,
|
|
1465
|
+
label: label ?? channelId,
|
|
1466
|
+
direction: 'bidirectional',
|
|
1467
|
+
metadata: { lazyRegistered: true, ...(extraMetadata ?? {}) },
|
|
989
1468
|
});
|
|
1469
|
+
this.untargetedPushEntries.add(entry);
|
|
990
1470
|
this.emitTraceFn({
|
|
991
1471
|
type: 'mcpl:channel-lazy-registered',
|
|
992
1472
|
serverId,
|
|
@@ -1086,7 +1566,10 @@ export class ChannelRegistry {
|
|
|
1086
1566
|
// Accessors
|
|
1087
1567
|
// ==========================================================================
|
|
1088
1568
|
/**
|
|
1089
|
-
* Get the default publish channel ID
|
|
1569
|
+
* Get the default publish channel ID: the channel of the most recent
|
|
1570
|
+
* incoming message that isn't a reaction, reaction removal, edit or
|
|
1571
|
+
* deletion marker, apart from an edit the coalescer delivers on acceptance
|
|
1572
|
+
* as the agent's first view.
|
|
1090
1573
|
*/
|
|
1091
1574
|
getDefaultPublishChannel() {
|
|
1092
1575
|
return this.defaultPublishChannel;
|
|
@@ -1104,7 +1587,7 @@ export class ChannelRegistry {
|
|
|
1104
1587
|
*/
|
|
1105
1588
|
isDeclaredChannel(serverId, channelId) {
|
|
1106
1589
|
const entry = this.channels.get(`${serverId}:${channelId}`);
|
|
1107
|
-
return !!entry && !entry
|
|
1590
|
+
return !!entry && !pushPlaceholder(entry);
|
|
1108
1591
|
}
|
|
1109
1592
|
getDescriptor(channelId) {
|
|
1110
1593
|
return this.findChannelEntry(channelId)?.descriptor;
|
|
@@ -1115,8 +1598,16 @@ export class ChannelRegistry {
|
|
|
1115
1598
|
const label = this.channels.get(`${serverId}:${channelId}`)?.descriptor.label;
|
|
1116
1599
|
return typeof label === 'string' && label.length > 0 ? label : undefined;
|
|
1117
1600
|
}
|
|
1118
|
-
|
|
1119
|
-
|
|
1601
|
+
/** Whether `channelId`'s transport is open: on `serverId` where the caller
|
|
1602
|
+
* knows the channel's server, and otherwise on the first server found to
|
|
1603
|
+
* register that id (findChannelEntry). The map's key joins the two ids
|
|
1604
|
+
* with a colon, so another server's entry can sit under a key: it has to
|
|
1605
|
+
* be this server's (as in streamingServerAt). */
|
|
1606
|
+
isChannelOpen(channelId, serverId) {
|
|
1607
|
+
if (serverId === undefined)
|
|
1608
|
+
return this.findChannelEntry(channelId)?.open === true;
|
|
1609
|
+
const entry = this.channels.get(`${serverId}:${channelId}`);
|
|
1610
|
+
return entry?.serverId === serverId && entry.open === true;
|
|
1120
1611
|
}
|
|
1121
1612
|
getDesiredState(serverId, channelId) {
|
|
1122
1613
|
return this.desiredStates.get(this.lifecycleKey(serverId, channelId))?.state;
|
|
@@ -1173,7 +1664,13 @@ export class ChannelRegistry {
|
|
|
1173
1664
|
case 'skip_reply':
|
|
1174
1665
|
return this.handleToolSkipReply(input);
|
|
1175
1666
|
default:
|
|
1176
|
-
|
|
1667
|
+
// Not every agent is given every channel tool, so the refusal points
|
|
1668
|
+
// to the ones this agent has rather than listing them all.
|
|
1669
|
+
return {
|
|
1670
|
+
success: false,
|
|
1671
|
+
error: `There's no channel tool "${toolName}", so nothing ran. Use one of the channel tools you were given.`,
|
|
1672
|
+
isError: true,
|
|
1673
|
+
};
|
|
1177
1674
|
}
|
|
1178
1675
|
}
|
|
1179
1676
|
// ==========================================================================
|
|
@@ -1187,8 +1684,9 @@ export class ChannelRegistry {
|
|
|
1187
1684
|
buildChannelContext(agentName) {
|
|
1188
1685
|
const openChannels = this.getOpenChannels();
|
|
1189
1686
|
// Resolve the outbound locus the SAME way routeSpeech does, so the agent is
|
|
1190
|
-
// told the channel its speech will actually land in
|
|
1191
|
-
//
|
|
1687
|
+
// told the channel its speech will actually land in (none, when its server
|
|
1688
|
+
// declared it inbound-only, since speech isn't posted there): a conversation
|
|
1689
|
+
// fork's home channel, else this turn's channel (single trunk agent — item-3
|
|
1192
1690
|
// redux: its locus, else its triggering channel), else the global default
|
|
1193
1691
|
// (heartbeats). Without this, a fork
|
|
1194
1692
|
// was advertised the global locus but published somewhere else; and a trunk
|
|
@@ -1206,7 +1704,10 @@ export class ChannelRegistry {
|
|
|
1206
1704
|
return undefined;
|
|
1207
1705
|
}
|
|
1208
1706
|
const context = {};
|
|
1209
|
-
// Incoming: the most
|
|
1707
|
+
// Incoming: the most recent inbound message that isn't a reaction,
|
|
1708
|
+
// reaction removal, edit or deletion marker, apart from an edit the
|
|
1709
|
+
// coalescer delivers on acceptance as the agent's first view (what the
|
|
1710
|
+
// agent is replying to).
|
|
1210
1711
|
// Left process-global — per-channel inbound tracking (the right messageId for
|
|
1211
1712
|
// a fork's own channel) is a separate concern from the outbound routing fix.
|
|
1212
1713
|
if (fallback && this.defaultPublishMessageId) {
|
|
@@ -1216,8 +1717,10 @@ export class ChannelRegistry {
|
|
|
1216
1717
|
threadId: this.defaultPublishThreadId,
|
|
1217
1718
|
};
|
|
1218
1719
|
}
|
|
1219
|
-
// Default outgoing: the resolved outbound locus (home channel for forks)
|
|
1220
|
-
|
|
1720
|
+
// Default outgoing: the resolved outbound locus (home channel for forks),
|
|
1721
|
+
// unless its server declared it inbound-only: routeSpeech publishes nothing
|
|
1722
|
+
// there, so it isn't where the agent's speech goes.
|
|
1723
|
+
if (outgoing && !this.inboundOnlyServer(outgoing)) {
|
|
1221
1724
|
context.defaultOutgoing = {
|
|
1222
1725
|
channelId: outgoing,
|
|
1223
1726
|
};
|
|
@@ -1238,7 +1741,7 @@ export class ChannelRegistry {
|
|
|
1238
1741
|
*/
|
|
1239
1742
|
removeServer(serverId) {
|
|
1240
1743
|
// Every lifecycle operation queued for this server is cancelled when it
|
|
1241
|
-
// would run (
|
|
1744
|
+
// would run (a ChannelLifecycleError of kind `cancelled`), so none acts on a closing
|
|
1242
1745
|
// connection or on a later re-registration's entries.
|
|
1243
1746
|
this.serverRemovals.set(serverId, (this.serverRemovals.get(serverId) ?? 0) + 1);
|
|
1244
1747
|
for (const [key, entry] of this.channels) {
|
|
@@ -1254,6 +1757,42 @@ export class ChannelRegistry {
|
|
|
1254
1757
|
}
|
|
1255
1758
|
// Desired state and migration markers deliberately survive disconnects.
|
|
1256
1759
|
}
|
|
1760
|
+
/**
|
|
1761
|
+
* The server's transport closed. Whatever it confirmed about a channel,
|
|
1762
|
+
* open or closed, held for that transport only, so each of the server's
|
|
1763
|
+
* channels reads as a registration's does: not open, and not confirmed
|
|
1764
|
+
* closed. Where the host directs the server's lifecycle, a receipt
|
|
1765
|
+
* confirms it again: a `channel_open` asks the server, and delivery opens
|
|
1766
|
+
* before it publishes (an untargeted push entry's traffic confirms it, as
|
|
1767
|
+
* before). Where the host doesn't, its traffic does, as after a
|
|
1768
|
+
* registration. The entries, their desired state, labels and tune-out
|
|
1769
|
+
* state stay, since the server is expected back (`removeServer` is for one
|
|
1770
|
+
* that isn't).
|
|
1771
|
+
*
|
|
1772
|
+
* What was under way here at the close confirms nothing afterwards
|
|
1773
|
+
* (transportCloses). Traffic that arrived before the close and is admitted
|
|
1774
|
+
* after it, behind the coalescer's await, marks nothing open
|
|
1775
|
+
* (handleIncoming). A lifecycle request sent before the close is answered
|
|
1776
|
+
* for an older transport: its failure withdraws the open flag, and its
|
|
1777
|
+
* receipt confirms nothing, and the operation tries again, which on the
|
|
1778
|
+
* closed connection is refused as unreachable, so the decision waits for
|
|
1779
|
+
* the next registration (runLifecycleOperation's sameTarget). What the
|
|
1780
|
+
* connection holds across the boundary is another matter: it reaches
|
|
1781
|
+
* handleIncoming after the next transport's grant, as that transport's
|
|
1782
|
+
* traffic (resetPolicyForTransportBoundary), as it does after a
|
|
1783
|
+
* registration.
|
|
1784
|
+
*
|
|
1785
|
+
* The framework calls this first in its handler for the connection's
|
|
1786
|
+
* `close`, so a registration on the next transport, whose entries are new,
|
|
1787
|
+
* can't come first and lose its confirmations to it.
|
|
1788
|
+
*/
|
|
1789
|
+
transportClosed(serverId) {
|
|
1790
|
+
this.transportCloses.set(serverId, (this.transportCloses.get(serverId) ?? 0) + 1);
|
|
1791
|
+
for (const entry of this.channels.values()) {
|
|
1792
|
+
if (entry.serverId === serverId)
|
|
1793
|
+
this.invalidateTransportConfirmation(entry);
|
|
1794
|
+
}
|
|
1795
|
+
}
|
|
1257
1796
|
/**
|
|
1258
1797
|
* Stop all typing intervals and clear all channel registrations.
|
|
1259
1798
|
*/
|
|
@@ -1289,16 +1828,9 @@ export class ChannelRegistry {
|
|
|
1289
1828
|
const event = item;
|
|
1290
1829
|
if (typeof event.serverId !== 'string')
|
|
1291
1830
|
continue;
|
|
1292
|
-
|
|
1293
|
-
|
|
1294
|
-
(
|
|
1295
|
-
(event.desired === 'tuned-out' && event.tuneOut))) {
|
|
1296
|
-
this.desiredStates.set(this.lifecycleKey(event.serverId, event.channelId), {
|
|
1297
|
-
state: event.desired,
|
|
1298
|
-
source: typeof event.source === "string" ? event.source : "unknown",
|
|
1299
|
-
tuneOut: event.desired === 'tuned-out' ? event.tuneOut : undefined,
|
|
1300
|
-
wakeCount: 0,
|
|
1301
|
-
});
|
|
1831
|
+
const decision = desiredStateRecord(item);
|
|
1832
|
+
if (decision) {
|
|
1833
|
+
this.desiredStates.set(this.lifecycleKey(decision.serverId, decision.channelId), { state: decision.state, source: decision.source, tuneOut: decision.tuneOut, wakeCount: 0 });
|
|
1302
1834
|
}
|
|
1303
1835
|
else if (event.kind === 'tune-out-wake' &&
|
|
1304
1836
|
typeof event.channelId === 'string' &&
|
|
@@ -1320,7 +1852,9 @@ export class ChannelRegistry {
|
|
|
1320
1852
|
/**
|
|
1321
1853
|
* Each writer appends its record here before it changes memory for it, so
|
|
1322
1854
|
* an append that throws, as on a full disk, fails the operation with that
|
|
1323
|
-
* change unmade, and memory and the log still agree. A
|
|
1855
|
+
* change unmade, and memory and the log still agree. A record that changes
|
|
1856
|
+
* no memory, as a decline's of the invitation it declined, is its
|
|
1857
|
+
* caller's to handle (handleToolDecline). A retry then records
|
|
1324
1858
|
* the change rather than finding it in memory already, where
|
|
1325
1859
|
* setDesiredState's same-state return would record nothing, and a restart
|
|
1326
1860
|
* replays what memory held. appendLabelSighting keeps the same order for
|
|
@@ -1660,8 +2194,20 @@ export class ChannelRegistry {
|
|
|
1660
2194
|
}
|
|
1661
2195
|
setDesiredState(serverId, channelId, desired, source) {
|
|
1662
2196
|
const key = this.lifecycleKey(serverId, channelId);
|
|
1663
|
-
|
|
2197
|
+
const current = this.desiredStates.get(key);
|
|
2198
|
+
// A decision that records the state already on record changes nothing,
|
|
2199
|
+
// so it writes nothing, unless it's the agent's own (channel_open,
|
|
2200
|
+
// channel_close or channel_decline) and the record isn't. The record
|
|
2201
|
+
// then says the agent decided, which is all handleToolClose's
|
|
2202
|
+
// explicit-open guard and ensureInitialDesiredState's lift of a default
|
|
2203
|
+
// ask of it. openChannelNow depends on it too: a failed open by speech
|
|
2204
|
+
// or a reply tells a decision made during its round-trip by the record
|
|
2205
|
+
// no longer being the object it wrote, and the agent's channel_open,
|
|
2206
|
+
// the only decision of the same state that can be made then, gets a new
|
|
2207
|
+
// record here.
|
|
2208
|
+
if (current?.state === desired && !(AGENT_DECISION_SOURCES.has(source) && !AGENT_DECISION_SOURCES.has(current.source))) {
|
|
1664
2209
|
return;
|
|
2210
|
+
}
|
|
1665
2211
|
this.appendLifecycleEvent({
|
|
1666
2212
|
kind: 'desired-state',
|
|
1667
2213
|
serverId,
|
|
@@ -1679,7 +2225,9 @@ export class ChannelRegistry {
|
|
|
1679
2225
|
* Enter (or re-enter with fresh params) the tuned-out state for a channel.
|
|
1680
2226
|
* Re-entering under a new epochId replaces the active epoch; the previous
|
|
1681
2227
|
* epoch's stamped messages stay excluded (stamps are permanent) and its
|
|
1682
|
-
* wake count is superseded.
|
|
2228
|
+
* wake count is superseded. Its transport is kept open: tune_out opens a
|
|
2229
|
+
* closed one (openForTuneOut), and reconcile opens it at the channel's
|
|
2230
|
+
* registration.
|
|
1683
2231
|
*/
|
|
1684
2232
|
enterTuneOut(serverId, channelId, params, source) {
|
|
1685
2233
|
const key = this.lifecycleKey(serverId, channelId);
|
|
@@ -1699,6 +2247,179 @@ export class ChannelRegistry {
|
|
|
1699
2247
|
wakeCount: 0,
|
|
1700
2248
|
});
|
|
1701
2249
|
}
|
|
2250
|
+
/**
|
|
2251
|
+
* Make a tuned-out channel's transport match its tune-out, which keeps it
|
|
2252
|
+
* open so its traffic reaches the subconscious (TuneOutParams). The
|
|
2253
|
+
* tune-out is recorded first (enterTuneOut), and this writes no decision,
|
|
2254
|
+
* so the tune-out stands whatever becomes of the open. Lifecycle work
|
|
2255
|
+
* queued for the channel goes first, until none is left, since each
|
|
2256
|
+
* operation reads the decision when it runs and so opens a channel tuned
|
|
2257
|
+
* out meanwhile; its own failure, such as a close the server refused,
|
|
2258
|
+
* isn't this open's. Then the state is read. Where this host directs the
|
|
2259
|
+
* lifecycle and the transport isn't confirmed open, the channel's
|
|
2260
|
+
* lifecycle queue opens it once (applyDesiredChannelState reads a
|
|
2261
|
+
* tune-out as open), and the answer waits for the work queued after it
|
|
2262
|
+
* too, such as a registration that came back, and comes from the state
|
|
2263
|
+
* that work leaves. Returns nothing where the transport is open, or, for
|
|
2264
|
+
* tune_out's answer, why the channel's messages don't or may not reach the
|
|
2265
|
+
* subconscious yet and when they will, or that the tune-out isn't in
|
|
2266
|
+
* effect any more. A call while this tune-out's open is in flight, as a
|
|
2267
|
+
* repeated tune_out makes, gets that open's answer rather than send
|
|
2268
|
+
* another.
|
|
2269
|
+
*/
|
|
2270
|
+
async openForTuneOut(serverId, channelId) {
|
|
2271
|
+
// The tune-out this answer is for, by its epoch: one that ended, or that
|
|
2272
|
+
// a later decision or a later tune-out replaced, isn't this one.
|
|
2273
|
+
const epochId = this.getTuneOutState(serverId, channelId)?.params.epochId;
|
|
2274
|
+
const key = `${this.lifecycleKey(serverId, channelId)}\u0000${epochId ?? ''}`;
|
|
2275
|
+
let opening = this.tuneOutOpens.get(key);
|
|
2276
|
+
if (!opening) {
|
|
2277
|
+
const started = this.openTuneOutTransport(serverId, channelId, epochId);
|
|
2278
|
+
this.tuneOutOpens.set(key, started);
|
|
2279
|
+
const release = () => {
|
|
2280
|
+
if (this.tuneOutOpens.get(key) === started)
|
|
2281
|
+
this.tuneOutOpens.delete(key);
|
|
2282
|
+
};
|
|
2283
|
+
void started.then(release, release);
|
|
2284
|
+
opening = started;
|
|
2285
|
+
}
|
|
2286
|
+
return opening;
|
|
2287
|
+
}
|
|
2288
|
+
/**
|
|
2289
|
+
* Whether a tune_out repeated now has nothing to wait for and finds its
|
|
2290
|
+
* channel's transport open, as the tune-out reads it: no lifecycle work
|
|
2291
|
+
* queued for the channel, since the tune-out's own call may still be
|
|
2292
|
+
* waiting for the work queued after its open; its server up; and an open
|
|
2293
|
+
* flag the tune-out takes as open (tuneOutReadsOpen). Where it doesn't,
|
|
2294
|
+
* the repeat goes through openForTuneOut, which joins this tune-out's open
|
|
2295
|
+
* in flight, or waits for the queued work and, where this host can open
|
|
2296
|
+
* the channel, tries the open again.
|
|
2297
|
+
*/
|
|
2298
|
+
tuneOutTransportOpen(serverId, channelId) {
|
|
2299
|
+
return this.getTuneOutState(serverId, channelId) !== null &&
|
|
2300
|
+
!this.channelLifecycleTails.has(this.lifecycleKey(serverId, channelId)) &&
|
|
2301
|
+
this.serverReach(serverId) === 'up' &&
|
|
2302
|
+
this.tuneOutReadsOpen(this.channels.get(`${serverId}:${channelId}`));
|
|
2303
|
+
}
|
|
2304
|
+
/**
|
|
2305
|
+
* Whether a tune-out takes an entry's transport as open: its open flag,
|
|
2306
|
+
* unless a close for it failed since it was confirmed (failedCloseTargets),
|
|
2307
|
+
* since that close may have taken effect. The other readers take any flag
|
|
2308
|
+
* a failed request left as it was (runLifecycleOperation), since a send
|
|
2309
|
+
* through it fails where it can be seen, and channel_open sends an open
|
|
2310
|
+
* after a failed close anyway, its decision having been closed. A
|
|
2311
|
+
* tune-out's success says traffic will arrive, nothing would show it
|
|
2312
|
+
* doesn't, and the decision it replaced isn't known here. An open that
|
|
2313
|
+
* failed, as a redundant one queued behind a confirming one may, can't
|
|
2314
|
+
* have closed the channel: one for the current target leaves the flag as
|
|
2315
|
+
* it was, so an open flag stays open (one for a target no longer current
|
|
2316
|
+
* withdraws it).
|
|
2317
|
+
*/
|
|
2318
|
+
tuneOutReadsOpen(entry) {
|
|
2319
|
+
// A flag is set open only where both marks are cleared, so a failed
|
|
2320
|
+
// close on an open flag is one since its confirmation.
|
|
2321
|
+
return entry !== undefined && entry.open && !this.failedCloseTargets.has(entry);
|
|
2322
|
+
}
|
|
2323
|
+
async openTuneOutTransport(serverId, channelId, epochId) {
|
|
2324
|
+
const channelKey = `${serverId}:${channelId}`;
|
|
2325
|
+
const lifecycleKey = this.lifecycleKey(serverId, channelId);
|
|
2326
|
+
const inEffect = () => epochId !== undefined && this.getTuneOutState(serverId, channelId)?.params.epochId === epochId;
|
|
2327
|
+
// "May not": a failed request leaves its outcome unknown, and an open
|
|
2328
|
+
// that took effect would have its traffic diverted. `again` where calling
|
|
2329
|
+
// tune_out again tries the open now: the channel is registered here and
|
|
2330
|
+
// its server up.
|
|
2331
|
+
const notYet = (later, why, again = false) => withStop(`The tune-out is recorded, but its messages may not reach the subconscious until this host opens the channel, ` +
|
|
2332
|
+
`which it does ${later}${again ? ', or now if you call tune_out again' : ''}; ${why}`);
|
|
2333
|
+
const nextRegistration = `when the "${serverId}" server next registers this channel, if this host may open and ` +
|
|
2334
|
+
'close its channels then';
|
|
2335
|
+
// The work queued for the channel as it stands: its tail, waited for,
|
|
2336
|
+
// and its failure returned, if it failed. Each wait below takes it until
|
|
2337
|
+
// no work is left, as a delivery's wait does (waitForOpenChannel), so
|
|
2338
|
+
// work queued while earlier work ran, such as a registration that came
|
|
2339
|
+
// back, goes first too.
|
|
2340
|
+
let awaited;
|
|
2341
|
+
const settle = async () => {
|
|
2342
|
+
const pending = this.channelLifecycleTails.get(lifecycleKey);
|
|
2343
|
+
if (!pending)
|
|
2344
|
+
return undefined;
|
|
2345
|
+
awaited = pending;
|
|
2346
|
+
try {
|
|
2347
|
+
await pending;
|
|
2348
|
+
return undefined;
|
|
2349
|
+
}
|
|
2350
|
+
catch (error) {
|
|
2351
|
+
return error;
|
|
2352
|
+
}
|
|
2353
|
+
};
|
|
2354
|
+
// What the state answers now, or null where this host is to open the
|
|
2355
|
+
// transport itself. `missing` answers for a channel that isn't
|
|
2356
|
+
// registered here, where this host directs the lifecycle.
|
|
2357
|
+
const answered = (entry, missing) => {
|
|
2358
|
+
if (!inEffect())
|
|
2359
|
+
return TUNE_OUT_REPLACED;
|
|
2360
|
+
// A connection that dropped keeps its entries' open flags, and whether
|
|
2361
|
+
// this host or the server opens the channel isn't known until it's
|
|
2362
|
+
// back, since a reconnect empties the grant until the new one is
|
|
2363
|
+
// established.
|
|
2364
|
+
const reach = this.serverReach(serverId);
|
|
2365
|
+
if (reach !== 'up') {
|
|
2366
|
+
return withStop(`The tune-out is recorded, but its messages don't reach the subconscious until the "${serverId}" server is ` +
|
|
2367
|
+
`connected and the channel is open; it can't be opened now: ${unreachableClause(serverId, reach)}` +
|
|
2368
|
+
(reach === 'gone' ? unreachableRemedy(reach) : ''));
|
|
2369
|
+
}
|
|
2370
|
+
const transportOpen = this.tuneOutReadsOpen(entry);
|
|
2371
|
+
if (!this.directsLifecycle(serverId)) {
|
|
2372
|
+
return transportOpen ? undefined
|
|
2373
|
+
: `The tune-out is recorded, but ${this.lifecycleRefusal(serverId).message}, so its messages reach the ` +
|
|
2374
|
+
'subconscious only as that server sends them, and calling tune_out again won\'t change that. If you need ' +
|
|
2375
|
+
'this host to open it, ask whoever runs this host.';
|
|
2376
|
+
}
|
|
2377
|
+
if (!entry)
|
|
2378
|
+
return missing;
|
|
2379
|
+
// A flag a close that may have taken effect left gets an open.
|
|
2380
|
+
return transportOpen ? undefined : null;
|
|
2381
|
+
};
|
|
2382
|
+
// Whether work is queued that settle hasn't waited for. It's looked at
|
|
2383
|
+
// in the turn that reads the state and queues the open, or answers, so
|
|
2384
|
+
// work queued after settle's look is waited for too. A settled tail
|
|
2385
|
+
// releases its own key before this runs, since its cleanup was
|
|
2386
|
+
// registered first (applyDesiredChannelState); one still standing isn't
|
|
2387
|
+
// waited for again, so the wait can't spin on it should that order ever
|
|
2388
|
+
// change, as waitForOpenChannel's guard keeps its own from doing.
|
|
2389
|
+
const queuedSince = () => {
|
|
2390
|
+
const tail = this.channelLifecycleTails.get(lifecycleKey);
|
|
2391
|
+
return tail !== undefined && tail !== awaited;
|
|
2392
|
+
};
|
|
2393
|
+
do
|
|
2394
|
+
await settle();
|
|
2395
|
+
while (queuedSince());
|
|
2396
|
+
const before = answered(this.channels.get(channelKey), notYet(nextRegistration, "it isn't registered here now"));
|
|
2397
|
+
if (before !== null)
|
|
2398
|
+
return before;
|
|
2399
|
+
let failure;
|
|
2400
|
+
try {
|
|
2401
|
+
await this.applyDesiredChannelState(serverId, channelId);
|
|
2402
|
+
}
|
|
2403
|
+
catch (error) {
|
|
2404
|
+
failure = error;
|
|
2405
|
+
}
|
|
2406
|
+
// A registration that came back while the open was out queued its own
|
|
2407
|
+
// reconcile, which the answer waits for too. The answer says why the
|
|
2408
|
+
// channel isn't open now, so where the last work failed, its failure,
|
|
2409
|
+
// the last attempt's, is the reason: this open's may concern a
|
|
2410
|
+
// registration that work replaced.
|
|
2411
|
+
let later;
|
|
2412
|
+
do
|
|
2413
|
+
later = await settle();
|
|
2414
|
+
while (queuedSince());
|
|
2415
|
+
failure = later ?? failure;
|
|
2416
|
+
const clause = failure !== undefined ? `: ${lifecycleClause(failure)}` : '';
|
|
2417
|
+
const after = this.channels.get(channelKey);
|
|
2418
|
+
const settled = answered(after, notYet(nextRegistration, `it isn't registered here any more${clause}`));
|
|
2419
|
+
if (settled !== null)
|
|
2420
|
+
return settled;
|
|
2421
|
+
return notYet(laterClause(after), failure !== undefined ? `opening it now didn't complete${clause}` : "it isn't open now", true);
|
|
2422
|
+
}
|
|
1702
2423
|
/**
|
|
1703
2424
|
* End the active tune-out, returning the channel to `nextState`.
|
|
1704
2425
|
* The caller (tune-out coordinator) owns the dump/notice flow; this is
|
|
@@ -1779,12 +2500,49 @@ export class ChannelRegistry {
|
|
|
1779
2500
|
}
|
|
1780
2501
|
/**
|
|
1781
2502
|
* Publish into a channel on behalf of a named non-resident agent (the
|
|
1782
|
-
* subconscious's speak_in_channel). Same delivery path
|
|
1783
|
-
* channel_publish tool
|
|
2503
|
+
* subconscious's speak_in_channel). Same delivery path, and the same result
|
|
2504
|
+
* as the channel_publish tool apart from `reason` below. Its traces carry the agent's name and follow
|
|
2505
|
+
* the publish's outcome as deliverSpeech's do: speech-routed after a
|
|
2506
|
+
* confirmed delivery, and speech-route-failed otherwise, `unknown` when the
|
|
2507
|
+
* words may have been posted and `failed` when nothing was, a refusal before
|
|
2508
|
+
* the publish included. The routed trace carries no message id, as before:
|
|
2509
|
+
* nothing here reads one, and a consumer that edits the newest traced
|
|
2510
|
+
* message in a channel would have this post to edit when an interruption of
|
|
2511
|
+
* the resident matches none. A refusal of the destination before anything
|
|
2512
|
+
* went out carries its `reason` (PublishRefusalReason), so a caller can act
|
|
2513
|
+
* on why nothing was posted without reading the words.
|
|
1784
2514
|
*/
|
|
1785
2515
|
async publishForAgent(channelId, text, agentName) {
|
|
1786
|
-
|
|
1787
|
-
|
|
2516
|
+
// The server the publish goes to, as handleToolPublish finds it before
|
|
2517
|
+
// it awaits: the channel may be removed while the reply is pending.
|
|
2518
|
+
const serverId = this.findChannelEntry(channelId)?.serverId ?? '';
|
|
2519
|
+
const seen = {};
|
|
2520
|
+
const result = await this.handleToolPublish({ channelId, content: text }, undefined, seen, 'speak_in_channel');
|
|
2521
|
+
if (seen.outcome?.status === 'delivered') {
|
|
2522
|
+
this.emitTraceFn({
|
|
2523
|
+
type: 'mcpl:speech-routed',
|
|
2524
|
+
conversationId: agentName,
|
|
2525
|
+
serverId,
|
|
2526
|
+
channelId,
|
|
2527
|
+
delivered: true,
|
|
2528
|
+
textLen: text.length,
|
|
2529
|
+
text,
|
|
2530
|
+
});
|
|
2531
|
+
}
|
|
2532
|
+
else {
|
|
2533
|
+
this.emitTraceFn({
|
|
2534
|
+
type: 'mcpl:speech-route-failed',
|
|
2535
|
+
conversationId: agentName,
|
|
2536
|
+
channelId,
|
|
2537
|
+
// The publish's own reason and the connector's detail, as
|
|
2538
|
+
// deliverSpeech's trace gives them, or the refusal before any publish.
|
|
2539
|
+
reason: seen.outcome?.reason ?? result.error ?? 'the publish failed',
|
|
2540
|
+
textLen: text.length,
|
|
2541
|
+
outcome: seen.outcome?.status === 'unknown' ? 'unknown' : 'failed',
|
|
2542
|
+
...(seen.outcome?.detail !== undefined ? { detail: connectorText(seen.outcome.detail) } : {}),
|
|
2543
|
+
});
|
|
2544
|
+
}
|
|
2545
|
+
return seen.refusal !== undefined ? { ...result, reason: seen.refusal } : result;
|
|
1788
2546
|
}
|
|
1789
2547
|
/**
|
|
1790
2548
|
* Consume the old recipe policy exactly once. It seeds Chronicle for
|
|
@@ -1869,6 +2627,7 @@ export class ChannelRegistry {
|
|
|
1869
2627
|
const removals = this.serverRemovals.get(serverId) ?? 0;
|
|
1870
2628
|
const previous = this.channelLifecycleTails.get(lifecycleKey) ?? Promise.resolve();
|
|
1871
2629
|
this.lifecycleOutstanding.set(lifecycleKey, (this.lifecycleOutstanding.get(lifecycleKey) ?? 0) + 1);
|
|
2630
|
+
this.lifecycleQueuedRemovals.set(lifecycleKey, removals);
|
|
1872
2631
|
const operation = previous.catch(() => { }).then(() => this.runLifecycleOperation(serverId, channelId, removals, options));
|
|
1873
2632
|
// Keep the rejection visible to existing joiners, while observing it
|
|
1874
2633
|
// immediately and letting each queued successor start after either result.
|
|
@@ -1890,17 +2649,14 @@ export class ChannelRegistry {
|
|
|
1890
2649
|
let attempts = 0;
|
|
1891
2650
|
for (;;) {
|
|
1892
2651
|
if ((this.serverRemovals.get(serverId) ?? 0) !== removals) {
|
|
1893
|
-
throw new
|
|
2652
|
+
throw new ChannelLifecycleError(`this host disconnected the "${serverId}" server while the change was being made`, 'cancelled');
|
|
1894
2653
|
}
|
|
1895
2654
|
const entry = this.channels.get(channelKey);
|
|
1896
2655
|
if (!entry)
|
|
1897
|
-
throw new
|
|
2656
|
+
throw new ChannelLifecycleError(`the "${serverId}" server no longer lists the channel`, 'unlisted');
|
|
1898
2657
|
const server = this.serverRegistry.getServer(serverId);
|
|
1899
|
-
if (!server)
|
|
1900
|
-
throw
|
|
1901
|
-
if (!CapabilityGrant.of(server).has('channels.lifecycle')) {
|
|
1902
|
-
throw new Error(`channels.lifecycle not in "${serverId}"'s effective grant (§14.1)`);
|
|
1903
|
-
}
|
|
2658
|
+
if (!server || !CapabilityGrant.of(server).has('channels.lifecycle'))
|
|
2659
|
+
throw this.lifecycleRefusal(serverId);
|
|
1904
2660
|
const descriptor = entry.descriptor;
|
|
1905
2661
|
const desired = this.getDesiredState(serverId, channelId);
|
|
1906
2662
|
const open = desired === 'open' || desired === 'tuned-out';
|
|
@@ -1909,10 +2665,12 @@ export class ChannelRegistry {
|
|
|
1909
2665
|
// release its queue slot and surface the failure to delivery joiners.
|
|
1910
2666
|
// Its open flag needs no change here: every retry follows a replaced
|
|
1911
2667
|
// registration, a retarget (already invalidated, whether the old
|
|
1912
|
-
// target's RPC was answered or failed),
|
|
1913
|
-
//
|
|
2668
|
+
// target's RPC was answered or failed), a receipt from before a
|
|
2669
|
+
// transport's close (invalidated by the close), or a receipt for this
|
|
2670
|
+
// very target.
|
|
1914
2671
|
if (attempts >= MAX_CHANNEL_LIFECYCLE_ATTEMPTS) {
|
|
1915
|
-
const error = new
|
|
2672
|
+
const error = new ChannelLifecycleError(`the channel's address at the "${serverId}" server, or the decision about it, kept changing, and ${attempts} tries ` +
|
|
2673
|
+
"didn't settle it", 'converge');
|
|
1916
2674
|
this.emitTraceFn({
|
|
1917
2675
|
type: 'mcpl:channel-reconcile-failed',
|
|
1918
2676
|
serverId, channelId, desired, attempts, error: error.message,
|
|
@@ -1920,7 +2678,14 @@ export class ChannelRegistry {
|
|
|
1920
2678
|
throw error;
|
|
1921
2679
|
}
|
|
1922
2680
|
attempts++;
|
|
2681
|
+
// A reconnect keeps the connection object, so the count of its
|
|
2682
|
+
// transport's closes (transportClosed) is what tells an answer from
|
|
2683
|
+
// the transport it was sent on apart from one on its successor: an
|
|
2684
|
+
// answer applied after a close it was sent before is from an older
|
|
2685
|
+
// transport, and confirms nothing.
|
|
2686
|
+
const closesAtSend = this.transportCloses.get(serverId) ?? 0;
|
|
1923
2687
|
const sameTarget = () => this.serverRegistry.getServer(serverId) === server &&
|
|
2688
|
+
(this.transportCloses.get(serverId) ?? 0) === closesAtSend &&
|
|
1924
2689
|
sameChannelTarget(entry.descriptor, descriptor);
|
|
1925
2690
|
let result;
|
|
1926
2691
|
try {
|
|
@@ -1942,8 +2707,11 @@ export class ChannelRegistry {
|
|
|
1942
2707
|
// while not open). A failure from an older connection or target
|
|
1943
2708
|
// also withdraws the open flag.
|
|
1944
2709
|
if (this.channels.get(channelKey) === entry) {
|
|
1945
|
-
if (sameTarget())
|
|
2710
|
+
if (sameTarget()) {
|
|
1946
2711
|
this.unconfirmedChannelTargets.add(entry);
|
|
2712
|
+
if (!open)
|
|
2713
|
+
this.failedCloseTargets.add(entry);
|
|
2714
|
+
}
|
|
1947
2715
|
else
|
|
1948
2716
|
this.invalidateTransportConfirmation(entry);
|
|
1949
2717
|
}
|
|
@@ -1991,12 +2759,15 @@ export class ChannelRegistry {
|
|
|
1991
2759
|
// its sends either.
|
|
1992
2760
|
if (substitute !== undefined) {
|
|
1993
2761
|
this.invalidateTransportConfirmation(entry);
|
|
1994
|
-
throw new
|
|
1995
|
-
(substitute.kind === 'other' ? 'a different channel' : 'a channel id
|
|
1996
|
-
|
|
2762
|
+
throw new ChannelLifecycleError(`the "${serverId}" server answered for ` +
|
|
2763
|
+
(substitute.kind === 'other' ? 'a different channel' : 'a channel whose id isn\'t a string') +
|
|
2764
|
+
', so nothing in its answer is used', 'substituted');
|
|
1997
2765
|
}
|
|
2766
|
+
if (open)
|
|
2767
|
+
this.applyOpenDeclaration(entry, result);
|
|
1998
2768
|
entry.open = open;
|
|
1999
2769
|
this.unconfirmedChannelTargets.delete(entry);
|
|
2770
|
+
this.failedCloseTargets.delete(entry);
|
|
2000
2771
|
const now = this.getDesiredState(serverId, channelId);
|
|
2001
2772
|
if (open !== (now === 'open' || now === 'tuned-out'))
|
|
2002
2773
|
continue;
|
|
@@ -2009,10 +2780,34 @@ export class ChannelRegistry {
|
|
|
2009
2780
|
const left = (this.lifecycleOutstanding.get(lifecycleKey) ?? 1) - 1;
|
|
2010
2781
|
if (left > 0)
|
|
2011
2782
|
this.lifecycleOutstanding.set(lifecycleKey, left);
|
|
2012
|
-
else
|
|
2783
|
+
else {
|
|
2013
2784
|
this.lifecycleOutstanding.delete(lifecycleKey);
|
|
2785
|
+
this.lifecycleQueuedRemovals.delete(lifecycleKey);
|
|
2786
|
+
}
|
|
2014
2787
|
}
|
|
2015
2788
|
}
|
|
2789
|
+
/** Whether lifecycle work already outstanding for the channel will carry out
|
|
2790
|
+
* its current decision: some is, and the newest was queued since its
|
|
2791
|
+
* server's registrations were last removed, so it won't cancel when it
|
|
2792
|
+
* would run. Each operation reads the decision when it runs. It answers for
|
|
2793
|
+
* now: a removal after it cancels that work too, and takes the channel's
|
|
2794
|
+
* entry with it, so the channel's next registration by channels/register,
|
|
2795
|
+
* or as added by channels/changed, carries the decision out, where this
|
|
2796
|
+
* host directs the lifecycle then. A push's registration
|
|
2797
|
+
* (ensureChannelRegistered) queues no lifecycle work. So where a push
|
|
2798
|
+
* re-makes an entry that a channels/changed removal took while an RPC for
|
|
2799
|
+
* the old entry was out, the operation running that RPC carries the
|
|
2800
|
+
* decision out for the push's entry only if the RPC is answered: a failed
|
|
2801
|
+
* one rethrows, since its retry covers only a retarget of its own entry.
|
|
2802
|
+
* This answers true meanwhile, so a channels/changed update that retargets
|
|
2803
|
+
* the push's entry is left to that operation, and stays undone after a
|
|
2804
|
+
* failed RPC until lifecycle work is queued for the channel again
|
|
2805
|
+
* (applyDesiredChannelState). No server we know of sends `updated` for a
|
|
2806
|
+
* channel it has removed. */
|
|
2807
|
+
outstandingWorkCarriesOut(serverId, key) {
|
|
2808
|
+
return this.lifecycleOutstanding.has(key) &&
|
|
2809
|
+
this.lifecycleQueuedRemovals.get(key) === (this.serverRemovals.get(serverId) ?? 0);
|
|
2810
|
+
}
|
|
2016
2811
|
/**
|
|
2017
2812
|
* A server that answered an open with another channel really opened that
|
|
2018
2813
|
* one. When it's registered here and the host wants it closed, close it
|
|
@@ -2027,40 +2822,57 @@ export class ChannelRegistry {
|
|
|
2027
2822
|
return;
|
|
2028
2823
|
if (this.getDesiredState(serverId, channelId) !== 'closed')
|
|
2029
2824
|
return;
|
|
2825
|
+
this.applyThroughQueue(serverId, channelId);
|
|
2826
|
+
}
|
|
2827
|
+
/**
|
|
2828
|
+
* Carry out a channel's decision through its lifecycle queue, for a
|
|
2829
|
+
* transport the server may have opened without the host's knowing: one it
|
|
2830
|
+
* opened for another channel's request (closeSubstitutedChannel), or one a
|
|
2831
|
+
* failed open's request may have reached (openChannelNow). The decision is
|
|
2832
|
+
* a closed one, except after a failed open whose put-back the server's
|
|
2833
|
+
* latest announcement or the policy lifted. A failure is reported as a
|
|
2834
|
+
* trace; the decision stands.
|
|
2835
|
+
*/
|
|
2836
|
+
applyThroughQueue(serverId, channelId) {
|
|
2030
2837
|
this.applyDesiredChannelState(serverId, channelId).catch((err) => {
|
|
2031
2838
|
// Removal while queued is cancellation, as in reconcileChannels, and
|
|
2032
2839
|
// exhausted convergence emitted its own diagnostic.
|
|
2033
2840
|
if (!this.channels.has(`${serverId}:${channelId}`) ||
|
|
2034
|
-
err instanceof
|
|
2035
|
-
err instanceof ChannelLifecycleConvergenceError)
|
|
2841
|
+
(err instanceof ChannelLifecycleError && (err.kind === 'cancelled' || err.kind === 'converge')))
|
|
2036
2842
|
return;
|
|
2037
2843
|
this.emitTraceFn({
|
|
2038
2844
|
type: 'mcpl:channel-reconcile-failed',
|
|
2039
|
-
serverId, channelId, desired:
|
|
2845
|
+
serverId, channelId, desired: this.getDesiredState(serverId, channelId), error: err.message,
|
|
2040
2846
|
});
|
|
2041
2847
|
});
|
|
2042
2848
|
}
|
|
2043
2849
|
/**
|
|
2044
2850
|
* Join outstanding lifecycle work without recording new intent. Retargeting
|
|
2045
2851
|
* may have invalidated open confirmation while the decision remains pending.
|
|
2046
|
-
* A close that settles during the wait remains authoritative
|
|
2047
|
-
*
|
|
2852
|
+
* A close that settles during the wait remains authoritative where the host
|
|
2853
|
+
* directs the server's lifecycle (closeStands); waiting for it is not an
|
|
2854
|
+
* instruction to open the channel again.
|
|
2048
2855
|
*/
|
|
2049
2856
|
async waitForOpenChannel(entry) {
|
|
2050
2857
|
const lifecycleKey = this.lifecycleKey(entry.serverId, entry.descriptor.id);
|
|
2858
|
+
// The failure of the last work waited on, if it failed, which says why a
|
|
2859
|
+
// channel it left unopened isn't open.
|
|
2860
|
+
let failed;
|
|
2051
2861
|
for (;;) {
|
|
2052
2862
|
const pending = this.channelLifecycleTails.get(lifecycleKey);
|
|
2053
2863
|
if (!pending)
|
|
2054
2864
|
break;
|
|
2055
2865
|
try {
|
|
2056
2866
|
await pending;
|
|
2867
|
+
failed = undefined;
|
|
2057
2868
|
}
|
|
2058
2869
|
catch (error) {
|
|
2059
2870
|
// A redundant backscroll failure can leave a known-open channel
|
|
2060
2871
|
// usable. Exhausted convergence is different: it never established
|
|
2061
2872
|
// the current target, so joined delivery must fail visibly.
|
|
2062
|
-
if (error instanceof
|
|
2873
|
+
if (error instanceof ChannelLifecycleError && error.kind === 'converge')
|
|
2063
2874
|
throw error;
|
|
2875
|
+
failed = error;
|
|
2064
2876
|
}
|
|
2065
2877
|
// A settled tail releases its own key. One still current after it
|
|
2066
2878
|
// settled would be awaited again without ever yielding to the event
|
|
@@ -2070,9 +2882,15 @@ export class ChannelRegistry {
|
|
|
2070
2882
|
}
|
|
2071
2883
|
const current = this.channels.get(`${entry.serverId}:${entry.descriptor.id}`);
|
|
2072
2884
|
if (!current)
|
|
2073
|
-
throw new
|
|
2074
|
-
|
|
2075
|
-
|
|
2885
|
+
throw new ChannelLifecycleError(CHANNEL_REMOVED_CLAUSE, 'removed');
|
|
2886
|
+
// A close that stands is what the words met, whatever became of an open,
|
|
2887
|
+
// and whether or not the close itself took: one that failed may have
|
|
2888
|
+
// left the transport open.
|
|
2889
|
+
if (this.closeStands(current)) {
|
|
2890
|
+
throw new ChannelLifecycleError('a decision to close the channel came before these words went out', 'not-open');
|
|
2891
|
+
}
|
|
2892
|
+
if (!current.open) {
|
|
2893
|
+
throw new ChannelLifecycleError("the channel isn't confirmed open" + (failed !== undefined ? `: ${lifecycleClause(failed)}${refusalRemedy(failed)}` : ''), 'not-open');
|
|
2076
2894
|
}
|
|
2077
2895
|
return current;
|
|
2078
2896
|
}
|
|
@@ -2132,9 +2950,8 @@ export class ChannelRegistry {
|
|
|
2132
2950
|
// Exhausted convergence and a substituted answer already emitted
|
|
2133
2951
|
// their own diagnostics.
|
|
2134
2952
|
if (!this.channels.has(`${serverId}:${channel.id}`) ||
|
|
2135
|
-
err instanceof
|
|
2136
|
-
|
|
2137
|
-
err instanceof ChannelOpenSubstitutionError)
|
|
2953
|
+
(err instanceof ChannelLifecycleError &&
|
|
2954
|
+
(err.kind === 'cancelled' || err.kind === 'converge' || err.kind === 'substituted')))
|
|
2138
2955
|
return;
|
|
2139
2956
|
this.emitTraceFn({
|
|
2140
2957
|
type: 'mcpl:channel-reconcile-failed',
|
|
@@ -2180,6 +2997,16 @@ export class ChannelRegistry {
|
|
|
2180
2997
|
getChannelServerId(channelId) {
|
|
2181
2998
|
return this.findChannelEntry(channelId)?.serverId ?? null;
|
|
2182
2999
|
}
|
|
3000
|
+
/**
|
|
3001
|
+
* The server that declared this channel inbound-only (isInboundOnly), or
|
|
3002
|
+
* undefined when it isn't one. The notices name that server. A caller that
|
|
3003
|
+
* knows the channel's server passes it; otherwise the channel is found by
|
|
3004
|
+
* its id alone (findChannelEntry).
|
|
3005
|
+
*/
|
|
3006
|
+
inboundOnlyServer(channelId, serverId) {
|
|
3007
|
+
const entry = serverId ? this.channels.get(`${serverId}:${channelId}`) : this.findChannelEntry(channelId);
|
|
3008
|
+
return entry && isInboundOnly(entry) ? entry.serverId : undefined;
|
|
3009
|
+
}
|
|
2183
3010
|
/**
|
|
2184
3011
|
* Find a channel entry by channelId (searches across all servers).
|
|
2185
3012
|
* Returns the first match.
|
|
@@ -2193,17 +3020,28 @@ export class ChannelRegistry {
|
|
|
2193
3020
|
return undefined;
|
|
2194
3021
|
}
|
|
2195
3022
|
resolveToolChannelEntry(channelId, serverId) {
|
|
2196
|
-
const
|
|
3023
|
+
const withId = [...this.channels.values()].filter((entry) => entry.descriptor.id === channelId);
|
|
3024
|
+
const matches = withId.filter((entry) => !serverId || entry.serverId === serverId);
|
|
2197
3025
|
if (matches.length === 0) {
|
|
3026
|
+
if (serverId && withId.length > 0) {
|
|
3027
|
+
// Leaving serverId out works only when one server has the id.
|
|
3028
|
+
const servers = withId.map((entry) => `"${entry.serverId}"`);
|
|
3029
|
+
return {
|
|
3030
|
+
error: `No channel "${channelId}" is on server "${serverId}", so nothing ran. ` + (servers.length === 1
|
|
3031
|
+
? `It's on server ${servers[0]}: call again with serverId ${servers[0]}, or leave serverId out.`
|
|
3032
|
+
: `It's on servers ${servers.join(', ')}: call again with serverId set to one of them.`),
|
|
3033
|
+
};
|
|
3034
|
+
}
|
|
2198
3035
|
return {
|
|
2199
3036
|
error: serverId
|
|
2200
|
-
? `
|
|
2201
|
-
: `
|
|
3037
|
+
? `No channel "${channelId}" is on server "${serverId}", so nothing ran. channel_list shows the channels and their servers.`
|
|
3038
|
+
: `No channel has the id "${channelId}", so nothing ran. channel_list shows the channel ids.`,
|
|
2202
3039
|
};
|
|
2203
3040
|
}
|
|
2204
3041
|
if (matches.length > 1) {
|
|
2205
3042
|
return {
|
|
2206
|
-
error: `Channel
|
|
3043
|
+
error: `Channel "${channelId}" is on more than one server (${matches.map((entry) => `"${entry.serverId}"`).join(', ')}), ` +
|
|
3044
|
+
'so nothing ran. Call again with serverId set to one of them.',
|
|
2207
3045
|
};
|
|
2208
3046
|
}
|
|
2209
3047
|
return { entry: matches[0] };
|
|
@@ -2243,15 +3081,31 @@ export class ChannelRegistry {
|
|
|
2243
3081
|
/**
|
|
2244
3082
|
* Record durable desired-open intent, then queue the channel's lifecycle
|
|
2245
3083
|
* work (applyDesiredChannelState), which tells the server to subscribe and
|
|
2246
|
-
* marks the live entry open on a receipt for its current target
|
|
2247
|
-
*
|
|
3084
|
+
* marks the live entry open on a receipt for its current target, applying
|
|
3085
|
+
* an inbound-only declaration the answer carries (applyOpenDeclaration).
|
|
3086
|
+
* Every open the agent or its speech asks for — the channel_open tool, delivery
|
|
2248
3087
|
* into a closed locus, an explicit send into a closed channel — comes
|
|
2249
3088
|
* here. Reconciliation queues that work directly, as the closes do
|
|
2250
3089
|
* (channel_close, a decline, and the close of a substituted channel).
|
|
2251
|
-
* Desired state is recorded BEFORE the server round-trip
|
|
2252
|
-
*
|
|
2253
|
-
*
|
|
2254
|
-
*
|
|
3090
|
+
* Desired state is recorded BEFORE the server round-trip. The agent's own
|
|
3091
|
+
* open is a decision about the channel: it sticks even if the subscribe
|
|
3092
|
+
* fails, and reconciliation retries later. An open by speech or a reply is
|
|
3093
|
+
* incidental to its words: when its round-trip fails, the decision it
|
|
3094
|
+
* wrote goes back to the one it replaced, so the agent, told the channel
|
|
3095
|
+
* is closed and the open failed, isn't later put into it by that decision.
|
|
3096
|
+
* That holds only while the record is still the one it wrote: a decision
|
|
3097
|
+
* made meanwhile stands, and the failure then comes as `overtaken`
|
|
3098
|
+
* (ChannelLifecycleError). Where the decision put back is a pure default,
|
|
3099
|
+
* nobody had decided, so the channel then follows its server's latest
|
|
3100
|
+
* announcement and the policy: a re-announcement during the round-trip
|
|
3101
|
+
* found the open's own record and lifted nothing. If they select it for
|
|
3102
|
+
* opening, the failure says so (`selected-again`). And since
|
|
3103
|
+
* a failed request may have reached the server, the decision that stands
|
|
3104
|
+
* is carried out on the wire too. An open by speech or a reply that can't
|
|
3105
|
+
* send its request, on a server without channels.lifecycle, writes
|
|
3106
|
+
* nothing. Automatic delivery needs open transport, not a change of
|
|
3107
|
+
* attention: preserve tune-out epochs both before and during the
|
|
3108
|
+
* round-trip.
|
|
2255
3109
|
*
|
|
2256
3110
|
* `opened` says whether this call turned a closed channel open, which is
|
|
2257
3111
|
* what the delivery and reply notices tell the resident. Reconfirming the
|
|
@@ -2259,17 +3113,126 @@ export class ChannelRegistry {
|
|
|
2259
3113
|
*/
|
|
2260
3114
|
async openChannelNow(entry, source, history) {
|
|
2261
3115
|
const transportOnly = source !== 'agent-tool';
|
|
3116
|
+
const key = this.lifecycleKey(entry.serverId, entry.descriptor.id);
|
|
3117
|
+
if (transportOnly) {
|
|
3118
|
+
// Without channels.lifecycle the open fails before any request leaves
|
|
3119
|
+
// (§14.1), as it does without the server, so an incidental open would
|
|
3120
|
+
// only write a decision to put back. It writes none.
|
|
3121
|
+
const server = this.serverRegistry.getServer(entry.serverId);
|
|
3122
|
+
if (!server || !CapabilityGrant.of(server).has('channels.lifecycle'))
|
|
3123
|
+
throw this.lifecycleRefusal(entry.serverId);
|
|
3124
|
+
}
|
|
3125
|
+
// The decision this open replaces. A channel with none on record, as one
|
|
3126
|
+
// registered from a push, was closed by default: nobody had decided.
|
|
3127
|
+
const replaced = this.desiredStates.get(key) ?? { state: 'closed', source: 'default-closed' };
|
|
2262
3128
|
const before = this.getDesiredState(entry.serverId, entry.descriptor.id);
|
|
2263
3129
|
const opened = before !== 'open' && before !== 'tuned-out';
|
|
2264
3130
|
if (!transportOnly || before !== 'tuned-out') {
|
|
2265
|
-
|
|
3131
|
+
// A decision the log refused changed nothing, and its words say so
|
|
3132
|
+
// rather than read as one a later decision overtook.
|
|
3133
|
+
try {
|
|
3134
|
+
this.setDesiredState(entry.serverId, entry.descriptor.id, 'open', source);
|
|
3135
|
+
}
|
|
3136
|
+
catch (err) {
|
|
3137
|
+
throw unrecordedDecision(err);
|
|
3138
|
+
}
|
|
3139
|
+
}
|
|
3140
|
+
// The record an incidental open wrote, to put back if its round-trip fails.
|
|
3141
|
+
const wrote = transportOnly && opened ? this.desiredStates.get(key) : undefined;
|
|
3142
|
+
try {
|
|
3143
|
+
const applied = await this.applyDesiredChannelState(entry.serverId, entry.descriptor.id, { history });
|
|
3144
|
+
const desired = this.getDesiredState(entry.serverId, entry.descriptor.id);
|
|
3145
|
+
if (!applied.open || (desired !== 'open' && !(transportOnly && desired === 'tuned-out'))) {
|
|
3146
|
+
throw new ChannelLifecycleError(supersededClause('open', desired), 'superseded');
|
|
3147
|
+
}
|
|
3148
|
+
return { result: applied.result, opened };
|
|
3149
|
+
}
|
|
3150
|
+
catch (err) {
|
|
3151
|
+
if (wrote && this.desiredStates.get(key) !== wrote) {
|
|
3152
|
+
// That decision stands, and the failure says so where its own clause
|
|
3153
|
+
// doesn't, as a superseded open's does. What helps turns on that
|
|
3154
|
+
// decision, so no step is offered.
|
|
3155
|
+
const own = lifecycleClause(err);
|
|
3156
|
+
throw new ChannelLifecycleError(err instanceof ChannelLifecycleError && err.kind === 'superseded'
|
|
3157
|
+
? own : afterClause(own, 'a decision about the channel made while the open was out stands'), 'overtaken', undefined, { cause: err });
|
|
3158
|
+
}
|
|
3159
|
+
if (wrote) {
|
|
3160
|
+
try {
|
|
3161
|
+
this.setDesiredState(entry.serverId, entry.descriptor.id, replaced.state, replaced.source);
|
|
3162
|
+
}
|
|
3163
|
+
catch (putBackErr) {
|
|
3164
|
+
// The caller reports both: the channel isn't open, but it stays
|
|
3165
|
+
// selected for opening, so reconciliation may open it later.
|
|
3166
|
+
throw new ChannelLifecycleError(afterClause(lifecycleClause(err), 'the channel stays selected for opening, because this host couldn\'t record ' +
|
|
3167
|
+
`undoing that: ${requestErrorText(putBackErr)}`), 'put-back-unrecorded', undefined, { cause: err });
|
|
3168
|
+
}
|
|
3169
|
+
// The decision put back is a closed one: an open that turned the
|
|
3170
|
+
// channel open replaced no open decision. Where it's a pure default,
|
|
3171
|
+
// nobody had decided, so the channel follows its server's latest
|
|
3172
|
+
// announcement and the policy, not the ones from before the open: a
|
|
3173
|
+
// re-announcement during the round-trip found the open's own record
|
|
3174
|
+
// and lifted nothing. The lift is ensureInitialDesiredState's own,
|
|
3175
|
+
// which leaves every real decision alone. One that can't be recorded
|
|
3176
|
+
// leaves the default, closed.
|
|
3177
|
+
const current = this.channels.get(`${entry.serverId}:${entry.descriptor.id}`);
|
|
3178
|
+
let selectedAgain;
|
|
3179
|
+
if (current) {
|
|
3180
|
+
try {
|
|
3181
|
+
this.ensureInitialDesiredState(entry.serverId, current.descriptor);
|
|
3182
|
+
}
|
|
3183
|
+
catch (liftErr) {
|
|
3184
|
+
console.error(`[channel] ${entry.serverId}:${logValue(entry.descriptor.id)}: the lift after a failed open couldn't be recorded:`, liftErr);
|
|
3185
|
+
}
|
|
3186
|
+
const now = this.desiredStates.get(key);
|
|
3187
|
+
if (now?.state === 'open' && (now.source === 'server-bootstrap' || now.source === 'subscription-policy')) {
|
|
3188
|
+
selectedAgain = now.source;
|
|
3189
|
+
}
|
|
3190
|
+
}
|
|
3191
|
+
// The failed request may have reached the server, so the decision
|
|
3192
|
+
// that stands is carried out through the queue, as a decline's close
|
|
3193
|
+
// is, unless other lifecycle work for the channel is queued that will
|
|
3194
|
+
// carry it out anyway: work queued before its server's registrations
|
|
3195
|
+
// were removed cancels instead. (An incidental open gets here only
|
|
3196
|
+
// where the host directed the lifecycle when it opened: see the grant
|
|
3197
|
+
// check above. Where the grant has lost channels.lifecycle since, as a
|
|
3198
|
+
// transport drop clears it, the queued work fails for it, and the
|
|
3199
|
+
// channel's next registration by channels/register, or as added by
|
|
3200
|
+
// channels/changed, carries the decision out, where this host directs
|
|
3201
|
+
// the lifecycle then.)
|
|
3202
|
+
if (current && !this.outstandingWorkCarriesOut(entry.serverId, key)) {
|
|
3203
|
+
this.applyThroughQueue(entry.serverId, entry.descriptor.id);
|
|
3204
|
+
}
|
|
3205
|
+
if (selectedAgain) {
|
|
3206
|
+
throw new ChannelLifecycleError(afterClause(lifecycleClause(err), 'the channel is selected for opening again, because ' +
|
|
3207
|
+
(selectedAgain === 'server-bootstrap' ? 'its server lists it as open by default' : 'the subscription policy admits it')), 'selected-again', undefined, { by: selectedAgain, cause: err });
|
|
3208
|
+
}
|
|
3209
|
+
}
|
|
3210
|
+
throw err;
|
|
2266
3211
|
}
|
|
2267
|
-
|
|
2268
|
-
|
|
2269
|
-
|
|
2270
|
-
|
|
3212
|
+
}
|
|
3213
|
+
/**
|
|
3214
|
+
* An open's answer carries the server's descriptor for the channel
|
|
3215
|
+
* (§14.3), the first place a lazily registered channel's own declaration
|
|
3216
|
+
* can arrive. runLifecycleOperation hands it here, wherever the host opens
|
|
3217
|
+
* a channel, once the answer is known to be for the channel's current
|
|
3218
|
+
* entry and target. An answer that names another channel never arrives
|
|
3219
|
+
* here: it's a substitution, which fails the open. One whose channel names
|
|
3220
|
+
* no id is this channel's, as runLifecycleOperation takes it, so its
|
|
3221
|
+
* declaration applies too.
|
|
3222
|
+
*
|
|
3223
|
+
* Only an inbound-only declaration is applied. The answer isn't always the
|
|
3224
|
+
* server's latest word: a `channels/changed` that arrives in the same read
|
|
3225
|
+
* as the answer is handled before the open's operation resumes, so the
|
|
3226
|
+
* answer is applied over it. Applying only a refusal keeps that race
|
|
3227
|
+
* fail-closed: a stale answer can keep a channel refused until the
|
|
3228
|
+
* server's next update, but never lift a newer refusal. A server lifts its
|
|
3229
|
+
* declaration by changing or registering the channel again.
|
|
3230
|
+
*/
|
|
3231
|
+
applyOpenDeclaration(entry, answer) {
|
|
3232
|
+
const declared = answer?.channel;
|
|
3233
|
+
if (declared?.direction === 'inbound') {
|
|
3234
|
+
entry.descriptor = { ...entry.descriptor, direction: 'inbound' };
|
|
2271
3235
|
}
|
|
2272
|
-
return { result: applied.result, opened };
|
|
2273
3236
|
}
|
|
2274
3237
|
/**
|
|
2275
3238
|
* Resolve a `>>` prose-routing target (explicit prose routing —
|
|
@@ -2284,8 +3247,24 @@ export class ChannelRegistry {
|
|
|
2284
3247
|
*
|
|
2285
3248
|
* Ambiguity is an error carrying candidates — never a guess: this is the
|
|
2286
3249
|
* mechanism that makes prose misdelivery structurally impossible.
|
|
3250
|
+
*
|
|
3251
|
+
* `forSpeech` is for a target the agent's speech will be posted to: a
|
|
3252
|
+
* channel its server declared inbound-only (isInboundOnly) then resolves
|
|
3253
|
+
* to an error that says so, since nothing is published there, and that
|
|
3254
|
+
* names the channel as `refusedChannelId`, so a caller can tell a refused
|
|
3255
|
+
* channel from a name that resolved to nothing. Without it, as for reading
|
|
3256
|
+
* a channel's history, any registered channel resolves.
|
|
2287
3257
|
*/
|
|
2288
|
-
resolveProseTarget(spec) {
|
|
3258
|
+
resolveProseTarget(spec, opts) {
|
|
3259
|
+
const resolved = this.resolveTargetByName(spec);
|
|
3260
|
+
if (!opts?.forSpeech || 'error' in resolved)
|
|
3261
|
+
return resolved;
|
|
3262
|
+
const entry = this.findChannelEntry(resolved.channelId);
|
|
3263
|
+
return entry && isInboundOnly(entry)
|
|
3264
|
+
? { error: `${resolved.channelId} is ${inboundOnlyReason(entry)}`, refusedChannelId: resolved.channelId }
|
|
3265
|
+
: resolved;
|
|
3266
|
+
}
|
|
3267
|
+
resolveTargetByName(spec) {
|
|
2289
3268
|
const entries = [...this.channels.values()];
|
|
2290
3269
|
const trimmed = spec.trim();
|
|
2291
3270
|
if (!trimmed)
|
|
@@ -2431,7 +3410,7 @@ export class ChannelRegistry {
|
|
|
2431
3410
|
for (const c of candidates) {
|
|
2432
3411
|
if (/\s/.test(c) || c === '#')
|
|
2433
3412
|
continue;
|
|
2434
|
-
const r = this.resolveProseTarget(c);
|
|
3413
|
+
const r = this.resolveProseTarget(c, { forSpeech: true });
|
|
2435
3414
|
if ('channelId' in r && r.channelId === d.id)
|
|
2436
3415
|
return c;
|
|
2437
3416
|
}
|
|
@@ -2443,7 +3422,17 @@ export class ChannelRegistry {
|
|
|
2443
3422
|
* engaging a channel opens it, so typing indicators, reaction machinery,
|
|
2444
3423
|
* and inbound forwarding all come alive with the first outbound message.
|
|
2445
3424
|
* Accepts composite MCPL ids or raw server-internal ids (explicit send
|
|
2446
|
-
* tools receive whatever the agent typed).
|
|
3425
|
+
* tools receive whatever the agent typed). An `open-failed` answer says
|
|
3426
|
+
* whether the open that failed was one that would have opened a channel
|
|
3427
|
+
* not selected open (`opening`), as opposed to one reconfirming the
|
|
3428
|
+
* transport of a channel already selected open or tuned out. It isn't one
|
|
3429
|
+
* either where a decision made during its round-trip replaced it
|
|
3430
|
+
* (`overtaken`), or where queued lifecycle work left the
|
|
3431
|
+
* channel closed before any open was sent. `selectedForOpening` says the
|
|
3432
|
+
* channel is selected for opening after the failure, and why: the put-back
|
|
3433
|
+
* couldn't be recorded (`put-back-unrecorded`), or the server's latest
|
|
3434
|
+
* announcement or the policy lifted the default it restored
|
|
3435
|
+
* (`selected-again`).
|
|
2447
3436
|
*/
|
|
2448
3437
|
async openIfClosedForSend(rawChannelId, serverId) {
|
|
2449
3438
|
let matches = [...this.channels.values()].filter((e) => e.descriptor.id === rawChannelId && (!serverId || e.serverId === serverId));
|
|
@@ -2456,6 +3445,7 @@ export class ChannelRegistry {
|
|
|
2456
3445
|
if (matches.length > 1)
|
|
2457
3446
|
return { status: 'ambiguous' };
|
|
2458
3447
|
let entry = matches[0];
|
|
3448
|
+
let opening = false;
|
|
2459
3449
|
try {
|
|
2460
3450
|
if (this.hasPendingLifecycle(entry)) {
|
|
2461
3451
|
entry = await this.waitForOpenChannel(entry);
|
|
@@ -2464,6 +3454,7 @@ export class ChannelRegistry {
|
|
|
2464
3454
|
if (entry.open && (desired === 'open' || desired === 'tuned-out')) {
|
|
2465
3455
|
return { status: 'already-open', channelId: entry.descriptor.id, label: entry.descriptor.label };
|
|
2466
3456
|
}
|
|
3457
|
+
opening = desired !== 'open' && desired !== 'tuned-out';
|
|
2467
3458
|
const { opened } = await this.openChannelNow(entry, 'opened-by-reply');
|
|
2468
3459
|
entry = await this.waitForOpenChannel(entry);
|
|
2469
3460
|
if (opened) {
|
|
@@ -2476,6 +3467,11 @@ export class ChannelRegistry {
|
|
|
2476
3467
|
return { status: opened ? 'opened' : 'already-open', channelId: entry.descriptor.id, label: entry.descriptor.label };
|
|
2477
3468
|
}
|
|
2478
3469
|
catch (err) {
|
|
3470
|
+
// Where a decision made during the open's round-trip replaced it, such
|
|
3471
|
+
// as the agent's own close or channel_open, the channel is as that
|
|
3472
|
+
// decision left it, and the agent isn't told the open failed.
|
|
3473
|
+
if (err instanceof ChannelLifecycleError && err.kind === 'overtaken')
|
|
3474
|
+
opening = false;
|
|
2479
3475
|
this.emitTraceFn({
|
|
2480
3476
|
type: 'mcpl:channel-open-failed',
|
|
2481
3477
|
serverId: entry.serverId,
|
|
@@ -2483,7 +3479,11 @@ export class ChannelRegistry {
|
|
|
2483
3479
|
error: err.message,
|
|
2484
3480
|
});
|
|
2485
3481
|
const current = this.channels.get(`${entry.serverId}:${entry.descriptor.id}`);
|
|
2486
|
-
return { status: 'open-failed', channelId: entry.descriptor.id,
|
|
3482
|
+
return { status: 'open-failed', channelId: entry.descriptor.id, opening,
|
|
3483
|
+
// Where the channel is selected for opening after the failure, the
|
|
3484
|
+
// agent is told so and why, as speech's failure says.
|
|
3485
|
+
...(err instanceof ChannelLifecycleError && err.kind === 'put-back-unrecorded' ? { selectedForOpening: 'unrecorded' } : {}),
|
|
3486
|
+
...(err instanceof ChannelLifecycleError && err.kind === 'selected-again' ? { selectedForOpening: err.by } : {}),
|
|
2487
3487
|
...(current ? { label: current.descriptor.label } : {}) };
|
|
2488
3488
|
}
|
|
2489
3489
|
}
|
|
@@ -2500,21 +3500,26 @@ export class ChannelRegistry {
|
|
|
2500
3500
|
// A tuned-out channel is transport-open but attention-diverted; a plain
|
|
2501
3501
|
// open would silently discard the epoch (and its pending backlog dump).
|
|
2502
3502
|
// Cancelling is the tune-out coordinator's flow, reached via its own
|
|
2503
|
-
// tool — refuse with the pointer rather than eat the state.
|
|
2504
|
-
// result, the agent reads the pointer itself; `data` names the refusal
|
|
2505
|
-
// for an in-process caller.
|
|
3503
|
+
// tool — refuse with the pointer rather than eat the state.
|
|
2506
3504
|
if (this.getDesiredState(entry.serverId, input.channelId) === 'tuned-out') {
|
|
2507
|
-
return
|
|
2508
|
-
success: false,
|
|
2509
|
-
isError: true,
|
|
2510
|
-
error: `Channel ${input.channelId} is tuned out. Cancel the tune-out ` +
|
|
2511
|
-
`(tune_out with mode: 'cancel') to resume normal attention — ` +
|
|
2512
|
-
`cancelling delivers the diverted backlog.`,
|
|
2513
|
-
data: { refusal: 'tuned-out', channelId: input.channelId },
|
|
2514
|
-
};
|
|
3505
|
+
return tunedOutRefusal('channel_open', input.channelId);
|
|
2515
3506
|
}
|
|
2516
3507
|
const alreadyDesiredOpen = this.getDesiredState(entry.serverId, input.channelId) === 'open';
|
|
2517
3508
|
if (entry.open && alreadyDesiredOpen && !input.backscroll && !this.hasPendingLifecycle(entry)) {
|
|
3509
|
+
// Open already, perhaps because speech, a reply, the server or a
|
|
3510
|
+
// policy opened it: the agent's open is still its decision, and is
|
|
3511
|
+
// recorded as one (setDesiredState), so the explicit-open guard of
|
|
3512
|
+
// handleToolClose reads it.
|
|
3513
|
+
try {
|
|
3514
|
+
this.setDesiredState(entry.serverId, input.channelId, 'open', 'agent-tool');
|
|
3515
|
+
}
|
|
3516
|
+
catch (err) {
|
|
3517
|
+
return {
|
|
3518
|
+
success: false,
|
|
3519
|
+
error: `Channel ${input.channelId} is already open, but recording your decision to open it failed: ${err.message}`,
|
|
3520
|
+
isError: true,
|
|
3521
|
+
};
|
|
3522
|
+
}
|
|
2518
3523
|
return {
|
|
2519
3524
|
success: true,
|
|
2520
3525
|
data: { channelId: input.channelId, status: 'already open' },
|
|
@@ -2540,17 +3545,12 @@ export class ChannelRegistry {
|
|
|
2540
3545
|
}
|
|
2541
3546
|
catch (err) {
|
|
2542
3547
|
// The decision was recorded before the round-trip and outlives its
|
|
2543
|
-
// failure.
|
|
2544
|
-
// would be the resident's first sign
|
|
2545
|
-
|
|
2546
|
-
const stillSelected = current !== undefined && !current.open &&
|
|
2547
|
-
this.getDesiredState(entry.serverId, input.channelId) === 'open';
|
|
3548
|
+
// failure. The text says so where it stands: otherwise a later
|
|
3549
|
+
// delivery that opens the channel would be the resident's first sign
|
|
3550
|
+
// that it was still wanted open.
|
|
2548
3551
|
return {
|
|
2549
3552
|
success: false,
|
|
2550
|
-
error:
|
|
2551
|
-
(stillSelected
|
|
2552
|
-
? ' (it stays selected for opening: a later delivery or reconnect tries again, and channel_close withdraws that)'
|
|
2553
|
-
: ''),
|
|
3553
|
+
error: this.lifecycleFailureText('open', entry, err, { history: !!input.backscroll }),
|
|
2554
3554
|
isError: true,
|
|
2555
3555
|
};
|
|
2556
3556
|
}
|
|
@@ -2565,14 +3565,6 @@ export class ChannelRegistry {
|
|
|
2565
3565
|
isError: true,
|
|
2566
3566
|
};
|
|
2567
3567
|
}
|
|
2568
|
-
const alreadyDesiredClosed = this.getDesiredState(entry.serverId, input.channelId) === 'closed';
|
|
2569
|
-
if (!entry.open && alreadyDesiredClosed && !this.hasPendingLifecycle(entry) &&
|
|
2570
|
-
!this.unconfirmedChannelTargets.has(entry)) {
|
|
2571
|
-
return {
|
|
2572
|
-
success: true,
|
|
2573
|
-
data: { channelId: input.channelId, status: 'already closed' },
|
|
2574
|
-
};
|
|
2575
|
-
}
|
|
2576
3568
|
// Provenance comes from trusted dispatch, not from self-description:
|
|
2577
3569
|
// only module-origin calls may record a machine source, and only from
|
|
2578
3570
|
// the closed vocabulary. Agent-origin (or origin-less — the safe
|
|
@@ -2591,6 +3583,27 @@ export class ChannelRegistry {
|
|
|
2591
3583
|
}
|
|
2592
3584
|
closeSource = input.source;
|
|
2593
3585
|
}
|
|
3586
|
+
const alreadyDesiredClosed = this.getDesiredState(entry.serverId, input.channelId) === 'closed';
|
|
3587
|
+
if (!entry.open && alreadyDesiredClosed && !this.hasPendingLifecycle(entry) &&
|
|
3588
|
+
!this.unconfirmedChannelTargets.has(entry)) {
|
|
3589
|
+
// Closed already, perhaps only by default: the agent's close is still
|
|
3590
|
+
// its decision, and is recorded as one (setDesiredState), so a later
|
|
3591
|
+
// registration's lift of a default leaves the channel closed.
|
|
3592
|
+
try {
|
|
3593
|
+
this.setDesiredState(entry.serverId, input.channelId, 'closed', closeSource);
|
|
3594
|
+
}
|
|
3595
|
+
catch (err) {
|
|
3596
|
+
return {
|
|
3597
|
+
success: false,
|
|
3598
|
+
error: `Channel ${input.channelId} is already closed, but recording the decision to close it failed: ${err.message}`,
|
|
3599
|
+
isError: true,
|
|
3600
|
+
};
|
|
3601
|
+
}
|
|
3602
|
+
return {
|
|
3603
|
+
success: true,
|
|
3604
|
+
data: { channelId: input.channelId, status: 'already closed' },
|
|
3605
|
+
};
|
|
3606
|
+
}
|
|
2594
3607
|
// Housekeeping must not override stated intent (issue #5: GC closes wore
|
|
2595
3608
|
// the agent's badge and reset explicitly-opened doors). A machine-sourced
|
|
2596
3609
|
// close of a channel whose current desired state is an agent/operator
|
|
@@ -2611,39 +3624,31 @@ export class ChannelRegistry {
|
|
|
2611
3624
|
};
|
|
2612
3625
|
}
|
|
2613
3626
|
}
|
|
2614
|
-
|
|
3627
|
+
// A decision the log refused changed nothing, and the answer says so.
|
|
3628
|
+
try {
|
|
3629
|
+
this.setDesiredState(entry.serverId, input.channelId, 'closed', closeSource);
|
|
3630
|
+
}
|
|
3631
|
+
catch (err) {
|
|
3632
|
+
return { success: false, error: this.lifecycleFailureText('close', entry, unrecordedDecision(err)), isError: true };
|
|
3633
|
+
}
|
|
2615
3634
|
this.stopTyping(input.channelId);
|
|
2616
|
-
|
|
2617
|
-
|
|
2618
|
-
|
|
2619
|
-
|
|
2620
|
-
error: `Server not found: ${entry.serverId}`,
|
|
2621
|
-
isError: true,
|
|
2622
|
-
};
|
|
3635
|
+
// Refused now, the close stays recorded for the server's next
|
|
3636
|
+
// registration, and the text says so.
|
|
3637
|
+
if (!this.directsLifecycle(entry.serverId)) {
|
|
3638
|
+
return { success: false, error: this.lifecycleFailureText('close', entry, this.lifecycleRefusal(entry.serverId)), isError: true };
|
|
2623
3639
|
}
|
|
2624
3640
|
try {
|
|
2625
|
-
if (!CapabilityGrant.of(server).has('channels.lifecycle')) {
|
|
2626
|
-
return {
|
|
2627
|
-
success: false,
|
|
2628
|
-
error: `channels.lifecycle not in "${entry.serverId}"'s effective grant (§14.1)`,
|
|
2629
|
-
isError: true,
|
|
2630
|
-
};
|
|
2631
|
-
}
|
|
2632
3641
|
const applied = await this.applyDesiredChannelState(entry.serverId, input.channelId);
|
|
2633
|
-
|
|
2634
|
-
|
|
2635
|
-
|
|
3642
|
+
const now = this.getDesiredState(entry.serverId, input.channelId);
|
|
3643
|
+
if (applied.open || now !== 'closed')
|
|
3644
|
+
throw new ChannelLifecycleError(supersededClause('close', now), 'superseded');
|
|
2636
3645
|
return {
|
|
2637
3646
|
success: true,
|
|
2638
3647
|
data: { channelId: input.channelId, status: 'closed' },
|
|
2639
3648
|
};
|
|
2640
3649
|
}
|
|
2641
3650
|
catch (err) {
|
|
2642
|
-
return {
|
|
2643
|
-
success: false,
|
|
2644
|
-
error: `Failed to close channel: ${err.message}`,
|
|
2645
|
-
isError: true,
|
|
2646
|
-
};
|
|
3651
|
+
return { success: false, error: this.lifecycleFailureText('close', entry, err), isError: true };
|
|
2647
3652
|
}
|
|
2648
3653
|
}
|
|
2649
3654
|
async handleToolDecline(input) {
|
|
@@ -2652,28 +3657,54 @@ export class ChannelRegistry {
|
|
|
2652
3657
|
if (!entry) {
|
|
2653
3658
|
return { success: false, error: resolved.error, isError: true };
|
|
2654
3659
|
}
|
|
3660
|
+
// A tuned-out channel's decision is the tune-out, whatever its transport,
|
|
3661
|
+
// and a decline recorded over it would end it without its cancel, so the
|
|
3662
|
+
// backlog it diverted would never reach the agent. Its cancel is what ends
|
|
3663
|
+
// it, as channel_open's refusal of a tuned-out channel says.
|
|
3664
|
+
if (this.getDesiredState(entry.serverId, input.channelId) === 'tuned-out') {
|
|
3665
|
+
return tunedOutRefusal('channel_decline', input.channelId);
|
|
3666
|
+
}
|
|
2655
3667
|
if (entry.open || this.getDesiredState(entry.serverId, input.channelId) === 'open') {
|
|
3668
|
+
// channel_close is the call that closes it: its own answer says when,
|
|
3669
|
+
// as for a server that isn't up. A server that's up without that grant
|
|
3670
|
+
// keeps its channels as it chooses, so the text says so, and whom to
|
|
3671
|
+
// ask.
|
|
3672
|
+
const refusal = this.serverReach(entry.serverId) === 'up' && !this.directsLifecycle(entry.serverId)
|
|
3673
|
+
? this.lifecycleRefusal(entry.serverId) : undefined;
|
|
2656
3674
|
return {
|
|
2657
3675
|
success: false,
|
|
2658
|
-
error: `Channel
|
|
3676
|
+
error: `Channel "${input.channelId}" is open, or set to open, so there's nothing to decline` +
|
|
3677
|
+
(refusal ? `, and ${refusal.message}; if you need it closed, ask whoever runs this host.`
|
|
3678
|
+
: '. If you need it closed, call channel_close.'),
|
|
2659
3679
|
isError: true,
|
|
2660
3680
|
};
|
|
2661
3681
|
}
|
|
2662
3682
|
// The lifecycle decision is authoritative even if the optional public
|
|
2663
|
-
// acknowledgment cannot be rendered by the surface.
|
|
2664
|
-
|
|
3683
|
+
// acknowledgment cannot be rendered by the surface. One the log refused
|
|
3684
|
+
// changed nothing, and nothing after it runs.
|
|
3685
|
+
try {
|
|
3686
|
+
this.setDesiredState(entry.serverId, input.channelId, 'closed', 'invitation-declined');
|
|
3687
|
+
}
|
|
3688
|
+
catch (err) {
|
|
3689
|
+
return {
|
|
3690
|
+
success: false,
|
|
3691
|
+
error: `Nothing changed for channel "${input.channelId}": ${unrecordedDecision(err).message}, so no acknowledgment ` +
|
|
3692
|
+
'was posted and nothing was sent to the server. Calling channel_decline again tries again; if it fails the same ' +
|
|
3693
|
+
'way, ask whoever runs this host.',
|
|
3694
|
+
isError: true,
|
|
3695
|
+
};
|
|
3696
|
+
}
|
|
2665
3697
|
let acknowledged = false;
|
|
2666
3698
|
let representation;
|
|
2667
|
-
|
|
3699
|
+
// What became of an acknowledgment that wasn't posted, worded once the
|
|
3700
|
+
// decline's own outcome is known: each says the decline is recorded,
|
|
3701
|
+
// since it is whatever becomes of the acknowledgment, and a repeated
|
|
3702
|
+
// decline records it again and posts, but only where another decline
|
|
3703
|
+
// would be taken (`retry`).
|
|
3704
|
+
let ackFailure;
|
|
2668
3705
|
if (input.acknowledge) {
|
|
2669
3706
|
const server = this.serverRegistry.getServer(entry.serverId);
|
|
2670
|
-
if (
|
|
2671
|
-
acknowledgmentError = `Server not found: ${entry.serverId}`;
|
|
2672
|
-
}
|
|
2673
|
-
else if (!CapabilityGrant.of(server).has('channels.acknowledge')) {
|
|
2674
|
-
acknowledgmentError = `channels.acknowledge not in "${entry.serverId}"'s effective grant (§14.1)`;
|
|
2675
|
-
}
|
|
2676
|
-
else {
|
|
3707
|
+
if (server && CapabilityGrant.of(server).has('channels.acknowledge')) {
|
|
2677
3708
|
try {
|
|
2678
3709
|
const result = await server.sendChannelsAcknowledge({
|
|
2679
3710
|
channelId: input.channelId,
|
|
@@ -2681,53 +3712,200 @@ export class ChannelRegistry {
|
|
|
2681
3712
|
intent: 'seen-not-opening',
|
|
2682
3713
|
value: input.acknowledge,
|
|
2683
3714
|
});
|
|
2684
|
-
|
|
2685
|
-
|
|
2686
|
-
|
|
2687
|
-
|
|
2688
|
-
|
|
3715
|
+
// An answer counts by #163's rule, as a publish's does: only
|
|
3716
|
+
// acknowledged: true confirms a post, and only false denies one.
|
|
3717
|
+
const receipt = (result ?? {});
|
|
3718
|
+
if (receipt.acknowledged === true) {
|
|
3719
|
+
acknowledged = true;
|
|
3720
|
+
if (typeof receipt.representation === 'string')
|
|
3721
|
+
representation = receipt.representation;
|
|
3722
|
+
}
|
|
3723
|
+
else if (receipt.acknowledged === false) {
|
|
3724
|
+
// A reason that isn't a non-empty string is none.
|
|
3725
|
+
const reason = typeof receipt.reason === 'string' && receipt.reason !== '' ? connectorText(receipt.reason) : undefined;
|
|
3726
|
+
ackFailure = (retry) => reason !== undefined
|
|
3727
|
+
? withStop(`The decline is recorded, but the "${entry.serverId}" server didn't post the acknowledgment: ${reason}`)
|
|
3728
|
+
: `The decline is recorded, but the "${entry.serverId}" server didn't post the acknowledgment, and gave no reason.` +
|
|
3729
|
+
(retry ? ` To try once more, ${retry}.` : '');
|
|
3730
|
+
}
|
|
3731
|
+
else {
|
|
3732
|
+
ackFailure = (retry) => `The decline is recorded, but the "${entry.serverId}" server's answer didn't say whether it ` +
|
|
3733
|
+
'posted the acknowledgment.' + (retry ? ' Calling channel_decline again with acknowledge could post it twice.' : '');
|
|
2689
3734
|
}
|
|
2690
3735
|
}
|
|
2691
3736
|
catch (error) {
|
|
2692
|
-
|
|
3737
|
+
// Only a request that never left the host proves nothing was
|
|
3738
|
+
// posted, as for a publish (publishErrorOutcome).
|
|
3739
|
+
const words = requestErrorText(error);
|
|
3740
|
+
ackFailure = error instanceof McplRequestError && error.outcome === 'not-sent'
|
|
3741
|
+
? (retry) => withStop(`The decline is recorded, but the acknowledgment wasn't posted: ${words}`) +
|
|
3742
|
+
(retry ? ` To try again, ${retry}.` : '')
|
|
3743
|
+
: (retry) => withStop(`The decline is recorded, but whether the acknowledgment was posted isn't known: ${words}`) +
|
|
3744
|
+
(retry ? ' Calling channel_decline again with acknowledge could post it twice.' : '');
|
|
2693
3745
|
}
|
|
2694
3746
|
}
|
|
3747
|
+
else {
|
|
3748
|
+
const reach = this.serverReach(entry.serverId);
|
|
3749
|
+
// Read when the acknowledgment was attempted. Where the server is up,
|
|
3750
|
+
// the decline's close can await past a change to its grant, so that
|
|
3751
|
+
// text says what kept the acknowledgment back then.
|
|
3752
|
+
ackFailure = (retry) => reach === 'up'
|
|
3753
|
+
? `The decline is recorded, but this host wasn't permitted to post acknowledgments to the "${entry.serverId}" server, ` +
|
|
3754
|
+
'so none was posted. If you need it, ask whoever runs this host.'
|
|
3755
|
+
: `The decline is recorded, but the acknowledgment wasn't posted: ${unreachableClause(entry.serverId, reach)}.` +
|
|
3756
|
+
(reach === 'gone' ? ' If you need it, ask whoever runs this host.'
|
|
3757
|
+
: retry ? ` To post it, ${retry} ${reach === 'connecting' ? 'in a moment' : "once it's back"}.` : '');
|
|
3758
|
+
}
|
|
2695
3759
|
}
|
|
2696
3760
|
// Where the host directs the lifecycle, a decline goes through the
|
|
2697
3761
|
// lifecycle queue like any closed decision, unless a receipt confirmed
|
|
2698
|
-
// the transport closed with nothing pending: an
|
|
2699
|
-
// be open, and pending work must settle on this decision.
|
|
2700
|
-
//
|
|
2701
|
-
|
|
3762
|
+
// the transport closed with nothing pending: an open or unconfirmed
|
|
3763
|
+
// transport may be open, and pending work must settle on this decision.
|
|
3764
|
+
// The decline refused an open channel before its acknowledgment, but
|
|
3765
|
+
// traffic can show one open meanwhile where this host didn't direct the
|
|
3766
|
+
// server's channels, before a grant that now lets it. A decline acts
|
|
3767
|
+
// only on its own decision: one made meanwhile, to open the channel or
|
|
3768
|
+
// tune it out, isn't the decline's to apply. A failed close is reported
|
|
3769
|
+
// below; the decision stands.
|
|
3770
|
+
let closeFailure;
|
|
3771
|
+
let closeFailed = false;
|
|
2702
3772
|
const current = this.channels.get(`${entry.serverId}:${input.channelId}`);
|
|
2703
3773
|
if (current && this.directsLifecycle(entry.serverId) &&
|
|
2704
|
-
|
|
3774
|
+
this.getDesiredState(entry.serverId, input.channelId) === 'closed' &&
|
|
3775
|
+
(current.open || this.unconfirmedChannelTargets.has(current) || this.hasPendingLifecycle(current))) {
|
|
2705
3776
|
try {
|
|
2706
|
-
|
|
2707
|
-
if (applied.open)
|
|
2708
|
-
closeError = 'the close was superseded by a newer lifecycle decision';
|
|
3777
|
+
await this.applyDesiredChannelState(entry.serverId, input.channelId);
|
|
2709
3778
|
}
|
|
2710
3779
|
catch (error) {
|
|
2711
|
-
|
|
3780
|
+
closeFailure = error;
|
|
3781
|
+
closeFailed = true;
|
|
2712
3782
|
}
|
|
2713
3783
|
}
|
|
2714
|
-
|
|
2715
|
-
|
|
2716
|
-
|
|
2717
|
-
|
|
2718
|
-
|
|
2719
|
-
|
|
2720
|
-
|
|
2721
|
-
|
|
3784
|
+
// A decision made while the decline ran, to open the channel or tune it
|
|
3785
|
+
// out, replaced it, and that is what stands.
|
|
3786
|
+
const decided = this.getDesiredState(entry.serverId, input.channelId);
|
|
3787
|
+
const stands = decided === 'closed';
|
|
3788
|
+
// The channel as the decline leaves it: closed for certain only where
|
|
3789
|
+
// it is registered, not open, its target confirmed, and no lifecycle
|
|
3790
|
+
// work for it outstanding, as the in-effect texts read it. A close that
|
|
3791
|
+
// didn't complete, a channel this host never confirmed closed, or a
|
|
3792
|
+
// registration that went leaves that unknown. A server without
|
|
3793
|
+
// channels.lifecycle keeps its channels as it chooses, and this host
|
|
3794
|
+
// asks it to open or close none of them, so a channel there is confirmed
|
|
3795
|
+
// closed only by the receipt of a request sent while the server had the
|
|
3796
|
+
// grant, whether the channel was registered or known only from a push.
|
|
3797
|
+
const after = this.channels.get(`${entry.serverId}:${input.channelId}`);
|
|
3798
|
+
const closed = after !== undefined && !after.open && !this.unconfirmedChannelTargets.has(after) &&
|
|
3799
|
+
!this.lifecycleOutstanding.has(this.lifecycleKey(entry.serverId, input.channelId));
|
|
3800
|
+
// `closeError` is the result's sentence for the agent: what became of
|
|
3801
|
+
// the channel, and what follows. Every status but `remained closed`
|
|
3802
|
+
// carries one, and that one none, by this tree; `status` is the word a
|
|
3803
|
+
// caller's code reads. Reconciling closes a channel decided closed when
|
|
3804
|
+
// the server next registers it (for a push's placeholder, if it ever
|
|
3805
|
+
// does), if this host directs their lifecycle then (§14.1), which
|
|
3806
|
+
// laterClause says.
|
|
3807
|
+
let closeError;
|
|
3808
|
+
const reach = this.serverReach(entry.serverId);
|
|
3809
|
+
const serverBack = reach === 'gone' ? ' If you need the server back, ask whoever runs this host.' : '';
|
|
3810
|
+
// What helps now with a registered channel the decline didn't leave
|
|
3811
|
+
// closed for certain, read from the state the reads above found, not
|
|
3812
|
+
// from how it came to be: whom to ask where this host doesn't direct the
|
|
3813
|
+
// server's channels, work still under way where some will carry the
|
|
3814
|
+
// decision out (outstandingWorkCarriesOut, not work a removal cancels),
|
|
3815
|
+
// and otherwise channel_close, which asks for the close now.
|
|
3816
|
+
const stepNow = () => !this.directsLifecycle(entry.serverId)
|
|
3817
|
+
? (reach === 'up' ? ' If you need it closed sooner, ask whoever runs this host.' : serverBack)
|
|
3818
|
+
: this.outstandingWorkCarriesOut(entry.serverId, this.lifecycleKey(entry.serverId, input.channelId))
|
|
3819
|
+
? ' Other work for it that\'s still under way applies the decline when its turn comes, so there\'s no need to ' +
|
|
3820
|
+
'decline again to close it.'
|
|
3821
|
+
: ' If you need it closed now, call channel_close.';
|
|
3822
|
+
if (!stands) {
|
|
3823
|
+
// channel_close closes it after all, whichever decision it was, while
|
|
3824
|
+
// the channel is registered; a server that's up without the grant
|
|
3825
|
+
// keeps its channels as it chooses, as the decline's refusal says.
|
|
3826
|
+
const step = after === undefined
|
|
3827
|
+
? `. It isn't registered here any more, so no channel tool can reach it until it's registered here again.${serverBack}`
|
|
3828
|
+
: reach === 'up' && !this.directsLifecycle(entry.serverId)
|
|
3829
|
+
? `, and ${this.lifecycleRefusal(entry.serverId).message}; if you need it closed, ask whoever runs this host.`
|
|
3830
|
+
: `. If you still want it closed, call channel_close.${serverBack}`;
|
|
3831
|
+
closeError = decided === 'tuned-out'
|
|
3832
|
+
? `The decline is recorded, but the channel was tuned out meanwhile, and that decision stands: its messages go to ` +
|
|
3833
|
+
`the subconscious${step}`
|
|
3834
|
+
: `The decline is recorded, but a later decision to open the channel replaced it, and that decision stands${step}`;
|
|
3835
|
+
}
|
|
3836
|
+
else if (closed) {
|
|
3837
|
+
// Closed for certain, whatever became of the decline's own close: one
|
|
3838
|
+
// refused for a grant that went after an earlier operation confirmed
|
|
3839
|
+
// the close changes nothing the agent needs.
|
|
3840
|
+
}
|
|
3841
|
+
else if (closeFailed) {
|
|
3842
|
+
// What happened comes from the failure: a registration that went
|
|
3843
|
+
// while the close was out says so, since the server may have closed it
|
|
3844
|
+
// first, and one that came back since says that; a request that failed
|
|
3845
|
+
// while the registration went says both. What helps comes from the
|
|
3846
|
+
// state now.
|
|
3847
|
+
const failure = closeFailure instanceof ChannelLifecycleError ? closeFailure : undefined;
|
|
3848
|
+
const went = failure?.kind === 'cancelled' || failure?.kind === 'unlisted';
|
|
3849
|
+
closeError = withStop(`The decline is recorded, and this host closes the channel ${laterClause(entry)}; ` +
|
|
3850
|
+
(!went ? `closing it now didn't complete: ${lifecycleClause(closeFailure)}`
|
|
3851
|
+
: after !== undefined
|
|
3852
|
+
? 'its registration went and came back while the close was out'
|
|
3853
|
+
: `it isn't registered here any more: ${failure.message}`)) + (after === undefined ? (went ? '' : ' It isn\'t registered here any more.') + serverBack : stepNow());
|
|
3854
|
+
}
|
|
3855
|
+
else if (after === undefined) {
|
|
3856
|
+
// The registration went while the acknowledgment was out, so no close
|
|
3857
|
+
// was tried.
|
|
3858
|
+
closeError = withStop(`The decline is recorded, and this host closes the channel ${laterClause(entry)}; it isn't registered here any more` +
|
|
3859
|
+
(reach !== 'up' ? `: ${unreachableClause(entry.serverId, reach)}` : '')) + serverBack;
|
|
3860
|
+
}
|
|
3861
|
+
else if (!this.directsLifecycle(entry.serverId)) {
|
|
3862
|
+
closeError = reach === 'up'
|
|
3863
|
+
? `The decline is recorded, but ${this.lifecycleRefusal(entry.serverId).message}, so the server keeps this one open ` +
|
|
3864
|
+
`or closed as it chooses, and declining again won't change that. This host closes it ${laterClause(entry)}. If you ` +
|
|
3865
|
+
'need it closed sooner, ask whoever runs this host.'
|
|
3866
|
+
: `The decline is recorded, but ${unreachableClause(entry.serverId, reach)}, so the channel may not be closed there ` +
|
|
3867
|
+
`yet. This host closes it ${laterClause(entry)}, so there's no need to decline again to close it.` + serverBack;
|
|
3868
|
+
}
|
|
3869
|
+
else {
|
|
3870
|
+
// This host directs the channel's lifecycle and its close didn't fail,
|
|
3871
|
+
// so what remains is other work for it, or a change since that close's
|
|
3872
|
+
// receipt that left it unconfirmed; the step says which.
|
|
3873
|
+
closeError = 'The decline is recorded, but the channel isn\'t closed for certain yet.' + stepNow();
|
|
3874
|
+
}
|
|
3875
|
+
// Another decline is taken only where this one was: the channel
|
|
3876
|
+
// registered, not open, and not decided open.
|
|
3877
|
+
const again = stands && after !== undefined && !after.open;
|
|
3878
|
+
const acknowledgmentError = ackFailure?.(again ? 'call channel_decline again with the same arguments' : undefined);
|
|
3879
|
+
// What the decline found, in a word: the channel remained closed, the
|
|
3880
|
+
// decline stands though the channel may not be closed, or a later
|
|
3881
|
+
// decision replaced it.
|
|
3882
|
+
const status = !stands ? 'replaced' : closed ? 'remained closed' : 'declined';
|
|
3883
|
+
// An audit record nothing reads back: the decline took effect above, so
|
|
3884
|
+
// a log that refuses it is the operator's to hear about, not a failure
|
|
3885
|
+
// of the decline.
|
|
3886
|
+
try {
|
|
3887
|
+
this.appendLifecycleEvent({
|
|
3888
|
+
kind: 'invitation-declined',
|
|
3889
|
+
serverId: entry.serverId,
|
|
3890
|
+
channelId: input.channelId,
|
|
3891
|
+
messageId: input.messageId,
|
|
3892
|
+
acknowledgment: representation ?? input.acknowledge,
|
|
3893
|
+
timestamp: new Date().toISOString(),
|
|
3894
|
+
});
|
|
3895
|
+
}
|
|
3896
|
+
catch (err) {
|
|
3897
|
+
console.error(`[channel-decline] server=${entry.serverId} channel=${logValue(input.channelId)}: the declined invitation wasn't ` +
|
|
3898
|
+
`recorded: ${err instanceof Error ? err.message : String(err)}`);
|
|
3899
|
+
}
|
|
2722
3900
|
return {
|
|
2723
3901
|
success: true,
|
|
2724
3902
|
data: {
|
|
2725
3903
|
channelId: input.channelId,
|
|
2726
|
-
status
|
|
3904
|
+
status,
|
|
2727
3905
|
acknowledged,
|
|
2728
3906
|
...(representation ? { representation } : {}),
|
|
2729
3907
|
...(acknowledgmentError ? { acknowledgmentError } : {}),
|
|
2730
|
-
...(closeError ? { closeError
|
|
3908
|
+
...(closeError ? { closeError } : {}),
|
|
2731
3909
|
},
|
|
2732
3910
|
};
|
|
2733
3911
|
}
|
|
@@ -2810,44 +3988,79 @@ export class ChannelRegistry {
|
|
|
2810
3988
|
};
|
|
2811
3989
|
}
|
|
2812
3990
|
/**
|
|
2813
|
-
*
|
|
2814
|
-
*
|
|
2815
|
-
*
|
|
2816
|
-
*
|
|
2817
|
-
*
|
|
2818
|
-
* is
|
|
2819
|
-
*
|
|
2820
|
-
|
|
2821
|
-
|
|
2822
|
-
*
|
|
2823
|
-
*
|
|
2824
|
-
|
|
2825
|
-
*
|
|
2826
|
-
*
|
|
2827
|
-
*
|
|
2828
|
-
*
|
|
2829
|
-
*
|
|
2830
|
-
*
|
|
3991
|
+
* MCPL Spec 14.3 outgoing streaming: forward a text delta to the server
|
|
3992
|
+
* owning the channel. The framework sends each piece of prose once its
|
|
3993
|
+
* publish succeeds, so a stream carries only what was published.
|
|
3994
|
+
* Emitted only when that server's grant has `channels.streaming` —
|
|
3995
|
+
* servers that never opted in receive nothing. Fire-and-forget and never
|
|
3996
|
+
* throws: streaming is an observer surface; the authoritative delivery is
|
|
3997
|
+
* channels/publish.
|
|
3998
|
+
*
|
|
3999
|
+
* `to` is the destination the publish went to, its server and channel.
|
|
4000
|
+
* The chunk goes there while that server registers that channel (Spec
|
|
4001
|
+
* 14.3: the recipient is "the server that registered the target
|
|
4002
|
+
* channel"). A stream doesn't start in a channel its server has declared
|
|
4003
|
+
* inbound-only (#350's rule), not even for a publish delivered there just
|
|
4004
|
+
* before the declaration. One that started there before it goes on, since
|
|
4005
|
+
* the declaration doesn't unregister the channel: a later chunk is for a
|
|
4006
|
+
* publish delivered before it. A bare channel id is resolved as before, to
|
|
4007
|
+
* the one server that registers it, at each call (streamingServerFor), and
|
|
4008
|
+
* keeps no record: a stream sent by destination ends by destination, since
|
|
4009
|
+
* only a destination's `complete` removes its record.
|
|
2831
4010
|
*/
|
|
2832
|
-
sendOutgoingChunk(
|
|
2833
|
-
|
|
4011
|
+
sendOutgoingChunk(to, conversationId, inferenceId, index, delta) {
|
|
4012
|
+
let server;
|
|
4013
|
+
if (typeof to === 'string') {
|
|
4014
|
+
server = this.streamingServerFor(to);
|
|
4015
|
+
}
|
|
4016
|
+
else {
|
|
4017
|
+
const key = destinationKey(to);
|
|
4018
|
+
let started = this.takenStreams.get(inferenceId);
|
|
4019
|
+
const continuing = started?.has(key) ?? false;
|
|
4020
|
+
server = this.streamingServerAt(to, !continuing);
|
|
4021
|
+
if (server && !continuing) {
|
|
4022
|
+
if (!started)
|
|
4023
|
+
this.takenStreams.set(inferenceId, started = new Set());
|
|
4024
|
+
started.add(key);
|
|
4025
|
+
}
|
|
4026
|
+
}
|
|
2834
4027
|
if (!server)
|
|
2835
4028
|
return;
|
|
4029
|
+
const channelId = typeof to === 'string' ? to : to.channelId;
|
|
2836
4030
|
try {
|
|
2837
4031
|
server.sendChannelsOutgoingChunk({ inferenceId, conversationId, channelId, index, delta });
|
|
2838
4032
|
}
|
|
2839
4033
|
catch { /* observer surface — never disturb the turn */ }
|
|
2840
4034
|
}
|
|
2841
|
-
/**
|
|
2842
|
-
|
|
2843
|
-
|
|
4035
|
+
/**
|
|
4036
|
+
* Spec 14.3 companion: final moderated content per channel at stream end.
|
|
4037
|
+
* Given a destination, it goes only where the stream started
|
|
4038
|
+
* (sendOutgoingChunk), while that server still registers that channel,
|
|
4039
|
+
* inbound-only or not, and its grant has `channels.streaming`: once per
|
|
4040
|
+
* destination, whose consumer, such as a TTS utterance, finalizes on it
|
|
4041
|
+
* and reconciles any chunk it missed. A bare channel id is resolved as
|
|
4042
|
+
* before (streamingServerFor).
|
|
4043
|
+
*/
|
|
4044
|
+
sendOutgoingComplete(to, conversationId, inferenceId, text) {
|
|
4045
|
+
let server;
|
|
4046
|
+
if (typeof to === 'string') {
|
|
4047
|
+
server = this.streamingServerFor(to);
|
|
4048
|
+
}
|
|
4049
|
+
else {
|
|
4050
|
+
const started = this.takenStreams.get(inferenceId);
|
|
4051
|
+
if (!started?.delete(destinationKey(to)))
|
|
4052
|
+
return;
|
|
4053
|
+
if (started.size === 0)
|
|
4054
|
+
this.takenStreams.delete(inferenceId);
|
|
4055
|
+
server = this.streamingServerAt(to, false);
|
|
4056
|
+
}
|
|
2844
4057
|
if (!server)
|
|
2845
4058
|
return;
|
|
2846
4059
|
try {
|
|
2847
4060
|
server.sendChannelsOutgoingComplete({
|
|
2848
4061
|
inferenceId,
|
|
2849
4062
|
conversationId,
|
|
2850
|
-
channelId,
|
|
4063
|
+
channelId: typeof to === 'string' ? to : to.channelId,
|
|
2851
4064
|
content: [{ type: 'text', text }],
|
|
2852
4065
|
});
|
|
2853
4066
|
}
|
|
@@ -2861,6 +4074,10 @@ export class ChannelRegistry {
|
|
|
2861
4074
|
const matches = [...this.channels.values()].filter((e) => e.descriptor.id === channelId);
|
|
2862
4075
|
if (matches.length !== 1)
|
|
2863
4076
|
return null;
|
|
4077
|
+
// Nothing is published into an inbound-only channel, so nothing is
|
|
4078
|
+
// streamed there either.
|
|
4079
|
+
if (isInboundOnly(matches[0]))
|
|
4080
|
+
return null;
|
|
2864
4081
|
const server = this.serverRegistry.getServer(matches[0].serverId);
|
|
2865
4082
|
// §5.4: the GRANT gates streaming, not the raw advertisement. The old
|
|
2866
4083
|
// `capabilities?.channels?.streaming` check was doubly wrong: undefined
|
|
@@ -2871,6 +4088,25 @@ export class ChannelRegistry {
|
|
|
2871
4088
|
return null;
|
|
2872
4089
|
return server;
|
|
2873
4090
|
}
|
|
4091
|
+
/**
|
|
4092
|
+
* A destination's server, for a stream message: while that server
|
|
4093
|
+
* registers that channel, and its grant has `channels.streaming` (as in
|
|
4094
|
+
* streamingServerFor). A stream doesn't start in an inbound-only channel.
|
|
4095
|
+
*/
|
|
4096
|
+
streamingServerAt(to, starting) {
|
|
4097
|
+
// The map's key joins the two ids with a colon, so another server's
|
|
4098
|
+
// entry can sit under a destination's key: it has to be this server's.
|
|
4099
|
+
const entry = this.channels.get(`${to.serverId}:${to.channelId}`);
|
|
4100
|
+
if (!entry || entry.serverId !== to.serverId)
|
|
4101
|
+
return null;
|
|
4102
|
+
if (starting && isInboundOnly(entry))
|
|
4103
|
+
return null;
|
|
4104
|
+
const server = this.serverRegistry.getServer(to.serverId);
|
|
4105
|
+
return CapabilityGrant.of(server).has('channels.streaming') ? server : null;
|
|
4106
|
+
}
|
|
4107
|
+
/** Resolve the outbound locus (fork HOME → this-turn's TRIGGERING channel →
|
|
4108
|
+
* process-global default). Public so a multi-segment caller can snapshot it
|
|
4109
|
+
* ONCE and pin every segment to it via routeSpeech's `overrideChannelId`. */
|
|
2874
4110
|
resolveLocus(conversationId) {
|
|
2875
4111
|
const home = this.homeChannelResolver?.(conversationId);
|
|
2876
4112
|
return home ?? this.activeChannelResolver?.(conversationId) ?? this.globalFallbackFor(conversationId);
|
|
@@ -2910,13 +4146,17 @@ export class ChannelRegistry {
|
|
|
2910
4146
|
if (matches.length === 0) {
|
|
2911
4147
|
return {
|
|
2912
4148
|
error: target.serverId
|
|
2913
|
-
? `
|
|
2914
|
-
: `no
|
|
4149
|
+
? `the "${target.serverId}" server has no channel "${target.channelId}" registered here`
|
|
4150
|
+
: `no channel "${target.channelId}" is registered here`,
|
|
2915
4151
|
};
|
|
2916
4152
|
}
|
|
2917
4153
|
if (matches.length > 1) {
|
|
2918
4154
|
return {
|
|
2919
|
-
|
|
4155
|
+
// Speech names no server, and neither its >> prefix nor
|
|
4156
|
+
// channel_publish can: whoever runs this host can. A caller that
|
|
4157
|
+
// can name one reads that none was.
|
|
4158
|
+
error: `channel id "${target.channelId}" is on more than one server, and no server was named for these words; ` +
|
|
4159
|
+
'if you need them there, ask whoever runs this host',
|
|
2920
4160
|
};
|
|
2921
4161
|
}
|
|
2922
4162
|
return { entry: matches[0] };
|
|
@@ -2938,7 +4178,33 @@ export class ChannelRegistry {
|
|
|
2938
4178
|
* possible to send into a closed channel: a closed but registered
|
|
2939
4179
|
* destination is opened first (`openSource` names why), once its server
|
|
2940
4180
|
* and that server's channels.publish grant are known to take the send, so
|
|
2941
|
-
* a refused
|
|
4181
|
+
* a send refused before the open opens nothing; and a failed open sends
|
|
4182
|
+
* nothing.
|
|
4183
|
+
*
|
|
4184
|
+
* A channel its server declared inbound-only (isInboundOnly) takes nothing
|
|
4185
|
+
* the host would post, whichever path the words took, a drafts resend
|
|
4186
|
+
* included: it's refused before anything opens. The channel's queued
|
|
4187
|
+
* lifecycle work and the open await the server, and a channels/changed
|
|
4188
|
+
* update, a re-register or the open's own answer (applyOpenDeclaration)
|
|
4189
|
+
* may declare the channel inbound-only meanwhile, or a removal take it
|
|
4190
|
+
* away. So the check just before the publish, after every await, reads
|
|
4191
|
+
* the channel's registration as it is then, and refuses one that is gone
|
|
4192
|
+
* or inbound-only, or whose server's grant no longer has channels.publish.
|
|
4193
|
+
* A removal during a wait already fails it there (waitForOpenChannel); the
|
|
4194
|
+
* check also catches one made after the last wait, as the opening's notice
|
|
4195
|
+
* can. A registration nothing has confirmed open, such as one that
|
|
4196
|
+
* replaced the one waited for or a retarget of it, or one whose close now
|
|
4197
|
+
* stands (where the host directs the server's lifecycle), is treated as at
|
|
4198
|
+
* the first wait: the words wait for its queued lifecycle work, and the
|
|
4199
|
+
* check runs again on the registration that work leaves. Words refused
|
|
4200
|
+
* after an open for a declaration leave the channel open, and the agent
|
|
4201
|
+
* gets the failure for the words. An open by delivery (`openSource`
|
|
4202
|
+
* 'opened-by-delivery', the default) that turned a closed channel open
|
|
4203
|
+
* also gives the notice that it's open, which says how to close it to a
|
|
4204
|
+
* reader that can.
|
|
4205
|
+
* One that only reconfirmed the transport of a channel already decided
|
|
4206
|
+
* open or tuned out changes no decision, and gives none. When the
|
|
4207
|
+
* registration is gone, the failure says the channel was removed.
|
|
2942
4208
|
*
|
|
2943
4209
|
* Only the connector's `delivered: true` confirms a post. `failed` means
|
|
2944
4210
|
* nothing was posted: the attempt stopped before the request was written,
|
|
@@ -2963,20 +4229,19 @@ export class ChannelRegistry {
|
|
|
2963
4229
|
};
|
|
2964
4230
|
// A send that would be refused is refused before anything opens: a
|
|
2965
4231
|
// closed channel opens only for words that can go out.
|
|
2966
|
-
|
|
2967
|
-
|
|
2968
|
-
return { status: 'failed', destination, reason: `server "${entry.serverId}" not found`, at: at() };
|
|
4232
|
+
if (isInboundOnly(entry)) {
|
|
4233
|
+
return { status: 'failed', destination, reason: inboundOnlyReason(entry), at: at() };
|
|
2969
4234
|
}
|
|
4235
|
+
const server = this.serverRegistry.getServer(entry.serverId);
|
|
2970
4236
|
// §14.1: channels/publish requires channels.publish in the grant. The
|
|
2971
|
-
// host not sending is the enforcement
|
|
2972
|
-
|
|
2973
|
-
|
|
2974
|
-
|
|
2975
|
-
|
|
2976
|
-
|
|
2977
|
-
|
|
2978
|
-
|
|
2979
|
-
}
|
|
4237
|
+
// host not sending is the enforcement, here and at the last check, and
|
|
4238
|
+
// the server's state words the refusal (sendRefusal).
|
|
4239
|
+
const ungranted = () => ({ status: 'failed', destination, reason: this.sendRefusal(entry.serverId), at: at() });
|
|
4240
|
+
if (!server || !CapabilityGrant.of(server).has('channels.publish'))
|
|
4241
|
+
return ungranted();
|
|
4242
|
+
const prevented = (err) => ({
|
|
4243
|
+
status: 'failed', destination, reason: lifecycleClause(err) + refusalRemedy(err), at: at(),
|
|
4244
|
+
});
|
|
2980
4245
|
// Lifecycle work already queued for the channel settles first: words go
|
|
2981
4246
|
// out only into the channel it leaves, and fail visibly if it leaves
|
|
2982
4247
|
// none open.
|
|
@@ -2985,12 +4250,7 @@ export class ChannelRegistry {
|
|
|
2985
4250
|
entry = await this.waitForOpenChannel(entry);
|
|
2986
4251
|
}
|
|
2987
4252
|
catch (err) {
|
|
2988
|
-
return
|
|
2989
|
-
status: 'failed',
|
|
2990
|
-
destination,
|
|
2991
|
-
reason: `lifecycle work prevented delivery: ${connectorText(err instanceof Error ? err.message : String(err))}`,
|
|
2992
|
-
at: at(),
|
|
2993
|
-
};
|
|
4253
|
+
return prevented(err);
|
|
2994
4254
|
}
|
|
2995
4255
|
}
|
|
2996
4256
|
// INVARIANT: it is not possible to send into a closed channel. A send
|
|
@@ -3034,13 +4294,44 @@ export class ChannelRegistry {
|
|
|
3034
4294
|
}
|
|
3035
4295
|
}
|
|
3036
4296
|
catch (err) {
|
|
3037
|
-
return {
|
|
3038
|
-
|
|
3039
|
-
|
|
3040
|
-
|
|
3041
|
-
|
|
3042
|
-
|
|
4297
|
+
return { status: 'failed', destination, reason: openFailedReason(err), at: at() };
|
|
4298
|
+
}
|
|
4299
|
+
}
|
|
4300
|
+
// Checked again here, after every await above, the lifecycle work's, the
|
|
4301
|
+
// open's or any other: a registration that is gone, or inbound-only, at
|
|
4302
|
+
// this moment takes nothing. The entry is read from the map rather than
|
|
4303
|
+
// taken from the last wait: the opening's notice runs in between, and
|
|
4304
|
+
// publish() resumes a microtask after the wait. A registration nothing
|
|
4305
|
+
// has confirmed open, such as one that replaced the one waited for
|
|
4306
|
+
// (registered with open: false) or a retarget of it (marked unconfirmed),
|
|
4307
|
+
// or one whose close now stands (closeStands), is treated as at the
|
|
4308
|
+
// first wait: the words wait for its queued lifecycle work, and
|
|
4309
|
+
// waitForOpenChannel refuses what that work leaves unconfirmed or with
|
|
4310
|
+
// its close standing. The loop opens nothing itself. The check then runs
|
|
4311
|
+
// again on the registration that stands. waitForOpenChannel returns
|
|
4312
|
+
// only a registration it found open and whose close doesn't stand, or
|
|
4313
|
+
// throws, so the loop ends unless the channel keeps changing.
|
|
4314
|
+
const key = `${entry.serverId}:${entry.descriptor.id}`;
|
|
4315
|
+
let current = this.channels.get(key);
|
|
4316
|
+
while (current && !isInboundOnly(current) && (!current.open || this.closeStands(current))) {
|
|
4317
|
+
try {
|
|
4318
|
+
entry = await this.waitForOpenChannel(current);
|
|
3043
4319
|
}
|
|
4320
|
+
catch (err) {
|
|
4321
|
+
return prevented(err);
|
|
4322
|
+
}
|
|
4323
|
+
current = this.channels.get(key);
|
|
4324
|
+
}
|
|
4325
|
+
if (!current)
|
|
4326
|
+
return { status: 'failed', destination, reason: CHANNEL_REMOVED_CLAUSE, at: at() };
|
|
4327
|
+
if (isInboundOnly(current)) {
|
|
4328
|
+
return { status: 'failed', destination, reason: inboundOnlyReason(current), at: at() };
|
|
4329
|
+
}
|
|
4330
|
+
// A grant reduced during any of the waits holds at once (§6.7): the
|
|
4331
|
+
// words already on their way take it too. Its refusal is worded for the
|
|
4332
|
+
// connection that refused (sendRefusal's `checked`).
|
|
4333
|
+
if (!CapabilityGrant.of(server).has('channels.publish')) {
|
|
4334
|
+
return { status: 'failed', destination, reason: this.sendRefusal(entry.serverId, server), at: at() };
|
|
3044
4335
|
}
|
|
3045
4336
|
let result;
|
|
3046
4337
|
try {
|
|
@@ -3059,9 +4350,13 @@ export class ChannelRegistry {
|
|
|
3059
4350
|
* Plain speech for one turn segment: publish `text` to the turn's frozen
|
|
3060
4351
|
* locus and report the PublishOutcome. A failure (or an uncertain outcome)
|
|
3061
4352
|
* is surfaced as a trace and through onRouteFailure, so the agent learns
|
|
3062
|
-
* its words did not (or may not have) reached anyone.
|
|
3063
|
-
*
|
|
3064
|
-
*
|
|
4353
|
+
* its words did not (or may not have) reached anyone. A `failed` one whose
|
|
4354
|
+
* caller holds its words with a notice of its own (`heldOnFailure`) gets
|
|
4355
|
+
* the trace but not onRouteFailure. An ephemeral run's speech with no locus
|
|
4356
|
+
* (null) is its caller's result: it returns as not delivered and surfaces
|
|
4357
|
+
* nothing. This is host-owned output routing (see forking-knowledge-miner
|
|
4358
|
+
* LOCUS-ROUTING-DESIGN), which replaced the per-surface sticky auto-post
|
|
4359
|
+
* that used to live in discord-mcpl.
|
|
3065
4360
|
*/
|
|
3066
4361
|
async deliverSpeech(conversationId, text,
|
|
3067
4362
|
/** The turn's FROZEN locus, snapshotted once by the caller (resolveLocus
|
|
@@ -3078,16 +4373,18 @@ export class ChannelRegistry {
|
|
|
3078
4373
|
* draft with its own notice, so no failure marker is written for it.
|
|
3079
4374
|
* An `unknown` outcome still gets its marker. */
|
|
3080
4375
|
opts) {
|
|
3081
|
-
|
|
4376
|
+
// `logged` is what the log line and the trace say, where it isn't the
|
|
4377
|
+
// agent's reason (the two no-locus reasons below).
|
|
4378
|
+
const fail = (channelId, reason, outcome, logged = reason) => {
|
|
3082
4379
|
const status = outcome.status === 'unknown' ? 'unknown' : 'failed';
|
|
3083
4380
|
const detail = outcome.detail !== undefined ? connectorText(outcome.detail) : undefined;
|
|
3084
4381
|
const detailText = detail !== undefined ? `; connector detail: ${detail}` : '';
|
|
3085
|
-
console.error(`[routeSpeech] ${conversationId}: ${
|
|
4382
|
+
console.error(`[routeSpeech] ${conversationId}: ${logged}${detailText} — speech ${status === 'unknown' ? 'delivery NOT confirmed' : 'NOT routed'} (${text.length} chars stay in chronicle)`);
|
|
3086
4383
|
this.emitTraceFn({
|
|
3087
4384
|
type: 'mcpl:speech-route-failed',
|
|
3088
4385
|
conversationId,
|
|
3089
4386
|
channelId: channelId ?? '',
|
|
3090
|
-
reason,
|
|
4387
|
+
reason: logged,
|
|
3091
4388
|
textLen: text.length,
|
|
3092
4389
|
outcome: status,
|
|
3093
4390
|
...(detail !== undefined ? { detail } : {}),
|
|
@@ -3097,12 +4394,18 @@ export class ChannelRegistry {
|
|
|
3097
4394
|
}
|
|
3098
4395
|
return outcome;
|
|
3099
4396
|
};
|
|
4397
|
+
// These two reasons are the only ones whose log line and trace keep the
|
|
4398
|
+
// operator's words rather than the agent's: connectome-host's
|
|
4399
|
+
// connectome-doctor reads the last [routeSpeech] line for "no locus". Keep
|
|
4400
|
+
// "no locus" in both logged texts. Each names no tool: whether one the
|
|
4401
|
+
// agent may call could post the words isn't known here, and the notice
|
|
4402
|
+
// calls it a routing or configuration situation.
|
|
3100
4403
|
// Runtime backstop for JS callers the compiler can't see: an omitted
|
|
3101
4404
|
// locus is a routing bug at the call site, never something to paper over
|
|
3102
4405
|
// with a live re-resolution.
|
|
3103
4406
|
if (locusChannelId === undefined) {
|
|
3104
|
-
const reason = '
|
|
3105
|
-
return fail(null, reason, { status: 'failed', reason, at: Date.now() });
|
|
4407
|
+
const reason = 'the host lost track of which channel this reply was for; if this keeps happening, ask whoever runs this host';
|
|
4408
|
+
return fail(null, reason, { status: 'failed', reason, at: Date.now() }, 'caller passed no locus (routing bug: every speech path must snapshot the turn locus)');
|
|
3106
4409
|
}
|
|
3107
4410
|
if (!locusChannelId) {
|
|
3108
4411
|
// An ephemeral run with no channel of its own: its plain speech is its
|
|
@@ -3114,8 +4417,10 @@ export class ChannelRegistry {
|
|
|
3114
4417
|
// The turn froze with no locus (no home, no triggering channel, no
|
|
3115
4418
|
// global inbound ever seen) — the agent was told its prose stays in
|
|
3116
4419
|
// the archive; honor that.
|
|
3117
|
-
|
|
3118
|
-
|
|
4420
|
+
// The locus froze at the turn's start, so this says what the turn had.
|
|
4421
|
+
const reason = 'this turn came from no channel, and it had no home or recent channel to reply in; if it should have ' +
|
|
4422
|
+
'had one, ask whoever runs this host';
|
|
4423
|
+
return fail(null, reason, { status: 'failed', reason, at: Date.now() }, 'turn has no locus (no home/trigger channel; nothing to deliver into)');
|
|
3119
4424
|
}
|
|
3120
4425
|
const outcome = await this.publish(conversationId, text, { channelId: locusChannelId, routed: true });
|
|
3121
4426
|
const channelId = outcome.destination?.channelId ?? locusChannelId;
|
|
@@ -3145,56 +4450,81 @@ export class ChannelRegistry {
|
|
|
3145
4450
|
return null;
|
|
3146
4451
|
return {
|
|
3147
4452
|
delivered: true,
|
|
4453
|
+
serverId: outcome.destination.serverId,
|
|
3148
4454
|
channelId: outcome.destination.channelId,
|
|
3149
4455
|
...(outcome.messageId !== undefined ? { messageId: outcome.messageId } : {}),
|
|
3150
4456
|
};
|
|
3151
4457
|
}
|
|
3152
|
-
|
|
3153
|
-
|
|
4458
|
+
/**
|
|
4459
|
+
* channel_publish, and the subconscious's speak_in_channel
|
|
4460
|
+
* (publishForAgent), which shares its delivery. Where an agent finds a
|
|
4461
|
+
* channel id differs: the subconscious isn't offered channel_list, and is
|
|
4462
|
+
* given speak_in_channel for the tuned-out channels whose messages it reads.
|
|
4463
|
+
*/
|
|
4464
|
+
async handleToolPublish(input, origin,
|
|
4465
|
+
/** Filled for publishForAgent: the publish's outcome once a request is
|
|
4466
|
+
* attempted, for its trace, or which check of the destination refused
|
|
4467
|
+
* it before anything went out, for its answer. */
|
|
4468
|
+
seen, tool = 'channel_publish') {
|
|
4469
|
+
const findIds = tool === 'channel_publish'
|
|
4470
|
+
? 'channel_list shows the channel ids.'
|
|
4471
|
+
: 'Use the id of a tuned-out channel whose messages you are reading.';
|
|
4472
|
+
// Resolve content: accept both `content` and `text` (backward compat).
|
|
4473
|
+
// speak_in_channel checks its own text first, so only channel_publish
|
|
4474
|
+
// reads this refusal.
|
|
3154
4475
|
const messageText = input.content ?? input.text;
|
|
3155
4476
|
if (!messageText) {
|
|
3156
|
-
return {
|
|
3157
|
-
|
|
3158
|
-
|
|
3159
|
-
|
|
3160
|
-
|
|
4477
|
+
return { success: false, error: 'Nothing was posted: channel_publish needs the message in `content`.', isError: true };
|
|
4478
|
+
}
|
|
4479
|
+
// An empty channelId names nothing, and isn't read as one left out.
|
|
4480
|
+
// speak_in_channel's caller passes one left out as empty, so there it
|
|
4481
|
+
// gets the refusal for one left out, as speak_in_channel has no default.
|
|
4482
|
+
if (input.channelId === '' && tool === 'channel_publish') {
|
|
4483
|
+
return { success: false, error: `Nothing was posted: channelId is empty. ${findIds}`, isError: true };
|
|
3161
4484
|
}
|
|
3162
|
-
// Resolve channelId: default to the most recent incoming
|
|
3163
|
-
//
|
|
4485
|
+
// Resolve channelId: default to the channel of the most recent incoming
|
|
4486
|
+
// message that isn't a reaction, reaction removal, edit or deletion
|
|
4487
|
+
// marker, apart from an edit the coalescer delivers on acceptance as the
|
|
4488
|
+
// agent's first view. An ephemeral run never takes that default
|
|
4489
|
+
// (takesGlobalFallback), so it names one.
|
|
3164
4490
|
const caller = origin?.kind === 'agent' ? origin.agentName : undefined;
|
|
3165
4491
|
const channelId = input.channelId ?? (caller !== undefined ? this.globalFallbackFor(caller) : this.defaultPublishChannel);
|
|
3166
4492
|
if (!channelId) {
|
|
3167
4493
|
return {
|
|
3168
4494
|
success: false,
|
|
3169
|
-
error:
|
|
3170
|
-
?
|
|
3171
|
-
|
|
3172
|
-
|
|
4495
|
+
error: tool === 'speak_in_channel'
|
|
4496
|
+
? `Nothing was posted: speak_in_channel needs a \`channelId\`. ${findIds}`
|
|
4497
|
+
: caller !== undefined && this.takesGlobalFallback?.(caller) === false
|
|
4498
|
+
? 'Nothing was posted: name the channel with channelId. A subagent has no default channel, since its plain '
|
|
4499
|
+
+ 'speech is returned to whoever called it, so channel_publish sends only to a channel it names.'
|
|
4500
|
+
: `Nothing was posted: channel_publish needs a \`channelId\`, and there's no channel to default to yet. ${findIds}`,
|
|
3173
4501
|
isError: true,
|
|
3174
4502
|
};
|
|
3175
4503
|
}
|
|
3176
4504
|
const entry = this.findChannelEntry(channelId);
|
|
3177
4505
|
if (!entry) {
|
|
3178
|
-
|
|
3179
|
-
|
|
3180
|
-
|
|
3181
|
-
isError: true,
|
|
3182
|
-
};
|
|
4506
|
+
if (seen)
|
|
4507
|
+
seen.refusal = 'channel-not-registered';
|
|
4508
|
+
return { success: false, error: `No channel has the id "${channelId}", so nothing was posted. ${findIds}`, isError: true };
|
|
3183
4509
|
}
|
|
3184
|
-
|
|
3185
|
-
|
|
4510
|
+
if (isInboundOnly(entry)) {
|
|
4511
|
+
if (seen)
|
|
4512
|
+
seen.refusal = 'inbound-only';
|
|
3186
4513
|
return {
|
|
3187
4514
|
success: false,
|
|
3188
|
-
error: `
|
|
4515
|
+
error: `Channel ${channelId} is ${inboundOnlyReason(entry)}`,
|
|
3189
4516
|
isError: true,
|
|
3190
4517
|
};
|
|
3191
4518
|
}
|
|
3192
|
-
|
|
3193
|
-
|
|
3194
|
-
|
|
3195
|
-
|
|
3196
|
-
|
|
3197
|
-
|
|
4519
|
+
// The same refusal, in the same words, as plain speech's (sendRefusal),
|
|
4520
|
+
// whose server state is the reason's: nothing awaits between the two.
|
|
4521
|
+
const server = this.serverRegistry.getServer(entry.serverId);
|
|
4522
|
+
if (!server || !CapabilityGrant.of(server).has('channels.publish')) {
|
|
4523
|
+
if (seen) {
|
|
4524
|
+
const reach = this.serverReach(entry.serverId);
|
|
4525
|
+
seen.refusal = reach === 'up' ? 'not-permitted' : `server-${reach}`;
|
|
4526
|
+
}
|
|
4527
|
+
return { success: false, error: `Nothing was posted to channel "${channelId}": ${this.sendRefusal(entry.serverId)}.`, isError: true };
|
|
3198
4528
|
}
|
|
3199
4529
|
const publishParams = {
|
|
3200
4530
|
conversationId: '', // Framework will fill this when wired
|
|
@@ -3216,7 +4546,13 @@ export class ChannelRegistry {
|
|
|
3216
4546
|
}
|
|
3217
4547
|
catch (err) {
|
|
3218
4548
|
outcome = publishErrorOutcome(err, destination, Date.now());
|
|
4549
|
+
// Refused before anything was written: nothing went out, as its words
|
|
4550
|
+
// say, so it's a refusal of the destination like the checks above.
|
|
4551
|
+
if (seen && err instanceof McplRequestError && err.outcome === 'not-sent')
|
|
4552
|
+
seen.refusal = 'not-sent';
|
|
3219
4553
|
}
|
|
4554
|
+
if (seen)
|
|
4555
|
+
seen.outcome = outcome;
|
|
3220
4556
|
if (outcome.status === 'delivered')
|
|
3221
4557
|
return { success: true, data: result };
|
|
3222
4558
|
// The connector's data may say what a multi-part send already posted.
|
|
@@ -3224,8 +4560,8 @@ export class ChannelRegistry {
|
|
|
3224
4560
|
return {
|
|
3225
4561
|
success: false,
|
|
3226
4562
|
error: (outcome.status === 'failed'
|
|
3227
|
-
? `
|
|
3228
|
-
: `
|
|
4563
|
+
? `Nothing was posted to channel "${channelId}": ${outcome.reason}.`
|
|
4564
|
+
: `Posting to channel "${channelId}" wasn't confirmed: ${outcome.reason}. ` +
|
|
3229
4565
|
'It may or may not have been posted, so sending it again could post it twice.') + detail,
|
|
3230
4566
|
isError: true,
|
|
3231
4567
|
};
|