typeclaw 0.48.2 → 0.48.3
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/package.json +1 -1
- package/src/agent/index.ts +35 -9
- package/src/agent/plugin-tools.ts +14 -0
- package/src/agent/todo/continuation-policy.ts +11 -1
- package/src/agent/todo/continuation-state.ts +3 -1
- package/src/agent/todo/continuation-wiring.ts +2 -0
- package/src/agent/tool-file-safety.ts +7 -1
- package/src/agent/tools/channel-reply.ts +18 -1
- package/src/bundled-plugins/security/policies/private-surface-read.ts +88 -32
- package/src/channels/adapters/discord-bot-reactions.ts +1 -0
- package/src/channels/adapters/discord-bot.ts +11 -2
- package/src/channels/adapters/discord-reactions.ts +1 -0
- package/src/channels/adapters/discord.ts +1 -0
- package/src/channels/adapters/slack-bot.ts +11 -2
- package/src/channels/adapters/slack.ts +1 -0
- package/src/channels/completion-claim.ts +307 -0
- package/src/channels/router.ts +275 -55
- package/src/channels/types.ts +4 -1
- package/src/config/providers.ts +16 -10
- package/src/init/models-dev.ts +25 -8
- package/src/mcp/client.ts +65 -7
- package/src/mcp/tools.ts +71 -4
- package/src/permissions/index.ts +1 -0
- package/src/permissions/permissions.ts +23 -0
- package/src/plugin/manager.ts +19 -1
- package/src/sandbox/canonical-secrets.ts +24 -4
- package/src/sandbox/hidden-paths.ts +8 -3
- package/src/sandbox/index.ts +2 -0
- package/src/skills/typeclaw-permissions/SKILL.md +13 -1
- package/src/skills/typeclaw-plugins/SKILL.md +91 -11
package/src/channels/router.ts
CHANGED
|
@@ -39,6 +39,7 @@ import type { Stream } from '@/stream'
|
|
|
39
39
|
|
|
40
40
|
import { extractMentionedUserIds } from './adapters/mention-hints'
|
|
41
41
|
import { formatChannelCommandHelp } from './commands'
|
|
42
|
+
import { isQualifyingWorkResult } from './completion-claim'
|
|
42
43
|
import { detectContinuationWillingness } from './continuation-willingness'
|
|
43
44
|
import { describeError } from './describe-error'
|
|
44
45
|
import {
|
|
@@ -196,6 +197,7 @@ export const SESSION_GC_INTERVAL_MS = 60 * 1000
|
|
|
196
197
|
// recovery paths (`source: 'system'`) bypass.
|
|
197
198
|
export const MAX_CHANNEL_SENDS_PER_TURN = 10
|
|
198
199
|
export const ENGAGE_REACTION_EMOJI = 'eyes'
|
|
200
|
+
export const CONTINUATION_REACTION_EMOJI = 'hourglass_flowing_sand'
|
|
199
201
|
// Best-effort "zipping it / going quiet" ack dropped on the triggering message
|
|
200
202
|
// when the model disengages (channel_disengage); fire-and-forget like engage :eyes:.
|
|
201
203
|
export const DISENGAGE_REACTION_EMOJI = 'zipper_mouth_face'
|
|
@@ -456,20 +458,31 @@ export const MAX_WILLINGNESS_NUDGES = 1
|
|
|
456
458
|
// Injected when a reply that ended the turn (terminal-reply abort) promised to
|
|
457
459
|
// keep working but omitted `more_work_this_turn: true`. Reminder-only, SYSTEM MESSAGE
|
|
458
460
|
// framing so persona-rich models do not reply to the notice itself.
|
|
461
|
+
// Leads with the DELIVERY imperative, mirroring SEND_WILLINGNESS_NUDGE below. An
|
|
462
|
+
// earlier revision closed on a bare "If there is nothing left to do, reply with
|
|
463
|
+
// `NO_REPLY`" and production models took that door after doing the promised work:
|
|
464
|
+
// "nothing left to DO" reads as satisfied the moment the investigation finishes,
|
|
465
|
+
// so the turn exited silent while still holding the answer. Splitting "no work
|
|
466
|
+
// left" from "nothing to report", and scoping NO_REPLY to already-delivered, is
|
|
467
|
+
// the load-bearing part of this wording — do not collapse it back.
|
|
459
468
|
export const WILLINGNESS_NUDGE = [
|
|
460
469
|
'---',
|
|
461
470
|
'**[SYSTEM MESSAGE — not from a human]**',
|
|
462
471
|
'',
|
|
463
|
-
'Your last reply
|
|
464
|
-
'after sending — a successful channel reply ends the turn unless you set',
|
|
472
|
+
'Your last reply promised the human you would keep working, but the turn ended',
|
|
473
|
+
'right after sending — a successful channel reply ends the turn unless you set',
|
|
465
474
|
'`more_work_this_turn: true` on it. This is an automated signal from the channel',
|
|
466
475
|
'router, not a message from anyone in the chat. **Do not acknowledge or reply to',
|
|
467
476
|
'this notice itself.**',
|
|
468
477
|
'',
|
|
469
|
-
'
|
|
470
|
-
'
|
|
471
|
-
'work this turn, set `more_work_this_turn: true`. If
|
|
472
|
-
'
|
|
478
|
+
'Someone is waiting on the result you just promised. Do the work now (fetch data,',
|
|
479
|
+
'run a tool, spawn a subagent) and post what you find — and on any further status',
|
|
480
|
+
'reply that precedes more work this turn, set `more_work_this_turn: true`. If you',
|
|
481
|
+
'already did the work, post the conclusion you reached: having no work left is NOT',
|
|
482
|
+
'the same as having nothing to report, and a promise that never lands reads to the',
|
|
483
|
+
'human as being ignored.',
|
|
484
|
+
'',
|
|
485
|
+
'`NO_REPLY` is correct ONLY if the result you promised is already in the channel.',
|
|
473
486
|
'',
|
|
474
487
|
'---',
|
|
475
488
|
].join('\n')
|
|
@@ -480,6 +493,10 @@ export const WILLINGNESS_NUDGE = [
|
|
|
480
493
|
// needs `more_work_this_turn: true`; this path is a `channel_send` (which never ends the
|
|
481
494
|
// turn) whose follow-up degenerated, so the model just needs to emit the reply it
|
|
482
495
|
// already worked out. Shares MAX_WILLINGNESS_NUDGES so a turn can't double-nudge.
|
|
496
|
+
// Scopes NO_REPLY the same way WILLINGNESS_NUDGE does, and for the same reason:
|
|
497
|
+
// both nudges share `willingnessNudges`, so both are covered by the
|
|
498
|
+
// `no_reply_after_willingness_nudge` fallback. A nudge that still advertised
|
|
499
|
+
// NO_REPLY as an ordinary exit would contradict the guard that answers it.
|
|
483
500
|
export const SEND_WILLINGNESS_NUDGE = [
|
|
484
501
|
'---',
|
|
485
502
|
'**[SYSTEM MESSAGE — not from a human]**',
|
|
@@ -489,8 +506,12 @@ export const SEND_WILLINGNESS_NUDGE = [
|
|
|
489
506
|
'message. This is an automated signal from the channel router, not a message',
|
|
490
507
|
'from anyone in the chat. **Do not acknowledge or reply to this notice itself.**',
|
|
491
508
|
'',
|
|
492
|
-
'Send the answer you just worked out now via your channel send tool.
|
|
493
|
-
'
|
|
509
|
+
'Send the answer you just worked out now via your channel send tool. Post what',
|
|
510
|
+
'you found even if the finding is "no change" or "it failed" — someone is waiting',
|
|
511
|
+
'on the result you promised, and having no work left is not the same as having',
|
|
512
|
+
'nothing to report.',
|
|
513
|
+
'',
|
|
514
|
+
'`NO_REPLY` is correct ONLY if the result you promised is already in the channel.',
|
|
494
515
|
'',
|
|
495
516
|
'---',
|
|
496
517
|
].join('\n')
|
|
@@ -906,6 +927,12 @@ type LiveSession = {
|
|
|
906
927
|
// legitimately keeps its "seen, not replying" ack, unlike the transient
|
|
907
928
|
// engage :eyes: which teardown must strip.
|
|
908
929
|
activeSilentAckReactions: Array<Promise<ReactionRef | null>>
|
|
930
|
+
// One add promise per willingness status posted by the agent, resolving to
|
|
931
|
+
// the removable reaction-instance ref. Cross-turn state on purpose: the
|
|
932
|
+
// hourglass stays visible until a substantive result, fallback, explicit
|
|
933
|
+
// silence, stop, or teardown retires every outstanding promise. Storing the
|
|
934
|
+
// promise synchronously prevents cleanup racing a slow reaction add.
|
|
935
|
+
activeContinuationReactions: Array<Promise<ReactionRef | null>>
|
|
909
936
|
lastTurnAuthorIds: Set<string>
|
|
910
937
|
// Mirror of currentTurnAuthorId at end-of-turn (the LAST speaker of the
|
|
911
938
|
// prior batch), preserved across the drain finally-block which resets
|
|
@@ -931,6 +958,11 @@ type LiveSession = {
|
|
|
931
958
|
// the drain loop's run condition checks BOTH queues so a system
|
|
932
959
|
// reminder alone is enough to trigger a turn.
|
|
933
960
|
pendingSystemReminders: string[]
|
|
961
|
+
// True only for the reminder-only iteration that consumed a willingness
|
|
962
|
+
// nudge. `willingnessNudges` persists across the logical turn, so it remains
|
|
963
|
+
// nonzero after a substantive result and would misclassify NO_REPLY from a
|
|
964
|
+
// later unrelated reminder as another dropped promise.
|
|
965
|
+
willingnessReminderIteration: boolean
|
|
934
966
|
consecutiveSends: Map<string, number>
|
|
935
967
|
// Per-(chat:thread) text of the last reserved bot send. Set
|
|
936
968
|
// SYNCHRONOUSLY inside router.send before the outbound callback awaits,
|
|
@@ -1041,6 +1073,10 @@ type LiveSession = {
|
|
|
1041
1073
|
// reason-specific stranded-toolUse recovery logs. `turnSeq`-stamped so stale
|
|
1042
1074
|
// abort provenance from an earlier turn can never leak into a later retry.
|
|
1043
1075
|
abortReasonThisTurn: { turnSeq: number; reason: string } | null
|
|
1076
|
+
// Set synchronously when a user invokes /stop so user intent supersedes a
|
|
1077
|
+
// terminal-reply stamp even while abort delivery or outcome persistence is
|
|
1078
|
+
// still in flight. Cleared only when a fresh real-user batch starts.
|
|
1079
|
+
userStoppedTurnSeq: number | null
|
|
1044
1080
|
// One-shot output-token budget for the NEXT `session.prompt()` only.
|
|
1045
1081
|
// `installChannelOutputCap` reads and clears it per stream call, so it
|
|
1046
1082
|
// overrides the default backstop for exactly one re-prompt. Set by the
|
|
@@ -1133,6 +1169,10 @@ type LiveSession = {
|
|
|
1133
1169
|
// retry iterations that end the turn. Reset ONLY on a real user batch,
|
|
1134
1170
|
// beside `githubReviewOutputTurn`.
|
|
1135
1171
|
toolExecutionThisLogicalTurn: boolean
|
|
1172
|
+
// Successful, non-communication, non-control tool output observed during
|
|
1173
|
+
// this logical turn. Unlike toolExecutionThisLogicalTurn, channel_reply and
|
|
1174
|
+
// todo/control calls cannot satisfy a later durable completion claim.
|
|
1175
|
+
qualifyingWorkThisLogicalTurn: boolean
|
|
1136
1176
|
// True while a successful `channel_reply({ more_work_this_turn: true })`
|
|
1137
1177
|
// promise remains unfulfilled in this LOGICAL turn. Unlike the per-iteration
|
|
1138
1178
|
// `continueReplyTurn` stamp used by retry authorization and empty-stop
|
|
@@ -1201,6 +1241,10 @@ type LiveSession = {
|
|
|
1201
1241
|
unsubProviderErrors: (() => void) | null
|
|
1202
1242
|
unsubTypingActivity: (() => void) | null
|
|
1203
1243
|
unsubTodoOutcome: (() => void) | null
|
|
1244
|
+
// Serializes outcome persistence. The tail always fulfills so one disk
|
|
1245
|
+
// failure cannot poison every later turn; its value separately reports
|
|
1246
|
+
// whether the latest write succeeded before continuation reads state.
|
|
1247
|
+
todoOutcomeWrite: Promise<boolean>
|
|
1204
1248
|
}
|
|
1205
1249
|
|
|
1206
1250
|
// `event` is null for command invocations that originated outside the inbound
|
|
@@ -1271,6 +1315,7 @@ export type ChannelRouter = {
|
|
|
1271
1315
|
chat: string
|
|
1272
1316
|
thread?: string | null
|
|
1273
1317
|
}) => number
|
|
1318
|
+
hasQualifyingWorkThisLogicalTurn?: (target: ChannelKey) => boolean
|
|
1274
1319
|
getSendRate: (target: {
|
|
1275
1320
|
adapter: ChannelKey['adapter']
|
|
1276
1321
|
workspace: string
|
|
@@ -1575,6 +1620,9 @@ export type CreateChannelRouterOptions = {
|
|
|
1575
1620
|
// than pre-seeding pendingSystemReminders from onPrompt (which would pass even if
|
|
1576
1621
|
// the resolver moved ahead of the continuation).
|
|
1577
1622
|
runIdleContinuation?: typeof runIdleContinuation
|
|
1623
|
+
// Test seam for holding an outcome write open and asserting drain ordering.
|
|
1624
|
+
// Production always uses the real persistence function.
|
|
1625
|
+
recordTurnOutcome?: typeof recordTurnOutcome
|
|
1578
1626
|
// Test seam: override the ensureLive watchdog ceiling so the timeout path
|
|
1579
1627
|
// is exercisable in <100ms instead of the 30s production default.
|
|
1580
1628
|
ensureLiveTimeoutMs?: number
|
|
@@ -2238,6 +2286,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
|
|
|
2238
2286
|
originRef,
|
|
2239
2287
|
promptQueue: [],
|
|
2240
2288
|
pendingSystemReminders: [],
|
|
2289
|
+
willingnessReminderIteration: false,
|
|
2241
2290
|
contextBuffer: [],
|
|
2242
2291
|
currentTurnAttachments: [],
|
|
2243
2292
|
historyTimedAttachments: [],
|
|
@@ -2263,6 +2312,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
|
|
|
2263
2312
|
pendingTurnReactions: [],
|
|
2264
2313
|
silentAckTurn: null,
|
|
2265
2314
|
activeSilentAckReactions: [],
|
|
2315
|
+
activeContinuationReactions: [],
|
|
2266
2316
|
// `lastTurnAuthorId` (string, used for `lastInboundAuthorId` in
|
|
2267
2317
|
// origin) and `lastTurnAuthorIds` (Set, used by
|
|
2268
2318
|
// `grantStickyForReplyTargets` as the fallback when
|
|
@@ -2292,6 +2342,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
|
|
|
2292
2342
|
lastTerminalReplyAbort: null,
|
|
2293
2343
|
continueReplyTurn: null,
|
|
2294
2344
|
abortReasonThisTurn: null,
|
|
2345
|
+
userStoppedTurnSeq: null,
|
|
2295
2346
|
nextPromptMaxTokens: undefined,
|
|
2296
2347
|
skippedTurn: null,
|
|
2297
2348
|
skipLockedSendTurn: null,
|
|
@@ -2300,6 +2351,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
|
|
|
2300
2351
|
stagedFallbackCause: null,
|
|
2301
2352
|
githubReviewOutputTurn: null,
|
|
2302
2353
|
toolExecutionThisLogicalTurn: false,
|
|
2354
|
+
qualifyingWorkThisLogicalTurn: false,
|
|
2303
2355
|
promisedWorkOutstandingThisLogicalTurn: false,
|
|
2304
2356
|
pendingQuoteCandidate: null,
|
|
2305
2357
|
recentEngagedPeerBotTurns: [],
|
|
@@ -2315,6 +2367,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
|
|
|
2315
2367
|
unsubProviderErrors: null,
|
|
2316
2368
|
unsubTypingActivity: null,
|
|
2317
2369
|
unsubTodoOutcome: null,
|
|
2370
|
+
todoOutcomeWrite: Promise.resolve(true),
|
|
2318
2371
|
}
|
|
2319
2372
|
// Raw text is logged on EVERY attempt for operators; the user-facing
|
|
2320
2373
|
// notice is deferred. The upstream SDK retries internally, and each retry
|
|
@@ -2332,13 +2385,24 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
|
|
|
2332
2385
|
live.unsubTodoOutcome = created.session.subscribe((event: unknown) => {
|
|
2333
2386
|
const usage = extractTurnUsage(event)
|
|
2334
2387
|
if (usage === null) return
|
|
2335
|
-
|
|
2388
|
+
const stampedAbort = live.abortReasonThisTurn
|
|
2389
|
+
const termination: 'terminal-after-channel-reply' | undefined =
|
|
2390
|
+
usage.stopReason === 'aborted' &&
|
|
2391
|
+
live.userStoppedTurnSeq !== live.turnSeq &&
|
|
2392
|
+
stampedAbort?.turnSeq === live.turnSeq &&
|
|
2393
|
+
stampedAbort.reason === 'terminal_after_channel_reply'
|
|
2394
|
+
? 'terminal-after-channel-reply'
|
|
2395
|
+
: undefined
|
|
2396
|
+
if (stampedAbort?.turnSeq === live.turnSeq) live.abortReasonThisTurn = null
|
|
2397
|
+
const outcomeArgs = {
|
|
2336
2398
|
agentDir: options.agentDir,
|
|
2337
2399
|
origin: buildLiveOrigin(live),
|
|
2338
2400
|
turnId: live.sessionId,
|
|
2339
2401
|
stopReason: usage.stopReason,
|
|
2402
|
+
...(termination !== undefined ? { termination } : {}),
|
|
2340
2403
|
...(usage.tokens !== undefined ? { tokens: usage.tokens } : {}),
|
|
2341
|
-
}
|
|
2404
|
+
}
|
|
2405
|
+
enqueueTodoOutcomeWrite(live, outcomeArgs)
|
|
2342
2406
|
})
|
|
2343
2407
|
live.unsubTypingActivity = subscribeTypingActivity(created.session, live)
|
|
2344
2408
|
installChannelReplyTerminalHook(live)
|
|
@@ -2681,6 +2745,15 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
|
|
|
2681
2745
|
agent.afterToolCall = async (context, signal) => {
|
|
2682
2746
|
const result = prior ? await prior(context, signal) : undefined
|
|
2683
2747
|
const details = context.result.details as { ok?: unknown; more_work_this_turn?: unknown } | undefined
|
|
2748
|
+
if (
|
|
2749
|
+
isQualifyingWorkResult({
|
|
2750
|
+
toolName: context.toolCall.name,
|
|
2751
|
+
isError: context.isError,
|
|
2752
|
+
details: context.result.details,
|
|
2753
|
+
})
|
|
2754
|
+
) {
|
|
2755
|
+
live.qualifyingWorkThisLogicalTurn = true
|
|
2756
|
+
}
|
|
2684
2757
|
const succeeded = context.toolCall.name === 'channel_reply' && !context.isError && details?.ok === true
|
|
2685
2758
|
const keepTurnAlive = details?.more_work_this_turn === true
|
|
2686
2759
|
if (succeeded) {
|
|
@@ -2693,7 +2766,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
|
|
|
2693
2766
|
live.continueReplyTurn = { turnSeq: live.turnSeq, sendCount: live.successfulChannelSends }
|
|
2694
2767
|
}
|
|
2695
2768
|
}
|
|
2696
|
-
if (succeeded && !keepTurnAlive && agent.signal?.aborted !== true) {
|
|
2769
|
+
if (succeeded && !keepTurnAlive && agent.signal?.aborted !== true && live.userStoppedTurnSeq !== live.turnSeq) {
|
|
2697
2770
|
logger.info(`[channels] ${live.keyId} terminal_after_channel_reply`)
|
|
2698
2771
|
const replyText = (context.toolCall.arguments as { text?: unknown } | undefined)?.text
|
|
2699
2772
|
live.lastTerminalReplyAbort = typeof replyText === 'string' ? { turnSeq: live.turnSeq, text: replyText } : null
|
|
@@ -2813,34 +2886,51 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
|
|
|
2813
2886
|
const maybeContinueTodosChannel = async (live: LiveSession): Promise<void> => {
|
|
2814
2887
|
if (live.destroyed) return
|
|
2815
2888
|
if (live.promptQueue.length > 0 || live.pendingSystemReminders.length > 0) return
|
|
2816
|
-
|
|
2817
|
-
|
|
2818
|
-
|
|
2819
|
-
|
|
2820
|
-
|
|
2821
|
-
|
|
2822
|
-
|
|
2823
|
-
|
|
2824
|
-
|
|
2825
|
-
|
|
2826
|
-
|
|
2889
|
+
// Joined to the outcome-write chain so a concurrent /stop's durable abort is
|
|
2890
|
+
// ORDERED AFTER this decision's own state write instead of racing it. The
|
|
2891
|
+
// decision itself awaits disk, so the stop marker is re-read at delivery
|
|
2892
|
+
// time too: a user who stops mid-decision must not receive the reminder.
|
|
2893
|
+
const decision = live.todoOutcomeWrite.then(async () => {
|
|
2894
|
+
try {
|
|
2895
|
+
await (options.runIdleContinuation ?? runIdleContinuation)({
|
|
2896
|
+
agentDir: options.agentDir,
|
|
2897
|
+
origin: buildLiveOrigin(live),
|
|
2898
|
+
deliver: (text) => {
|
|
2899
|
+
if (live.destroyed || live.userStoppedTurnSeq === live.turnSeq) {
|
|
2900
|
+
logger.info(`[channels] ${live.keyId}: dropping todo continuation reminder after user stop`)
|
|
2901
|
+
return
|
|
2902
|
+
}
|
|
2903
|
+
live.pendingSystemReminders.push(text)
|
|
2904
|
+
},
|
|
2905
|
+
})
|
|
2906
|
+
} catch (err) {
|
|
2907
|
+
logger.warn(`[channels] ${live.keyId}: todo continuation failed: ${describeError(err)}`)
|
|
2908
|
+
}
|
|
2909
|
+
return true
|
|
2910
|
+
})
|
|
2911
|
+
live.todoOutcomeWrite = decision
|
|
2912
|
+
await decision
|
|
2827
2913
|
}
|
|
2828
2914
|
|
|
2829
2915
|
const postEmptyTurnFallback = async (live: LiveSession, cause: string): Promise<void> => {
|
|
2830
2916
|
logger.warn(`[channels] ${live.keyId} empty_turn_fallback cause=${cause}`)
|
|
2831
2917
|
live.emptyTurnFallbackTurn = live.turnSeq
|
|
2832
|
-
|
|
2833
|
-
|
|
2834
|
-
|
|
2835
|
-
|
|
2836
|
-
|
|
2837
|
-
|
|
2838
|
-
|
|
2839
|
-
|
|
2840
|
-
|
|
2841
|
-
|
|
2842
|
-
|
|
2843
|
-
|
|
2918
|
+
try {
|
|
2919
|
+
const result = await send(
|
|
2920
|
+
{
|
|
2921
|
+
adapter: live.key.adapter,
|
|
2922
|
+
workspace: live.key.workspace,
|
|
2923
|
+
chat: live.key.chat,
|
|
2924
|
+
thread: live.key.thread,
|
|
2925
|
+
text: EMPTY_TURN_FALLBACK_TEXT,
|
|
2926
|
+
},
|
|
2927
|
+
{ source: 'system', outputKind: 'meta' },
|
|
2928
|
+
)
|
|
2929
|
+
if (!result.ok) {
|
|
2930
|
+
logger.warn(`[channels] ${live.keyId}: empty-turn fallback send failed: ${result.error}`)
|
|
2931
|
+
}
|
|
2932
|
+
} finally {
|
|
2933
|
+
void dropContinuationReactions(live)
|
|
2844
2934
|
}
|
|
2845
2935
|
}
|
|
2846
2936
|
|
|
@@ -2953,6 +3043,31 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
|
|
|
2953
3043
|
}
|
|
2954
3044
|
}
|
|
2955
3045
|
|
|
3046
|
+
const enqueueTodoOutcomeWrite = (
|
|
3047
|
+
live: LiveSession,
|
|
3048
|
+
args: Parameters<typeof recordTurnOutcome>[0],
|
|
3049
|
+
): Promise<boolean> => {
|
|
3050
|
+
const write = live.todoOutcomeWrite.then(async () => {
|
|
3051
|
+
try {
|
|
3052
|
+
await (options.recordTurnOutcome ?? recordTurnOutcome)(args)
|
|
3053
|
+
return true
|
|
3054
|
+
} catch (err) {
|
|
3055
|
+
logger.error(`[channels] ${live.keyId}: todo outcome capture failed: ${describeError(err)}`)
|
|
3056
|
+
return false
|
|
3057
|
+
}
|
|
3058
|
+
})
|
|
3059
|
+
live.todoOutcomeWrite = write
|
|
3060
|
+
return write
|
|
3061
|
+
}
|
|
3062
|
+
|
|
3063
|
+
const awaitLatestTodoOutcomeWrite = async (live: LiveSession): Promise<boolean> => {
|
|
3064
|
+
while (true) {
|
|
3065
|
+
const write = live.todoOutcomeWrite
|
|
3066
|
+
const succeeded = await write
|
|
3067
|
+
if (write === live.todoOutcomeWrite) return succeeded
|
|
3068
|
+
}
|
|
3069
|
+
}
|
|
3070
|
+
|
|
2956
3071
|
const fireSessionEnd = async (live: LiveSession): Promise<void> => {
|
|
2957
3072
|
if (!live.hooks) return
|
|
2958
3073
|
try {
|
|
@@ -2963,12 +3078,22 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
|
|
|
2963
3078
|
}
|
|
2964
3079
|
|
|
2965
3080
|
const stopCurrentChannelTurn = async (live: LiveSession): Promise<void> => {
|
|
3081
|
+
live.userStoppedTurnSeq = live.turnSeq
|
|
3082
|
+
live.lastTerminalReplyAbort = null
|
|
3083
|
+
live.abortReasonThisTurn = { turnSeq: live.turnSeq, reason: 'user_stop' }
|
|
2966
3084
|
if (live.debounceTimer) clearTimeout(live.debounceTimer)
|
|
2967
3085
|
live.debounceTimer = null
|
|
2968
3086
|
live.firstUnprocessedAt = 0
|
|
2969
3087
|
live.promptQueue.length = 0
|
|
2970
3088
|
live.pendingSystemReminders.length = 0
|
|
2971
3089
|
live.continueReplyTurn = null
|
|
3090
|
+
void dropContinuationReactions(live)
|
|
3091
|
+
enqueueTodoOutcomeWrite(live, {
|
|
3092
|
+
agentDir: options.agentDir,
|
|
3093
|
+
origin: buildLiveOrigin(live),
|
|
3094
|
+
turnId: live.sessionId,
|
|
3095
|
+
stopReason: 'aborted',
|
|
3096
|
+
})
|
|
2972
3097
|
await stopTypingHeartbeat(live)
|
|
2973
3098
|
try {
|
|
2974
3099
|
await live.session.abort()
|
|
@@ -2976,6 +3101,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
|
|
|
2976
3101
|
} catch (err) {
|
|
2977
3102
|
logger.warn(`[channels] ${live.keyId}: command /stop abort failed: ${describeError(err)}`)
|
|
2978
3103
|
}
|
|
3104
|
+
await awaitLatestTodoOutcomeWrite(live)
|
|
2979
3105
|
}
|
|
2980
3106
|
|
|
2981
3107
|
// ensureLive() installs a session BEFORE the engage/observe decision, so a
|
|
@@ -3089,6 +3215,8 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
|
|
|
3089
3215
|
const observed = live.contextBuffer.splice(0, live.contextBuffer.length)
|
|
3090
3216
|
const reminders = live.pendingSystemReminders.splice(0, live.pendingSystemReminders.length)
|
|
3091
3217
|
live.currentTurnAttachments = collectTurnAttachments(observed, batch)
|
|
3218
|
+
live.willingnessReminderIteration =
|
|
3219
|
+
batch.length === 0 && reminders.some((r) => r === WILLINGNESS_NUDGE || r === SEND_WILLINGNESS_NUDGE)
|
|
3092
3220
|
|
|
3093
3221
|
if (batch.length > 0) {
|
|
3094
3222
|
// A fresh user batch starts a NEW logical turn. Drop any provider
|
|
@@ -3136,12 +3264,14 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
|
|
|
3136
3264
|
live.stagedFallbackCause = null
|
|
3137
3265
|
}
|
|
3138
3266
|
live.abortReasonThisTurn = null
|
|
3267
|
+
live.userStoppedTurnSeq = null
|
|
3139
3268
|
live.nextPromptMaxTokens = undefined
|
|
3140
3269
|
// Cleared with the retry budgets (NOT beside resetReviewTurn below) so a
|
|
3141
3270
|
// review landed earlier in this logical turn keeps suppressing the
|
|
3142
3271
|
// empty-turn fallback across the reminder-only retry iterations.
|
|
3143
3272
|
live.githubReviewOutputTurn = null
|
|
3144
3273
|
live.toolExecutionThisLogicalTurn = false
|
|
3274
|
+
live.qualifyingWorkThisLogicalTurn = false
|
|
3145
3275
|
live.promisedWorkOutstandingThisLogicalTurn = false
|
|
3146
3276
|
} else if (live.lastTurnAuthorId !== null) {
|
|
3147
3277
|
live.currentTurnEngageReactions = []
|
|
@@ -3200,6 +3330,8 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
|
|
|
3200
3330
|
live.policyDeniedToolSendsThisTurn.clear()
|
|
3201
3331
|
resetReviewTurn(live.sessionId)
|
|
3202
3332
|
const isRealUserTurn = batch.length > 0
|
|
3333
|
+
await awaitLatestTodoOutcomeWrite(live)
|
|
3334
|
+
await recordTodoTurnStart(live, isRealUserTurn)
|
|
3203
3335
|
const retrievalQuery = composeRetrievalQuery(batch)
|
|
3204
3336
|
// A fresh real-user batch opens a new logical turn. Capture its question
|
|
3205
3337
|
// shape as PENDING (committed only once the turn completes below). The
|
|
@@ -3345,8 +3477,14 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
|
|
|
3345
3477
|
await fireSessionTurnEnd(live)
|
|
3346
3478
|
}
|
|
3347
3479
|
await fireSessionIdle(live)
|
|
3348
|
-
await
|
|
3349
|
-
|
|
3480
|
+
const outcomeWriteSucceeded = await awaitLatestTodoOutcomeWrite(live)
|
|
3481
|
+
if (!outcomeWriteSucceeded) {
|
|
3482
|
+
logger.warn(`[channels] ${live.keyId}: skipping todo continuation after failed outcome write`)
|
|
3483
|
+
} else if (live.userStoppedTurnSeq === live.turnSeq) {
|
|
3484
|
+
logger.info(`[channels] ${live.keyId}: skipping todo continuation after user stop`)
|
|
3485
|
+
} else {
|
|
3486
|
+
await maybeContinueTodosChannel(live)
|
|
3487
|
+
}
|
|
3350
3488
|
await resolveStagedFallback(live)
|
|
3351
3489
|
live.lastTurnAuthorIds = new Set(live.currentTurnAuthorIds)
|
|
3352
3490
|
if (live.currentTurnAuthorId !== null) {
|
|
@@ -4491,8 +4629,8 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
|
|
|
4491
4629
|
live.pendingQuoteCandidate = null
|
|
4492
4630
|
}
|
|
4493
4631
|
const text = normalizeSendText(msg.text)
|
|
4494
|
-
const
|
|
4495
|
-
|
|
4632
|
+
const continuationWillingness = text !== undefined && detectContinuationWillingness(text)
|
|
4633
|
+
const outputKind = opts?.outputKind ?? (continuationWillingness ? 'status' : 'substantive')
|
|
4496
4634
|
|
|
4497
4635
|
// Central enforcement. Tool-initiated sends are subject to two policies:
|
|
4498
4636
|
// a per-turn count cap (kills runaway loops regardless of content) and
|
|
@@ -4586,6 +4724,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
|
|
|
4586
4724
|
let delivered = false
|
|
4587
4725
|
let messageId: string | undefined
|
|
4588
4726
|
let messageIds: readonly string[] | undefined
|
|
4727
|
+
let reactionRef: ReactionRef | undefined
|
|
4589
4728
|
try {
|
|
4590
4729
|
for (const cb of snapshot) {
|
|
4591
4730
|
const result = await cb(msg)
|
|
@@ -4593,6 +4732,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
|
|
|
4593
4732
|
delivered = true
|
|
4594
4733
|
messageId = result.messageId
|
|
4595
4734
|
messageIds = result.messageIds
|
|
4735
|
+
reactionRef = result.reactionRef
|
|
4596
4736
|
break
|
|
4597
4737
|
}
|
|
4598
4738
|
lastError = result.error
|
|
@@ -4623,6 +4763,12 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
|
|
|
4623
4763
|
return { ok: false, error: lastError ?? 'no callback accepted the outbound', code: 'callback-rejected' }
|
|
4624
4764
|
}
|
|
4625
4765
|
|
|
4766
|
+
if (live && continuationWillingness && reactionRef !== undefined) {
|
|
4767
|
+
reactOnContinuationWillingness(live, reactionRef)
|
|
4768
|
+
} else if (live && !continuationWillingness && outputKind === 'substantive') {
|
|
4769
|
+
void dropContinuationReactions(live)
|
|
4770
|
+
}
|
|
4771
|
+
|
|
4626
4772
|
if (live) {
|
|
4627
4773
|
live.successfulChannelSends++
|
|
4628
4774
|
// Promise fulfillment follows OUTPUT KIND, never source:
|
|
@@ -4687,6 +4833,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
|
|
|
4687
4833
|
ok: true,
|
|
4688
4834
|
...(messageId !== undefined ? { messageId } : {}),
|
|
4689
4835
|
...(messageIds !== undefined ? { messageIds } : {}),
|
|
4836
|
+
...(reactionRef !== undefined ? { reactionRef } : {}),
|
|
4690
4837
|
}
|
|
4691
4838
|
}
|
|
4692
4839
|
|
|
@@ -4729,6 +4876,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
|
|
|
4729
4876
|
live.skippedTurn = null
|
|
4730
4877
|
logger.info(`[channels] ${live.keyId} skipped_by_tool reason=${JSON.stringify(reason)}`)
|
|
4731
4878
|
armSilentTurnAck(live, 'skip_response')
|
|
4879
|
+
void dropContinuationReactions(live)
|
|
4732
4880
|
return
|
|
4733
4881
|
}
|
|
4734
4882
|
if (live.skippedTurn !== null && live.skippedTurn.turnSeq === live.turnSeq) {
|
|
@@ -5092,9 +5240,23 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
|
|
|
5092
5240
|
await postEmptyTurnFallback(live, 'empty_stop_after_tool_work_retries_exhausted')
|
|
5093
5241
|
return
|
|
5094
5242
|
}
|
|
5243
|
+
// Explicit NO_REPLY normally records a deliberate choice to stay silent.
|
|
5244
|
+
// Only the reminder iteration that consumed a willingness nudge is different:
|
|
5245
|
+
// the turn-persistent nudge budget remains nonzero after a substantive result,
|
|
5246
|
+
// so using it here would post a bogus fallback on a later unrelated reminder.
|
|
5247
|
+
if (
|
|
5248
|
+
isNoReplySignal(assistantText) &&
|
|
5249
|
+
live.willingnessReminderIteration &&
|
|
5250
|
+
live.successfulChannelSends === successfulSendsBeforePrompt &&
|
|
5251
|
+
live.promptQueue.length === 0
|
|
5252
|
+
) {
|
|
5253
|
+
await postEmptyTurnFallback(live, 'no_reply_after_willingness_nudge')
|
|
5254
|
+
return
|
|
5255
|
+
}
|
|
5095
5256
|
const leakedReasoning = !isNoReplySignal(assistantText)
|
|
5096
5257
|
logger.info(`[channels] ${live.keyId} no_reply${leakedReasoning ? ' (with_leaked_reasoning)' : ''}`)
|
|
5097
5258
|
armSilentTurnAck(live, 'no_reply')
|
|
5259
|
+
void dropContinuationReactions(live)
|
|
5098
5260
|
return
|
|
5099
5261
|
}
|
|
5100
5262
|
|
|
@@ -5290,6 +5452,10 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
|
|
|
5290
5452
|
return live.consecutiveSends.get(consecutiveSendKey(target.chat, target.thread)) ?? 0
|
|
5291
5453
|
}
|
|
5292
5454
|
|
|
5455
|
+
const hasQualifyingWorkThisLogicalTurn = (target: ChannelKey): boolean => {
|
|
5456
|
+
return liveSessions.get(channelKeyId(target))?.qualifyingWorkThisLogicalTurn === true
|
|
5457
|
+
}
|
|
5458
|
+
|
|
5293
5459
|
const getSendRate = (target: {
|
|
5294
5460
|
adapter: ChannelKey['adapter']
|
|
5295
5461
|
workspace: string
|
|
@@ -5322,6 +5488,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
|
|
|
5322
5488
|
clearQueuedEngageReactions(live)
|
|
5323
5489
|
dropEngageReactions(live, live.currentTurnEngageReactions)
|
|
5324
5490
|
live.currentTurnEngageReactions = []
|
|
5491
|
+
void dropContinuationReactions(live)
|
|
5325
5492
|
if (live.debounceTimer) clearTimeout(live.debounceTimer)
|
|
5326
5493
|
live.debounceTimer = null
|
|
5327
5494
|
live.unsubProviderErrors?.()
|
|
@@ -5359,12 +5526,9 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
|
|
|
5359
5526
|
if (live.draining) continue
|
|
5360
5527
|
if (live.promptQueue.length > 0) continue
|
|
5361
5528
|
// pendingSystemReminders is checked alongside promptQueue because both
|
|
5362
|
-
// represent pending work that drain() will process.
|
|
5363
|
-
//
|
|
5364
|
-
//
|
|
5365
|
-
// the line above — but the guard exists to keep the invariant honest
|
|
5366
|
-
// for any future caller that queues a reminder without immediately
|
|
5367
|
-
// waking the drain loop.
|
|
5529
|
+
// represent pending work that drain() will process. Reminder injection
|
|
5530
|
+
// wakes an idle session immediately, but deliberately leaves a pending
|
|
5531
|
+
// inbound debounce in charge so both queues coalesce into one turn.
|
|
5368
5532
|
if (live.pendingSystemReminders.length > 0) continue
|
|
5369
5533
|
if (t - live.lastInboundAt <= SESSION_IDLE_MS) continue
|
|
5370
5534
|
if (isPinnedByRunningChild(live.sessionId, live.keyId, 'idle_gc evicting')) continue
|
|
@@ -5760,17 +5924,12 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
|
|
|
5760
5924
|
// hard-block that legitimate fetch.
|
|
5761
5925
|
forgetSharedLoopGuardTool(live.sessionId, SUBAGENT_OUTPUT_TOOL_NAME)
|
|
5762
5926
|
logger.info(`[channels] ${live.keyId}: subagent-completion reminder queued task=${args.taskId} ok=${args.ok}`)
|
|
5763
|
-
// Wake
|
|
5764
|
-
//
|
|
5765
|
-
//
|
|
5766
|
-
//
|
|
5767
|
-
//
|
|
5768
|
-
|
|
5769
|
-
// not apply. Mirrors the TUI path's `idle ? 'interrupt' : 'queue'`
|
|
5770
|
-
// semantics: the channel router doesn't have a `delivery: interrupt`
|
|
5771
|
-
// mechanism (no in-flight abort during a turn), but firing drain()
|
|
5772
|
-
// immediately is the equivalent for an idle session.
|
|
5773
|
-
if (!live.draining) {
|
|
5927
|
+
// Wake an idle session immediately, but leave an already-scheduled inbound
|
|
5928
|
+
// debounce in charge. Starting a fire-and-forget drain here would splice
|
|
5929
|
+
// both queues before the debounce owner can await that drain, making the
|
|
5930
|
+
// caller observe an in-progress turn and defeating deterministic coalescing.
|
|
5931
|
+
// An in-flight drain picks up the reminder on its next iteration.
|
|
5932
|
+
if (!live.draining && live.debounceTimer === null) {
|
|
5774
5933
|
void drain(live)
|
|
5775
5934
|
}
|
|
5776
5935
|
return { kind: 'delivered', keyId: live.keyId }
|
|
@@ -6009,10 +6168,71 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
|
|
|
6009
6168
|
).then(() => undefined)
|
|
6010
6169
|
}
|
|
6011
6170
|
|
|
6171
|
+
const reactOnContinuationWillingness = (live: LiveSession, reactionRef: ReactionRef): void => {
|
|
6172
|
+
const addResult = react({
|
|
6173
|
+
adapter: live.key.adapter,
|
|
6174
|
+
workspace: live.key.workspace,
|
|
6175
|
+
chat: live.key.chat,
|
|
6176
|
+
thread: live.key.thread,
|
|
6177
|
+
reactionRef,
|
|
6178
|
+
emoji: CONTINUATION_REACTION_EMOJI,
|
|
6179
|
+
})
|
|
6180
|
+
void addResult
|
|
6181
|
+
.then((result) => {
|
|
6182
|
+
if (!result.ok && result.code !== 'unsupported') {
|
|
6183
|
+
logger.info(
|
|
6184
|
+
`[channels] continuation-react failed adapter=${live.key.adapter} chat=${live.key.chat}: ${result.error}`,
|
|
6185
|
+
)
|
|
6186
|
+
}
|
|
6187
|
+
})
|
|
6188
|
+
.catch((err) => {
|
|
6189
|
+
logger.info(
|
|
6190
|
+
`[channels] continuation-react threw adapter=${live.key.adapter} chat=${live.key.chat}: ${describeError(err)}`,
|
|
6191
|
+
)
|
|
6192
|
+
})
|
|
6193
|
+
live.activeContinuationReactions.push(
|
|
6194
|
+
addResult.then((result) => (result.ok ? (result.reactionRef ?? null) : null)).catch(() => null),
|
|
6195
|
+
)
|
|
6196
|
+
}
|
|
6197
|
+
|
|
6198
|
+
const dropContinuationReactions = (live: LiveSession): Promise<void> => {
|
|
6199
|
+
const addPromises = live.activeContinuationReactions
|
|
6200
|
+
if (addPromises.length === 0) return Promise.resolve()
|
|
6201
|
+
live.activeContinuationReactions = []
|
|
6202
|
+
return Promise.all(
|
|
6203
|
+
addPromises.map((addPromise) =>
|
|
6204
|
+
addPromise
|
|
6205
|
+
.then((reactionRef) => {
|
|
6206
|
+
if (reactionRef === null) return undefined
|
|
6207
|
+
return removeReaction({
|
|
6208
|
+
adapter: live.key.adapter,
|
|
6209
|
+
workspace: live.key.workspace,
|
|
6210
|
+
chat: live.key.chat,
|
|
6211
|
+
thread: live.key.thread,
|
|
6212
|
+
reactionRef,
|
|
6213
|
+
})
|
|
6214
|
+
})
|
|
6215
|
+
.then((result) => {
|
|
6216
|
+
if (result && !result.ok && result.code !== 'unsupported' && result.code !== 'not-found') {
|
|
6217
|
+
logger.info(
|
|
6218
|
+
`[channels] continuation-unreact failed adapter=${live.key.adapter} chat=${live.key.chat}: ${result.error}`,
|
|
6219
|
+
)
|
|
6220
|
+
}
|
|
6221
|
+
})
|
|
6222
|
+
.catch((err) => {
|
|
6223
|
+
logger.info(
|
|
6224
|
+
`[channels] continuation-unreact threw adapter=${live.key.adapter} chat=${live.key.chat}: ${describeError(err)}`,
|
|
6225
|
+
)
|
|
6226
|
+
}),
|
|
6227
|
+
),
|
|
6228
|
+
).then(() => undefined)
|
|
6229
|
+
}
|
|
6230
|
+
|
|
6012
6231
|
return {
|
|
6013
6232
|
route,
|
|
6014
6233
|
send,
|
|
6015
6234
|
getConsecutiveSendCount,
|
|
6235
|
+
hasQualifyingWorkThisLogicalTurn,
|
|
6016
6236
|
getSendRate,
|
|
6017
6237
|
registerOutbound,
|
|
6018
6238
|
unregisterOutbound,
|
package/src/channels/types.ts
CHANGED
|
@@ -273,8 +273,11 @@ export type SendErrorCode =
|
|
|
273
273
|
// Optional throughout: an adapter whose SDK does not hand back an id (legacy
|
|
274
274
|
// slack/discord user-account adapters) omits both, and callers must treat a
|
|
275
275
|
// missing id as "not available", never as an error.
|
|
276
|
+
// `reactionRef` is the outbound message's adapter-owned TARGET ref — the entity
|
|
277
|
+
// a later ReactionRequest reacts to. It is explicitly NOT the per-reaction
|
|
278
|
+
// removal-instance ref returned by `ReactionResult.reactionRef` after an add.
|
|
276
279
|
export type SendResult =
|
|
277
|
-
| { ok: true; messageId?: string; messageIds?: readonly string[] }
|
|
280
|
+
| { ok: true; messageId?: string; messageIds?: readonly string[]; reactionRef?: ReactionRef }
|
|
278
281
|
| { ok: false; error: string; code?: SendErrorCode }
|
|
279
282
|
|
|
280
283
|
export type OutboundCallback = (msg: OutboundMessage) => Promise<SendResult>
|