Skip to content

feat: sub-agent continuation chain hop (#196)#1

Merged
cael-dandelion-cult merged 1 commit into
feature/context-pressurefrom
elliott/subagent-continuation
Mar 5, 2026
Merged

feat: sub-agent continuation chain hop (#196)#1
cael-dandelion-cult merged 1 commit into
feature/context-pressurefrom
elliott/subagent-continuation

Conversation

@karmafeast

Copy link
Copy Markdown

Summary

Parse [[CONTINUE_DELEGATE:]] brackets from sub-agent output in the announce flow. When a sub-agent's findings contain a delegate signal, strip the brackets, spawn a new sub-agent as a child of the same requester session, and announce the stripped text normally.

What this enables

Shard-to-shard chain hops: delegate 1 reads data, emits [[CONTINUE_DELEGATE: task | silent-wake]], gateway parses it at the announce boundary and spawns delegate 2 automatically. No parent-session relay needed.

Implementation

  • 1 file changed: src/agents/subagent-announce.ts (+62/-3)
  • Bracket parsing via existing stripContinuationSignal() from tokens.ts
  • Chain spawn via existing spawnSubagentDirect() with inherited silentAnnounce/wakeOnReturn flags
  • Bounded by existing maxSpawnDepth safety cap
  • Delayed spawn supported (+Ns suffix), capped at 300s
  • Fire-and-forget spawn — doesn't block the announce flow

Tests

128/128 existing tests pass. Build clean.

Closes #196

Parse [[CONTINUE_DELEGATE:]] brackets from sub-agent output in the
announce flow (subagent-announce.ts). When a sub-agent's findings
contain a delegate signal, strip the brackets, spawn a new sub-agent
as a child of the same requester session, and announce the stripped
text normally.

This enables shard-to-shard chain hops: delegate 1 reads data,
emits [[CONTINUE_DELEGATE: task | silent-wake]], gateway parses it
at the announce boundary and spawns delegate 2 automatically.

The new chain hop inherits silentAnnounce/wakeOnReturn flags from
the signal, and is bounded by the existing maxSpawnDepth safety cap
in spawnSubagentDirect.

Implementation: ~55 lines in subagent-announce.ts. No new files.
128/128 existing tests pass.
@karmafeast
karmafeast force-pushed the elliott/subagent-continuation branch from 396984d to 706adb9 Compare March 5, 2026 05:08
@cael-dandelion-cult
cael-dandelion-cult merged commit 525a2ea into feature/context-pressure Mar 5, 2026
2 of 9 checks passed
cael-dandelion-cult added a commit that referenced this pull request Mar 6, 2026
1. Document delayed fan-out generation guard behavior in tool description
   and JSDoc (finding #1: delayed delegates self-cancel at tolerance=0)
2. Harmonize chain-hop timer with generationGuardTolerance config
   (finding #3: bracket chain-hop timers now honor tolerance, matching
   agent-runner delegate timer behavior)

Found by: web Codex review (figs dispatch)
karmafeast pushed a commit that referenced this pull request Mar 7, 2026
- 6 tests for maxChainLength enforcement via task-prefix [continuation:chain-hop:N]
  - Boundary enforcement (hop 9 → 10 >= 10 → block)
  - Cost cap blocking when chain length within bounds
  - Custom maxChainLength from config
  - First bracket-started hop (no prefix → hop 0)
- FINDINGS.md: P0 status corrected (committed at 5118e7a, not 'locally applied')
- FINDINGS.md: P1/P2 status updated (prince branches in progress)
- FINDINGS.md: WORK timer tolerance asymmetry documented
- FINDINGS.md: Path-dependency gap (bracket-started chains) documented (Codex 5.4 finding #1)

Test: OPENCLAW_TEST_FAST=1 npx vitest run src/agents/subagent-announce.chain-guard.test.ts
Result: 6/6 pass
karmafeast pushed a commit that referenced this pull request Mar 7, 2026
Bracket-origin delegate spawns now emit [continuation:chain-hop:N] prefix
matching the tool-origin path. This ensures the announce-side guard at
subagent-announce.ts:1346 can enforce maxChainLength identically for both
bracket-origin and tool-origin chains.

Before: [continuation] Delegated task (turn N/M): ...
After:  [continuation:chain-hop:N] Delegated task (turn N/M): ...

Addresses WORKORDER6-codex54.md Workstream B and Codex 5.4 finding #1.

Test: failing test written first (confirmed [continuation] prefix lacked
chain-hop:N), then fix applied. 41/41 agent-runner tests pass.
cael-dandelion-cult pushed a commit that referenced this pull request Apr 2, 2026
* feat: add QQ Bot channel extension

* fix(qqbot): add setupWizard to runtime plugin for onboard re-entry

* fix: fix review

* fix: fix review

* chore: sync lockfile and config-docs baseline for qqbot extension

* refactor: 移除图床服务器相关代码

* fix

* docs: 新增 QQ Bot 插件文档并修正链接路径

* refactor: remove credential backup functionality and update setup logic

- Deleted the credential backup module to streamline the codebase.
- Updated the setup surface to handle client secrets more robustly, allowing for configured secret inputs.
- Simplified slash commands by removing unused hot upgrade compatibility checks and related functions.
- Adjusted types to use SecretInput for client secrets in QQBot configuration.
- Modified bundled plugin metadata to allow additional properties in the config schema.

* feat: 添加本地媒体路径解析功能,修正 QQBot 媒体路径处理

* feat: 添加本地媒体路径解析功能,修正 QQBot 媒体路径处理

* feat: remove qqbot-media and qqbot-remind skills, add tests for config and setup

- Deleted the qqbot-media and qqbot-remind skills documentation files.
- Added unit tests for qqbot configuration and setup processes, ensuring proper handling of SecretRef-backed credentials and account configurations.
- Implemented tests for local media path remapping, verifying correct resolution of media file paths.
- Removed obsolete channel and remind tools, streamlining the codebase.

* feat: 更新 QQBot 配置模式,添加音频格式和账户定义

* feat: 添加 QQBot 频道管理和定时提醒技能,更新媒体路径解析功能

* fix

* feat: 添加 /bot-upgrade 指令以查看 QQBot 插件升级指引

* feat: update reminder and qq channel skills

* feat: 更新remind工具投递目标地址格式

* feat: Refactor QQBot payload handling and improve code documentation

- Simplified and clarified the structure of payload interfaces for Cron reminders and media messages.
- Enhanced the parsing function to provide clearer error messages and improved validation.
- Updated platform utility functions for better cross-platform compatibility and clearer documentation.
- Improved text parsing utilities for better readability and consistency in emoji representation.
- Optimized upload cache management with clearer comments and reduced redundancy.
- Integrated QQBot plugin into the bundled channel plugins and updated metadata for installation.

* OK apps/macos/Sources/OpenClaw/HostEnvSecurityPolicy.generated.swift

> [email protected] check:bundled-channel-config-metadata /Users/yuehuali/code/PR/openclaw
> node --import tsx scripts/generate-bundled-channel-config-metadata.ts --check

[bundled-channel-config-metadata] stale generated output at src/config/bundled-channel-config-metadata.generated.ts
 ELIFECYCLE  Command failed with exit code 1.
 ELIFECYCLE  Command failed with exit code 1.

* feat: 添加 QQBot 渠道配置及相关账户设置

* fix(qqbot): resolve 14 high-priority bugs from PR openclaw#52986 review

DM routing (7 fixes):
- #1: DM slash-command replies use sendDmMessage(guildId) instead of sendC2CMessage(senderId)
- #2: DM qualifiedTarget uses qqbot:dm:${guildId} instead of qqbot:c2c:${senderId}
- #3: sendTextChunks adds DM branch
- #4: sendMarkdownReply adds DM branch for text and Base64 images
- #5: parseAndSendMediaTags maps DM to targetType:dm + guildId
- #6: sendTextToTarget DM branch uses sendDmMessage; MessageTarget adds guildId field
- #7: handleImage/Audio/Video/FilePayload add DM branches

Other high-priority fixes:
- #8: Fix sendC2CVoiceMessage/sendGroupVoiceMessage parameter misalignment
- #9: broadcastMessage uses groupOpenid instead of member_openid for group users
- #10: Unify KnownUser storage - proactive.ts delegates to known-users.ts
- #11: Remove invalid recordKnownUser calls for guild/DM users
- #12: sendGroupMessage uses sendAndNotify to trigger onMessageSent hook
- #13: sendPhoto channel unsupported returns error field
- #14: sendTextAfterMedia adds channel and dm branches

Type fixes:
- DeliverEventContext adds guildId field
- MediaTargetContext.targetType adds dm variant
- sendPlainTextReply imgMediaTarget adds DM branch

* fix(qqbot): resolve 2 blockers + 7 medium-priority bugs from PR openclaw#52986 review

Blocker-1: Remove unused dmPolicy config knob
- dmPolicy was declared in schema/types/plugin.json but never consumed at runtime
- Removed from config-schema.ts, types.ts, and openclaw.plugin.json
- allowFrom remains active (already wired into framework command-auth)

Blocker-2: Gate sensitive slash commands with allowFrom authorization
- SlashCommand interface adds requireAuth?: boolean
- SlashCommandContext adds commandAuthorized: boolean
- /bot-logs set to requireAuth: true (reads local log files)
- matchSlashCommand rejects unauthorized senders for requireAuth commands
- trySlashCommandOrEnqueue computes commandAuthorized from allowFrom config

Medium-priority fixes:
- #15: Strip non-HTTP/non-local markdown image tags to prevent path leakage
- #16: applyQQBotAccountConfig clears clientSecret when setting clientSecretFile and vice versa
- #17: getAdminMarkerFile sanitizes accountId to prevent path traversal
- #18: URGENT_COMMANDS uses exact match instead of startsWith prefix match
- #19: isCronExpression validates each token starts with a cron-valid character
- #20: --token format validation rejects malformed input without colon separator
- #21: resolveDefaultQQBotAccountId checks QQBOT_APP_ID environment variable

* test(qqbot): add focused tests for slash command authorization path

- Unauthorized sender rejected for /bot-logs (requireAuth: true)
- Authorized sender allowed for /bot-logs
- Non-requireAuth commands (/bot-ping, /bot-help, /bot-version) work for all senders
- Unknown slash commands return null (passthrough)
- Non-slash messages return null
- Usage query (/bot-logs ?) also gated by auth check

* fix(qqbot): align global TTS fallback with framework config resolution

- Extract isGlobalTTSAvailable to utils/audio-convert.ts, mirroring core
  resolveTtsConfig logic: check auto !== 'off', fall back to legacy
  enabled boolean, default to off when neither is set.
- Add pre-check in reply-dispatcher before calling globalTextToSpeech to
  avoid unnecessary TTS calls and noisy error logs when TTS is not
  configured.
- Remove inline as any casts; use OpenClawConfig type throughout.
- Refactor handleAudioPayload into flat early-return structure with
  unified send path (plugin TTS → global fallback → send).

* fix(qqbot): break ESM circular dependency causing multi-account startup crash

The bundled gateway chunk had a circular static import on the channel
chunk (gateway -> outbound-deliver -> channel, while channel dynamically
imports gateway). When two accounts start concurrently via Promise.all,
the first dynamic import triggers module graph evaluation; the circular
reference causes api exports (including runDiagnostics) to resolve as
undefined before the module finishes evaluating.

Fix: extract chunkText and TEXT_CHUNK_LIMIT from channel.ts into a new
text-utils.ts leaf module. outbound-deliver.ts now imports from
text-utils.ts, breaking the cycle. channel.ts re-exports for backward
compatibility.

* fix(qqbot): serialize gateway module import to prevent multi-account startup race

When multiple accounts start concurrently via Promise.all, each calls
await import('./gateway.js') independently. Due to ESM circular
dependencies in the bundled output, the first import can resolve
transitive exports as undefined before module evaluation completes.

Fix: cache the dynamic import promise in a module-level variable so all
concurrent startAccount calls share the same import, ensuring the
gateway module is fully evaluated before any account uses it.

* refactor(qqbot): remove startup greeting logic

Remove getStartupGreetingPlan and related startup greeting delivery:
- Delete startup-greeting.ts (greeting plan, marker persistence)
- Delete admin-resolver.ts (admin resolution, greeting dispatch)
- Remove startup greeting calls from gateway READY/RESUMED handlers
- Remove isFirstReadyGlobal flag and adminCtx

* fix(qqbot): skip octal escape decoding for Windows local paths

Windows paths like C:\Users\1\file.txt contain backslash-digit sequences
that were incorrectly matched as octal escape sequences and decoded,
corrupting the file path. Detect Windows local paths (drive letter or UNC
prefix) and skip the octal decoding step for them.

* fix bot issue

* feat: 支持 TTS 自动开关并清理配置中的 clientSecretFile

* docs: 添加 QQBot 配置和消息处理的设计说明

* rebase

* fix(qqbot): align slash-command auth with shared command-auth model

Route requireAuth:true slash commands (e.g. /bot-logs) through the
framework's api.registerCommand() so resolveCommandAuthorization()
applies commands.allowFrom.qqbot precedence and qqbot: prefix
normalization before any handler runs.

- slash-commands.ts: registerCommand() now auto-routes by requireAuth
  into two maps (commands / frameworkCommands); getFrameworkCommands()
  exports the auth-required set for framework registration; bot-help
  lists both maps
- index.ts: registerFull() iterates getFrameworkCommands() and calls
  api.registerCommand() for each; handler derives msgType from ctx.from,
  sends file attachments via sendDocument, supports multi-account via
  ctx.accountId
- gateway.ts (inbound): replace raw allowFrom string comparison with
  qqbotPlugin.config.formatAllowFrom() to strip qqbot: prefix and
  uppercase before matching event.senderId
- gateway.ts (pre-dispatch): remove stale auth computation; commandAuthorized
  is true (requireAuth:true commands never reach matchSlashCommand)
- command-auth.test.ts: add regression tests for qqbot: prefix
  normalization in the inbound commandAuthorized computation
- slash-commands.test.ts: update /bot-logs tests to expect null
  (command routed to framework, not in local registry)

* rebase and solve conflict

* fix(qqbot): preserve mixed env setup credentials

---------

Co-authored-by: yuehuali <[email protected]>
Co-authored-by: walli <[email protected]>
Co-authored-by: WideLee <[email protected]>
Co-authored-by: Frank Yang <[email protected]>
@elliott-dandelion-cult
elliott-dandelion-cult deleted the elliott/subagent-continuation branch April 23, 2026 19:14
elliott-dandelion-cult added a commit that referenced this pull request May 1, 2026
…-gap todo

Pin the three observability surfaces (ctx.log.warn, emitAgentEvent,
onAgentEvent) that fire when reconcileSessionStoreCompactionCountAfterSuccess
rejects, and pin the behavior contract that handleCompactionEnd emits
completed=true regardless of reconcile outcome.

Add it.todo documenting the fire-and-forget gap (audit gap #1 from
wave-D bbcf2f3).

Co-Authored-By: Claude Opus 4.6 <[email protected]>
ronan-dandelion-cult pushed a commit that referenced this pull request May 8, 2026
…ore continue_delegate attachments + paired chainState fixes onto v2026.5.7

Lands the v5.7 canonical-line content for the continuation feature:

Squashed from PR #604 (HEAD 8fe4f71) — 7 commits cohort-byte-walked:
- ed117ab  feat(continuation): context-pressure + targeted returns squashed onto v2026.5.7 base (#598)
- 2023fcf  fix(continuation): clean rebased delegate config (lint cleanup)
- 81fb7d1  fix(matrix): prefer crypto backup status first (rebase-fix; defers HTTP roundtrip when crypto present)
- 7c229fa  fix(channels): honor declared credential env (introduces listBundledConfiguredChannelEnvSignalIds)
- 387753f  test(browser): avoid DNS in target swap fixture (loopback instead of DNS-dependent fixture)
- ea7661d  feat: restore continue_delegate attachments (WO-605: restores capability cohort flagged as regression at issue #605)
- 8fe4f71  fix(continuation): paired chainState persistence fixes (#606 P1 fixes; agent-runner.ts:2913 + delegate-dispatch.ts:103)

Closes #602 (workorder for v5.7 rebase)
Closes #605 (regression-restore continue_delegate attachments)
Refs #603 (compaction-on-opus-4.7 IDE-auth diagnostic; separate fix lane)

Cohort byte-walk + cosign-state at admin-merge:
- 🩸 cael multi-pass byte-walks (WO-605 substrate + 4 rebase-fix commits with 1 conditional on matrix sdk + ed117ab squash)
- 🌫 silas area-walks (continuation primitives + agent-runner.ts deep walk + WO-605 design+code-flow+zod validation; second-walker partial-cosign on matrix)
- 🌊 ronan full byte-walk (4 rebase-fixes + ed117ab squash + ea7661d WO-605)
- 🌻 elliott seat-state-prevents-cosign per substrate-condition: DNS resolver-path failure on elliott-host (Pi-hole at 10.0.0.10 timing out, systemd-resolved blocking before fallback to 10.0.0.1; gateway can't reach Discord/GitHub/OpenAI). Cure-home per cohort canon: openclaw-dns-client lane (no unilateral host changes per banked rule). Post-DNS-cure cosign on canonical-tip welcome.

3-of-4 cohort cosigns substantively converged + 1-deferred-pending-DNS-fix.

Open follow-up substrate (post-merge):
- Matrix sdk.ts:81f conditional cosign — Cael + Silas flagged 2 risk-surfaces wanting deeper Matrix-SDK expertise (resolveRoomKeyBackupTrustState null vs populated semantics; ??= falsy-but-not-null edge case). 🌻 has Intel/Arc seat-ownership; revisit when seat-state allows.
- Hedge-vs-main-path race finding (Ronan 1502335023 + Silas 1502340658 cohort byte-walk): theoretically-real cross-flow async race in hedge-persist; lower-frequency than P1 #1; PR-shipping fine; file as follow-on issue under 'hedge-persist race' for future-cohort.

Driven per figs's drive-forward + tighten-cron-to-5m directive at msg 1502329589 + 1502318362.
karmafeast pushed a commit that referenced this pull request May 17, 2026
…pletion

Covers the four documented branches of the post-queued-compaction dispatcher
plus the inner sessionEntry-missing guard:

  - branch 1: compactionResult.ok === false       → early no-op
  - branch 2: compactionResult.compacted === false → early no-op
  - branch 3: sessionKey / activeSessionStore missing → logs
      `session-store-unavailable`, no-op (two sub-cases)
  - branch 4: happy-path increment → resolve → dispatch → span (verifies
      ordering, all arg-passthrough including compactionTokensAfter,
      newSessionId, newSessionFile, releaseTraceparent, and that the
      REFRESHED sessionEntry is used for dispatch)
  - branch 4b: sessionEntry resolves to undefined → logs
      `session-entry-unavailable`, no-op
  - plus two coverage cases for the `?? ` fallbacks: getter-returns-undefined
      and resolveSessionStoreEntry-existing-undefined

The function had zero prior test coverage on df50294 per the spiderweb-gap
audit; this fills the #1 spiderweb-T1 slot.
karmafeast added a commit that referenced this pull request May 17, 2026
Addresses the three clawsweeper P2 findings on cure-(11) head 52262ff
("needs changes before merge" verdict at 2026-05-17T19:52Z):

1. Mantis desktop-proof command filter restored (P2 #1)
   - .github/workflows/mantis-telegram-desktop-proof.yml: byte-identical
     to upstream/main; restores `should_run` semantic gate, downstream
     job `if:` conditions, and `requestedDesktopProof` phrase-filter.
   - test/scripts/mantis-telegram-desktop-proof-workflow.test.ts:
     byte-identical to upstream/main; restores assertions that match
     the upstream-aligned workflow shape.

2. Mantis live-lane desktop-proof exclusion restored (P2 #2)
   - .github/workflows/mantis-telegram-live.yml: byte-identical to
     upstream/main; restores `requestedDesktopProof` compound check
     and `!requestedDesktopProof` exclusion in the `requested` predicate.

3. continue_work delay-reporting alignment (P2 #3)
   - src/agents/tools/continue-work-tool.ts: tool now reports the
     resolved post-clamp delay (via clampDelayMs + runtime config)
     instead of the raw input delaySeconds. When clamping changes
     the value, a `note` field surfaces the requested-vs-clamped
     delta to the model.
   - src/agents/tools/continue-work-tool.test.ts: assertions updated
     for resolved-delay behavior, vi.mock for config resolution.

Orphan-test alignment for cure-(11) presentation migration:

   - src/agents/pi-embedded-subscribe.handlers.tools.test.ts:
     `expectInteractiveApprovalButtons` helper updated to expect
     `["presentation"]` instead of `["interactive"]`. cure-(11) migrated
     `buildExecApprovalPendingReplyPayload` return field from
     `interactive: buildApprovalInteractiveReply(...)` to
     `presentation: buildApprovalPresentation(...)` (+ updated
     `exec-approval-reply.test.ts` to match) but missed updating
     this test helper. Completing the migration here. Reverting was
     not viable because telegram/slack approval-renderer extensions
     consume the new MessagePresentation surface.

Verification gates (focused, pre-cohort-byte-walk):
- pnpm tsgo:core ✓
- pnpm tsgo:test ✓
- vitest src/agents/tools/continue-work-tool.test.ts: 20/20 ✓
- vitest src/auto-reply/reply/agent-runner.continuation-work-span.test.ts: 3/3 ✓
- vitest test/scripts/mantis-telegram-desktop-proof-workflow.test.ts: PASS ✓
- vitest src/agents/pi-embedded-subscribe.handlers.tools.test.ts: 68/68 ✓
- Mantis files diff -q against upstream/main: byte-identical ✓
- git diff --check: clean ✓

Full vitest (33GB heap) running pre-push verification.

This is a CANDIDATE commit. Will be squashed before force-push to
PR head per cure-N runbook canon (single-squash + Co-Authored-By
trailers + proofs-SHA == push-SHA invariant).

Co-authored-by: Elliott 🌻 <[email protected]>
Co-authored-by: Silas 🌫️ <[email protected]>
Co-authored-by: Cael 🩸 <[email protected]>
Co-authored-by: Ronan 🌊 <[email protected]>
Co-authored-by: frond-scribe 🌿 <[email protected]>
karmafeast added a commit that referenced this pull request May 17, 2026
Addresses the three clawsweeper P2 findings on cure-(11) head 52262ff
("needs changes before merge" verdict at 2026-05-17T19:52Z):

1. Mantis desktop-proof command filter restored (P2 #1)
   - .github/workflows/mantis-telegram-desktop-proof.yml: byte-identical
     to upstream/main; restores `should_run` semantic gate, downstream
     job `if:` conditions, and `requestedDesktopProof` phrase-filter.
   - test/scripts/mantis-telegram-desktop-proof-workflow.test.ts:
     byte-identical to upstream/main; restores assertions that match
     the upstream-aligned workflow shape.

2. Mantis live-lane desktop-proof exclusion restored (P2 #2)
   - .github/workflows/mantis-telegram-live.yml: byte-identical to
     upstream/main; restores `requestedDesktopProof` compound check
     and `!requestedDesktopProof` exclusion in the `requested` predicate.

3. continue_work delay-reporting alignment (P2 #3)
   - src/agents/tools/continue-work-tool.ts: tool now reports the
     resolved post-clamp delay (via clampDelayMs + runtime config)
     instead of the raw input delaySeconds. When clamping changes
     the value, a `note` field surfaces the requested-vs-clamped
     delta to the model.
   - src/agents/tools/continue-work-tool.test.ts: assertions updated
     for resolved-delay behavior, vi.mock for config resolution.

Orphan-test alignment for cure-(11) presentation migration:

   - src/agents/pi-embedded-subscribe.handlers.tools.test.ts:
     `expectInteractiveApprovalButtons` helper updated to expect
     `["presentation"]` instead of `["interactive"]`. cure-(11) migrated
     `buildExecApprovalPendingReplyPayload` return field from
     `interactive: buildApprovalInteractiveReply(...)` to
     `presentation: buildApprovalPresentation(...)` (+ updated
     `exec-approval-reply.test.ts` to match) but missed updating
     this test helper. Completing the migration here. Reverting was
     not viable because telegram/slack approval-renderer extensions
     consume the new MessagePresentation surface.

Verification gates (focused, pre-cohort-byte-walk):
- pnpm tsgo:core ✓
- pnpm tsgo:test ✓
- vitest src/agents/tools/continue-work-tool.test.ts: 20/20 ✓
- vitest src/auto-reply/reply/agent-runner.continuation-work-span.test.ts: 3/3 ✓
- vitest test/scripts/mantis-telegram-desktop-proof-workflow.test.ts: PASS ✓
- vitest src/agents/pi-embedded-subscribe.handlers.tools.test.ts: 68/68 ✓
- Mantis files diff -q against upstream/main: byte-identical ✓
- git diff --check: clean ✓

Full vitest (33GB heap) running pre-push verification.

This is a CANDIDATE commit. Will be squashed before force-push to
PR head per cure-N runbook canon (single-squash + Co-Authored-By
trailers + proofs-SHA == push-SHA invariant).

Co-authored-by: Elliott 🌻 <[email protected]>
Co-authored-by: Silas 🌫️ <[email protected]>
Co-authored-by: Cael 🩸 <[email protected]>
Co-authored-by: Ronan 🌊 <[email protected]>
Co-authored-by: frond-scribe 🌿 <[email protected]>
karmafeast pushed a commit that referenced this pull request May 28, 2026
…penclaw#76262)

* fix(msteams): rebase SDK migration onto current main

Reapply the msteams SDK migration (originally on feat/msteams-sdk-migration)
on top of upstream/main, resolving conflicts with parallel msteams work that
landed upstream during our session.

What got applied vs decisions made:

CLEANLY APPLIED (3-way patch):
- monitor.ts, monitor-handler.ts, polls.ts, reply-stream-controller.ts/.test.ts,
  reply-dispatcher.ts, attachments/download.ts, monitor.lifecycle.test.ts,
  monitor-handler/message-handler.ts, monitor-handler.types.ts, etc.
- streaming-message.ts + .test.ts deletions

WHOLESALE TAKE FROM ORIGINAL BRANCH (partial 3-way left broken cross-refs):
- sdk.ts, sdk.test.ts, messenger.ts, feedback-reflection.ts,
  send-context.ts, send.test.ts

KEPT UPSTREAM (deferred for separate cleanup):
- extensions/msteams/package.json (still has jsonwebtoken/jwks-rsa per
  Peter's b3bc60a incremental approach)
- src/plugins/contracts/package-manifest.contract.test.ts (consistent with
  package.json)
- pnpm-lock.yaml (avoids lockfile churn; pnpm install --frozen-lockfile clean)

ADAPTED:
- Dockerfile matrix-sdk-crypto check now wraps upstream's new retry-loop in
  the if-matrix-bundled gate

KNOWN TEST FAILURES (need eyes — see PR comment):
- attachments.test.ts: 1 fail (pre-existing — warn meta arg shape changed in
  our migration but test wasn't updated)
- reply-dispatcher.test.ts: 6 fails (pre-existing — tests mock old
  TeamsHttpStream, not updated for our ctx.stream rewrite)
- send.test.ts: 4 fails (NEW from merge — upstream's send.ts changed media
  loading; our mocks need updating or take upstream's send.test.ts wholesale)

UPSTREAM COMMITS POTENTIALLY MISSED (in wholesale-take files):
- 08c4af0 fix(msteams): accept conversation id allowlists
- e1840b8 fix(msteams): bind global audience tokens to app id
- Channels turn-kernel refactor (ffe67e9 / 1ead1b2 / 9a9cd0c) —
  may be partially preserved in cleanly-patched files

Static checks pass: pnpm check:changed is green (typecheck, lint, contract
tests, import cycles, etc.). Manual testing required before merge.

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>

* fix(msteams): preserve thread routing for channel and group-chat replies

- monitor.ts: adaptSdkContext now uses ctx.reply() for channel and groupChat
  conversations (so the SDK threads outbound activities to the inbound's
  replyToId/serviceUrl) and ctx.send() only for personal DMs (where
  reply()'s blockquote-prepend is ugly).
- messenger.ts: sendProactively passes resolvedThreadId on the non-thread
  fallback path so channel @mentions that fall through outbound.ts -> send.ts
  still land in the original thread instead of top-level.

Live-validated: channel @mention -> bot replies in thread, threaded reply
-> bot replies in same thread, no top-level leakage.

* fix(msteams): tag outbound SDK calls with OpenClaw User-Agent

- user-agent.ts: add buildOpenClawUserAgentFragment() that returns just
  'OpenClaw/<version>'. The SDK's Client.clone merges this with its own
  'teams.ts[apps]/<sdk-version>' identifier — passing the full buildUserAgent()
  here would double-print the SDK token.
- sdk.ts: pass the fragment via AppOptions.client.headers['User-Agent'] so
  the Teams backend can identify OpenClaw traffic for usage telemetry.

Final UA looks like 'OpenClaw/<openclaw-version> teams.ts[apps]/<sdk-version>'.

* fix(msteams): handle StreamCancelledError when user presses Stop mid-stream

The new SDK throws StreamCancelledError synchronously from stream.emit/update
when the user pressed Stop in Teams: Teams replies 403 to the next chunk
update, the SDK flips _canceled, and any subsequent emit() throws. The old
custom TeamsHttpStream either swallowed cancel or didn't expose this exception
type, so the migration inherited an SDK behavior the original code didn't have
to handle.

Symptom on 2026-05-05: pressing Stop during a streaming reply caused an
unhandled promise rejection that crashed the Node 24 process. Docker restarted
the gateway about two minutes after each Stop click. Two related bugs surfaced
once the crash was caught: the would-be block fallback re-delivered the full
text as a second message (duplicate after Stop), and the typing-keepalive kept
pulsing in Teams for the rest of the agent run because nothing told it to
stop.

reply-stream-controller.ts:
- Wrap stream.update / stream.emit / stream.close in try/catch that swallows
  StreamCancelledError (matched by .name to dodge tsgo's SDK re-export
  resolution quirk). Latch a wasCanceled flag so subsequent calls
  short-circuit even if stream.canceled is stale.
- preparePayload() returns undefined when the stream was canceled — the
  streamed prefix is already visible to the user, so dropping the payload
  prevents a duplicate block message from overriding the cancel intent.

reply-dispatcher.ts:
- Typing-keepalive gate now also checks streamController.wasCanceled() so
  typing pulses stop firing once Stop is observed. Otherwise the bot keeps
  pulsing for the rest of the (uncancellable) agent run.

reply-stream-controller.test.ts:
- 6 new regression tests cover: cancel-during-emit (the crash scenario),
  cancel-during-update, cancel-during-finalize, non-cancel error propagation,
  post-cancel inactivity, and dropped-payload-on-cancel.

Live-validated: long streaming reply + Stop mid-stream -> stream freezes,
no duplicate message, no zombie typing, container stays healthy.

* fix(msteams): allow Bearer-token retry on Skype CDN attachment downloads

Teams puts inline DM images and clipboard-pasted images on
*.asm.skype.com URLs (e.g. us-api.asm.skype.com/v1/objects/<id>/views/imgo).
The download path in attachments/download.ts already does a plain GET first
and falls back to a Bearer-token retry on 401/403 — but the retry was gated
on the URL being in DEFAULT_MEDIA_AUTH_HOST_ALLOWLIST. asm.skype.com hosts
were in DEFAULT_MEDIA_HOST_ALLOWLIST (download permitted) but not in the
auth-host list, so a 401 plain-GET response skipped the retry and surfaced
as a missing image to the agent.

Add asm.skype.com and ams.skype.com to the auth allowlist so openclaw
attempts the Bearer-token retry consistently, matching how it treats the
other CDN/Bot-Framework hosts already in the list.

Note: this does not unblock all clipboard-pasted DM images — for at least
some tenants asm.skype.com rejects the Bot Framework token (returns 401
even with auth). Routing those URLs through <serviceUrl>/v3/attachments/...
the way openclaw#62219 already handles HTML-wrapped attachments is a separate
follow-up. The +button 'Upload from this device' path works today because
Teams generates an attachment with an HTML wrapper that triggers the
existing BF v3 attachments fallback in monitor-handler/inbound-media.ts.

* fix(msteams): align docker-compose msteams port default with plugin default

The plugin defaults webhook.port to 3978 (the Bot Framework standard used in
Microsoft samples) and listens on whatever the operator sets there. The
docker-compose.yml port mapping was exposing ${OPENCLAW_MSTEAMS_PORT:-3000}:3000
which only works for operators who explicitly set webhook.port to 3000.
Default-config users would have the plugin listening on 3978 inside the
container while compose forwarded 3000, causing connection refused.

Realign to ${OPENCLAW_MSTEAMS_PORT:-3978}:3978 so a default-config docker
compose up Just Works with Teams. Operators wanting a custom port override
both webhook.port in openclaw.json and OPENCLAW_MSTEAMS_PORT env var.

* fix(msteams): post-rebase reconciliation with main

Three follow-ups after rebasing the SDK migration onto current main:

- reply-dispatcher.ts: rename createChannelReplyPipeline to its post-rebase
  identifier createChannelMessageReplyPipeline (the plugin-sdk barrel renamed
  it during the 1454-commit rebase window).
- reply-dispatcher.ts: tighten the typing-keepalive onStartError signature to
  (err: unknown) to satisfy upstream's stricter type checks.
- messenger.ts: drop the unconditional thread suffix on the bottom proactive
  fallback. The previous behavior threaded all top-level proactive sends when
  the stored ref had a threadId, which contradicts replyStyle='top-level'
  semantics (and breaks the new upstream test). Threading on the proactive
  path is preserved where it matters — the onRevoked branch within
  replyStyle==='thread' still passes resolvedThreadId, which is the original
  openclaw#55198 fix path.
- attachments.test.ts: update the warn-call assertion to match the migration's
  inline message format (host=... error=...) — the structured meta object was
  being dropped by the logger formatter pre-migration.

* feat(msteams): port streaming preview/progress features to ctx.stream

While the SDK migration was open, upstream landed preview/progress/draft
streaming features built on the OLD custom TeamsHttpStream class (which the
migration deletes). This commit ports the user-visible parts of those
features onto the new ctx.stream substrate so the migration doesn't lose
ground:

- pickInformativeStatusText: reads custom labels from
  msteams.streaming.progressDraft config via resolveChannelProgressDraftLabel.
  Falls back to the plugin-sdk default rotation. Pre-rebase used a hardcoded
  4-string array.
- streamMode resolution: "partial" (default, per-token streaming),
  "progress" (no tokens; preview card carries informative label that updates
  as tools run), or "block" (no native streaming). Mode is read from
  cfg.channels.msteams.streaming.preview.
- progress-draft gate: createChannelProgressDraftGate gates informative
  updates so the rotating label only starts firing once meaningful work has
  begun (avoids flicker before the first tool call).
- noteProgressWork() / pushProgressLine(): public methods on the controller
  for callers (typing keepalive ticks, tool-event callbacks) to signal work.
  pushProgressLine appends tool names as bullets above the rotating label
  when streaming.previewToolProgress is enabled. Wiring these into actual
  tool events is a separate follow-up.
- preparePayload progress-mode path: when stream is active but no tokens
  streamed (progress mode) and a final text payload arrives, emit the text
  into the stream so the preview card transitions in place to the final
  reply on close().

reply-dispatcher: pass log + msteamsConfig + a stable progressSeed
(${accountId}:${conversation.id}) to createTeamsReplyStreamController so the
informative-label rotation is consistent across reconnects.

What's NOT ported and why:
- Live-edit-via-replaceInformativeWithFinal: the SDK's HttpStream natively
  accumulates emitted text + entities + channelData and flushes ONE final
  activity at close() using the same activity id as the preview. So the
  separate "replace informative with final" call from upstream is
  unnecessary — we get live-finalization for free via the SDK's design.
- pushProgressLine triggers from tool events: needs reply-pipeline-side
  callbacks the new SDK migration didn't surface yet. Follow-up.

Tests: existing 22 reply-stream-controller tests still pass (the new
behaviors are additive).

* feat(msteams): wire pipeline tool events to streaming progress + fix test debt

Two follow-ups from yesterday's stopping point:

1. Wire pipeline events into the stream controller's progress-draft surface.
   reply-dispatcher's replyOptions now exposes onReasoningStream, onToolStart,
   onItemEvent, onPlanUpdate, onApprovalEvent, onCommandOutput callbacks that
   format each event via the channel-streaming helpers and route through
   streamController.pushProgressLine(). Mirrors the discord adapter's wiring.
   Also:
   - resolveChannelStreamingPreviewToolProgress + ...SuppressDefaultTool... so
     the dispatcher exposes suppressDefaultToolProgressMessages on its
     replyOptions when progress mode is on.
   - Switch disableBlockStreaming resolution to the channel-streaming helpers
     (resolveChannelPreviewStreamMode + resolveChannelStreamingBlockEnabled)
     so streaming.mode='block' and streaming.block.enabled=true are honored
     alongside the legacy blockStreaming boolean.

2. Fix the test debt that the rebase exposed:
   - reply-dispatcher.test.ts: drop the streamInstances + TeamsHttpStream
     mock pattern (file deleted by migration); replace with a streamMock
     provided via context.stream that mirrors the SDK's IStreamer shape
     (update/emit/close/canceled). Update assertions on sendInformativeUpdate
     -> stream.update, stream.update -> stream.emit. Drop the
     resumes-typing-between-segments test (no equivalent in the new
     ctx.stream model — the SDK's HttpStream doesn't have a 'between
     segments' notion; close ends the stream).
   - send.test.ts: fix two stale mock targets — loadOutboundMediaFromUrl
     comes from openclaw/plugin-sdk/outbound-media (not /msteams), and
     resolveMarkdownTableMode comes from openclaw/plugin-sdk/markdown-table-runtime
     (not /config-runtime). The previous mock paths were no-ops post-migration.

All 854 msteams tests now pass (was 17 failing in 4 files yesterday).

* fix(msteams): SDK streaming delta + use app.reply for proactive thread sends

Two narrow regressions exposed by the @microsoft/teams.apps migration:

- The SDK's HttpStream.emit appends each chunk to its internal buffer
  (`this.text += activity.text`), but the channel reply pipeline emits
  cumulative text on each chunk. Forwarding cumulative text into an
  appending sink produced "chunk1 + chunk1chunk2 + chunk1chunk2chunk3..."
  duplication for streamed (DM) replies. Track the emitted prefix length
  in the stream controller and only forward the new tail.
- Replace the manual `${convId};messageid=${msgId}` URL construction in
  the proactive thread fallback with `app.reply()`, which builds the
  threaded conversation id via the SDK's own toThreadedConversationId
  helper. Mechanically equivalent today; removes coupling to Teams' URL
  format and tracks any future SDK changes.

Also adds the `reply` method to the structural MSTeamsApp type so the
refactor typechecks without casts.

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>

* chore(msteams): bump @microsoft/teams.api and teams.apps to 2.0.10

2.0.10 adds support for the AAD v1 token issuer that the Bot Framework
JWT validator needs. The minor version bump pulls teams.cards / common /
graph along to 2.0.10 too.

Add `@microsoft/teams.*` to `minimumReleaseAgeExclude` in
pnpm-workspace.yaml because 2.0.10 was published <48h ago and the default
`minimumReleaseAge: 2880` (~2 days) would otherwise reject it.

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>

* revert(msteams): remove asm.skype.com auth-host allowlist additions

These hosts were added in dfc169d for inline DM image auth-retry, but
the commit's own footnote acknowledges it doesn't actually unblock
clipboard-pasted images (asm.skype.com rejects Bot Framework tokens in
at least some tenants). The change is unrelated to the SDK migration and
the user-visible bug it claimed to fix isn't fixed; lifting it out keeps
this PR focused on the migration. Will land as a separate PR if the
auth-allowlist consistency improvement is wanted on its own.

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>

* refactor(msteams): typed ExpressAdapter helper, drop unknown-cast pyramid

The monitor's SDK bootstrap had an awkward chain:

  httpServerAdapter: new (
    (await import("@microsoft/teams.apps")) as unknown as {
      ExpressAdapter: new (app: unknown) => unknown;
    }
  ).ExpressAdapter(expressApp) as never,

Three casts (`unknown`, structural shape literal, `never`) were a
defensive workaround from when the SDK's hashed d.ts files tripped up
tsgo. With the SDK's exports now resolving cleanly, the same import can
be done with full types.

- Extend the lazy `loadSdkModules()` cache to include `ExpressAdapter`
  alongside `App` so the dynamic import is shared.
- Add `createMSTeamsExpressAdapter(serverOrApp)` helper in `sdk.ts` that
  encapsulates the lazy import and returns a properly-typed adapter
  instance.
- Replace `httpServerAdapter`'s structural shape on `CreateMSTeamsAppOptions`
  with the SDK's own `IHttpServerAdapter` interface (re-exported from
  `@microsoft/teams.apps`).

The call site in `monitor.ts` becomes a single typed call with no `any`,
no `unknown`, no `as never`. The lazy-load behavior is preserved: nothing
imports `@microsoft/teams.apps` at module load time.

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>

* fix(msteams): unbreak tsgo:extensions on the ExpressAdapter helper

CI's check-prod-types failed because the previous commit's typed helper
used `typeof import("@microsoft/teams.apps").ExpressAdapter`, which
tsc/tsgo's NodeNext resolution can't follow through the SDK's chained
`export *` barrel:

    @microsoft/teams.apps/dist/index.d.ts:
        export * from "./http";          // folder with index.d.ts
        export * from "./app";           // single .d.ts file

The folder re-export drops `ExpressAdapter` and `IHttpServerAdapter` from
the namespace shape under `tsconfig.extensions.json` (passes under the
per-extension `tsconfig.json` because of inherited `paths`). Same root
cause as why we already model `MSTeamsApp` structurally (line 47 comment).

Switch the ExpressAdapter side to the same structural-shape pattern:
- Define `MSTeamsHttpServerAdapter` and `MSTeamsExpressAdapterCtor` locally.
- Cast `m.ExpressAdapter` once inside `loadSdkModules` (the runtime export
  is fine; only the type surface is hidden).
- `httpServerAdapter` on `CreateMSTeamsAppOptions` and the return type of
  `createMSTeamsExpressAdapter` use the local structural type.

Net result: the call site in `monitor.ts` stays the cast-free single line
the previous commit landed; the one remaining cast is confined to the
SDK-loading helper with an explanatory comment.

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>

* chore(msteams): drop unused jsonwebtoken/jwks-rsa deps

The SDK migration removed all `import "jsonwebtoken"` / `import "jwks-rsa"`
from source code (the SDK does JWT validation internally now), but the
package.json entries and the matching `package-manifest.contract.test.ts`
expectation were left orphaned. Drop both:

- `extensions/msteams/package.json`: remove `jsonwebtoken` (^9), `jwks-rsa`
  (^4) from `dependencies` and `@types/jsonwebtoken` from `devDependencies`.
- `src/plugins/contracts/package-manifest.contract.test.ts`: remove the
  two entries from msteams's `pluginLocalRuntimeDeps` expectation.
- `monitor.lifecycle.test.ts`: extend the `./sdk.js` mock with the
  `createMSTeamsExpressAdapter` export added in the typed-helper cleanup,
  so the lifecycle suite still mounts after the deps drop.

Lockfile regenerates accordingly. All msteams tests (865) pass.

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>

* chore(msteams): drop unused @microsoft/teams.api direct dep

CI's deadcode:dependencies (knip) flagged @microsoft/teams.api as
unused in extensions/msteams. The plugin source uses structural type
aliases (MSTeamsActivityParams, MSTeamsActivityLike, etc.) to dodge
tsgo resolution bugs with teams.api's hashed d.ts files, so it never
imports teams.api directly. The package is brought in transitively
via @microsoft/teams.apps; the only other reference is
probe.test.ts's vi.mock("@microsoft/teams.api"), which works on the
import-path string and doesn't require a direct dep declaration.

Lockfile regenerates accordingly. tsgo:extensions, knip, and all
865 msteams tests pass.

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>

* fix(msteams): clear three CI gate failures (lint, contract, deprecated config API)

Three CI checks flagged on the latest run; all three are msteams-local
and unrelated to one another:

- **check-lint** / **check-additional-extension-bundled**:
  `oxlint` flagged a redundant `as string[]` assertion in
  `reply-dispatcher.ts:431`. The preceding `every((s: unknown) => typeof
  s === "string")` already narrows the array type, so the cast does
  nothing. Drop it.

- **checks-fast-contracts-plugins-c**: the
  `package-manifest.contract.test.ts` `pluginLocalRuntimeDeps` for
  msteams still expected `@microsoft/teams.api`, but the deadcode
  cleanup commit (8f4050f) dropped it from
  `extensions/msteams/package.json`. Remove it from the contract test
  too — `teams.api` is only present transitively via `teams.apps`,
  which is the reason knip flagged it.

- **check-additional-runtime-topology-architecture**: the deprecated
  internal config API guard caught `messenger.ts:223` calling
  `getMSTeamsRuntime().config.loadConfig()`. Switch to
  `config.current()` to match the pattern used by phone-control,
  synology-chat, and matrix.

Pre-existing failures on this run that are NOT msteams-related and not
caused by this PR: `check-test-types` (errors in
`src/agents/openai-transport-stream.test.ts` and
`pi-embedded-runner/openai-stream-wrappers.test.ts`) and `macos-swift`
(`hoistAwait` in `MacNodeRuntime.swift`). Leaving those for upstream.

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>

* fix(msteams): cast config.current() return to OpenClawConfig

The previous commit switched `messenger.ts:223` from the deprecated
`config.loadConfig()` to `config.current()` to satisfy the architecture
guard, but `config.current()` returns a deeply-readonly type that's not
assignable to the `Partial<OpenClawConfig>` parameter
`resolveMarkdownTableMode` expects (a mutable type from the SDK
contract). Phone-control, synology-chat, and matrix all cast at this
seam — adopt the same pattern.

Verified locally: tsgo:core, tsgo:extensions, check:architecture, and
test:extensions:package-boundary:compile all pass.

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>

* fix(msteams): address PR review — pre-auth body limit, allowlist log level, /api/messages forwarder, narrow release-age exclude

Four narrow fixes from the PR review (BradGroux + clawsweeper bot +
galiniliev's plan), each its own concern:

- **pre-auth-body-limit** (monitor.ts) — install
  `express.json({ limit: DEFAULT_WEBHOOK_MAX_BODY_BYTES })` before the
  bearer-presence gate and SDK route. Express memoizes the parsed body
  on the request, so the SDK's later `json()` becomes a no-op and our
  limit applies before any handler parses bodies. Closes the gap where
  a `Bearer garbage`-shaped attacker could force unbounded JSON parsing
  before token validation.

- **allowlist-error-logging** (monitor.ts) — restore main's `runtime.error`
  level for the `msteams resolve failed` catch (was downgraded to
  `runtime.log` mid-merge). Graph allowlist resolution failures are
  security-relevant; they need to surface to operators.

- **legacy-messages-route** (monitor.ts) — when `webhook.path` is set
  to a custom value, also accept POSTs on the legacy `/api/messages`
  path with a one-time deprecation warning, then re-enter the Express
  middleware chain on the configured path. Keeps existing Azure Bot
  registrations working through the transition. Cast-free
  (`expressApp(req, res, next)` works because `Application extends
  IRouter extends RequestHandler`).

- **release-age-scope** (pnpm-workspace.yaml) — narrow
  `@microsoft/teams.*` glob to the single direct dep
  `@microsoft/teams.apps`. Future scoped packages no longer get a
  freshness-guard pass.

Tests + checks: msteams suite (867), tsgo:core, tsgo:extensions,
tsgo:test, lint:extensions, check:architecture, knip --dependencies,
package-manifest contract, all green.

Still pending from the review (separate commits):
- auth-coverage-tests (Brad #1 + comment) — tests proving the SDK accepts
  `aud=<bot app id>` and rejects `aud=api.botframework.com`.
- invoke-response-handling (Brad #2, codex P2) — file-consent invoke ack
  must return through the SDK invoke handler, not `ctx.sendActivity`.
- stream-failure-fallback (codex P2, galin F5) — `streamFailed` latch so
  partial streams fall back to block delivery on non-cancel errors.
- serviceurl-routing (Brad #4, codex P2) — proposed rebuttal pending
  empirical confirmation that `smba.trafficmanager.net/teams` routes to
  non-default-region conversations.

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>

* test(msteams): lock SDK auth contract — aud + v1/v2 issuer coverage

Adds extensions/msteams/src/auth-coverage.test.ts driving ServiceTokenValidator
and createEntraTokenValidator directly with jose-minted RS256 tokens against an
in-memory JWKS (via JwksClient.prototype patch). Locks in the three contract
cases @BradGroux flagged on openclaw#76262: aud=<bot app id> accepted, aud=api.botframework.com
rejected even when appid/azp match, and v1/v2 issuers accepted for allowed tenant
(disallowed tenant rejected).

Drops a stale ambient module declaration in src/types/microsoft-teams-sdk.d.ts
that was shadowing the SDK's real jwt-validator types with a long-renamed
createServiceTokenValidator surface.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* fix(msteams): route file-consent invokes through typed app.on, drop broken invokeResponse send

Brad #2 / codex #4 on PR openclaw#76262 — `ctx.sendActivity({ type: "invokeResponse", ... })`
no longer reaches Teams as an HTTP InvokeResponse on the new SDK; it becomes
an outbound Bot Framework activity instead. Move file-consent accept/decline
to typed `app.on("file.consent.accept|decline", ...)` handlers. The SDK's
typed-route layer wraps a void return into `{ status: 200 }`
(`app.process.js:130`), so the manual ack disappears.

While in here, type `MSTeamsApp.on` properly. Borrowing the SDK's `App.on`
directly fails because that function carries a `this: App<TPlugin>`
constraint our structural alias can't satisfy, so we model an equivalent
generic over `IRoutes` with route-specific overloads (`card.action`,
`file.consent.*`, `activity`). The overloads work around a tsgo bug — the
`@microsoft/teams.api` `Activity` discriminated union collapses to `any`,
turning `ActivityRoutes` into a `[string]: RouteHandler<X, void>` index
signature that swallows every typed `Out` not already void-compatible
(card.action returns `AdaptiveCardActionResponse`; the others happen to
include `void`). Real tsc resolves cleanly. Linked upstream:
microsoft/typescript-go#1057.

Other cleanups:
- Cast-free call sites for `adaptSdkContext` (now returns
  `MSTeamsTurnContext` instead of `unknown`).
- card.action error responses include `innerHttpError` per the SDK's
  `HttpError` shape requirement.
- Activity catch-all also skips `fileConsent/invoke` now that it's
  typed-routed (parallel to the existing `adaptiveCard/action` skip).

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* fix(msteams): route SSO sign-in invokes through typed app.on, drop broken invokeResponse send

Brad #2 / codex #4 on PR openclaw#76262, SSO half. Continue the typed-route migration:
`signin/tokenExchange` and `signin/verifyState` now register via
`app.on("signin.token-exchange" | "signin.verify-state", ...)`. Per the
SDK's router, registering a user route with the same name as a system
route removes the system default — so the SDK's built-in handlers (which
would call `api.users.token.exchange` themselves and emit a `signin` event
nobody currently subscribes to) are silenced, and only ours runs. The SDK
wraps a void return into the HTTP 200 InvokeResponse, so the legacy
`ctx.sendActivity({ type: "invokeResponse", ... })` ack — broken on the new
SDK because it becomes an outbound BF activity instead of the HTTP
response — is gone.

The handler body is extracted from the activity-catch-all dispatch in
`monitor-handler.ts` to a new `signin-invoke.ts`, parallel to
`file-consent-invoke.ts`. `isSigninInvokeAuthorized` is now exported from
`monitor-handler.ts` so the new handler can reuse it. The activity
catch-all skips the SSO invoke names alongside the existing skips for
`adaptiveCard/action` and `fileConsent/invoke`.

`MSTeamsAppOn` overloads now cover the two SSO routes with their typed
ctx (`ISignInTokenExchangeInvokeActivity` / `ISignInVerifyStateInvokeActivity`).
Tests in `monitor-handler.sso.test.ts` were rewritten to call the
extracted handler directly — the `registered.run(ctx)` shape no longer
covers SSO, and the `expect(ctx.sendActivity).toHaveBeenCalledWith({ type:
"invokeResponse" })` assertions were dropped to match the new contract
(the SDK ack happens via the typed-route return value).

Note on overlap with openclaw#77784 (Stefan Stüben, Microsoft): that PR is doing
a much bigger SSO rework (sign-in card / sign-in-link / six-digit-code
fallbacks plus a `ctx.auth` plumbed to plugin tools). This change is
the small migration-correctness fix and is structured so openclaw#77784's SSO
body changes drop into the typed-route registrations cleanly on rebase.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* fix(msteams): route message-submit (feedback) invokes through typed app.on

Last invoke off the activity catch-all dispatch. `message/submitAction`
(thumbs up/down on AI-generated messages) now registers via
`app.on("message.submit", ...)`. Same shape as file-consent and SSO:
handler body extracted to a new `feedback-invoke.ts`, the SDK wraps a
void return into the HTTP 200 InvokeResponse, the broken
`ctx.sendActivity({ type: "invokeResponse", ... })` line is gone, and
the activity catch-all skips this invoke name alongside the others.

`isFeedbackInvokeAuthorized` is exported from `monitor-handler.ts` so
`feedback-invoke.ts` can reuse it. Tests in
`monitor-handler.feedback-authz.test.ts` were rewritten to call the
extracted handler directly — the old `handler.run(ctx)` shape no longer
intercepts feedback, and `originalRun` was removed because the typed
route is the dispatch point now.

`MSTeamsAppOn` overload added with the typed
`IMessageSubmitActionInvokeActivity` ctx, slotted between the SSO
overloads and the `activity` catch-all so `activity` stays last.

This leaves only `message`, `conversationUpdate`, and `messageReaction`
flowing through `app.on("activity", ...)` → `handler.run`. Promoting
those is the path to deleting the catch-all entirely.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* fix(msteams): fall back to block delivery when partial-mode stream fails mid-flight

codex #5 / Galin F5 on PR openclaw#76262. `reply-stream-controller.ts` previously
re-threw any non-cancel error from `stream.emit` during partial streaming
and from `stream.emit`/`stream.close` during finalize. Combined with
`preparePayload` suppressing block delivery once `tokensEmitted` was
true, that meant a network blip or API error mid-stream produced a
truncated reply with no recovery — the user saw the prefix that made it
through and nothing else.

Add a `streamFailed` latch parallel to `canceledLocally` / `tokensEmitted`:

- `onPartialReply`: catch non-cancel errors, set `streamFailed = true`,
  log a warn, don't propagate (the pipeline must keep running so
  `preparePayload` can decide).
- `preparePayload`: when `tokensEmitted && streamFailed`, fall through to
  block delivery instead of suppressing. The user may see a duplicate
  (streamed prefix + full block reply); intentional — matches the
  pre-migration `TeamsHttpStream.hasContent` recovery and is better than
  truncated-only.
- `finalize`: same latch + warn on non-cancel close failure, swallow
  rather than throw. The streamed content already reached the user; the
  closing activity (AI-Generated marker, feedback channelData) is the
  only loss, not worth blowing up the dispatcher.
- `isStreamActive` returns false once the stream has failed.

New tests cover crash-mid-stream after tokens were emitted (assert block
delivery payload is returned), happy-path no-duplicate behavior (assert
`preparePayload` still suppresses when nothing failed), and finalize
close-failure (assert no throw). The pre-existing "re-throws non-cancel"
test was inverted to assert non-throwing latch behavior.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* fix(msteams): declare @microsoft/teams.api as a runtime dependency

Type-only `import("@microsoft/teams.api/dist/...").TypeName` references
in `sdk.ts` (added when typed `MSTeamsApp.on` overloads were introduced)
are picked up by the `extension-runtime-dependencies` contract test as
genuine runtime imports. Declaring `@microsoft/teams.api` as a direct
dep makes the contract pass; the package was already coming in
transitively via `@microsoft/teams.apps`.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* fix(msteams): keep SSO on SDK signin routes

* test(msteams): avoid redundant signin handler assertion

* docs(msteams): clarify Teams cloud support

* fix(msteams): use current SDK string helper

* fix(msteams): gate SDK invoke side effects

* test(msteams): avoid implicit any in lifecycle tests

* fix(msteams): preserve SDK user agent and matrix check

* fix(msteams): expose SDK common dependency

* fix(msteams): use SDK user agent merge

* fix(msteams): fall back when stream close no-ops

* chore(msteams): drop unrelated merge artifacts

* chore(msteams): restore unrelated main files

* chore(msteams): restore unrelated main files

* chore(msteams): restore unrelated main files

* test(msteams): type stream close mock result

* fix(msteams): configure Teams cloud service URL

* chore(msteams): refresh shrinkwrap

* chore(deps): refresh shrinkwrap locks

* chore(ci): rerun guards after main sync

* chore(deps): refresh shrinkwrap for node 24

* chore(config): refresh docs baseline

* fix(msteams): preserve Teams SDK proactive references

* fix(msteams): harden SDK proactive sends

* fix(msteams): align service url contract

* test: fix bonjour beacon type narrowing

* fix(msteams): ignore ambient service url

* fix(msteams): fall through submit invokes

* test: align shrinkwrap override policy with Teams SDK deps

* fix(msteams): ack invoke routes promptly

* fix(msteams): support china cloud boundaries

* test: sync PR with current CI gates

* test: isolate channel setup registry metadata

---------

Co-authored-by: Claude Sonnet 4.6 <[email protected]>
Co-authored-by: Peter Steinberger <[email protected]>
elliott-dandelion-cult added a commit that referenced this pull request May 31, 2026
Restores totalTokens/contextTokens/contextBudgetStatus field-undefined
assertions on session-reset that were dropped during re-derive cure cycle.

Surgical block-restore from upstream e76df69 (lines 766-832):
- Seeded session entry with totalTokens=64_000 + totalTokensFresh=false +
  contextTokens=128_000 + full contextBudgetStatus shape (schemaVersion=1
  through unwindowedMessageCount=8)
- Added 3 post-reset field-undefined assertions on result.sessionEntry
  (totalTokens / contextTokens / contextBudgetStatus all undefined)
- Augmented store type-narrowing record + added 3 post-reset
  field-undefined assertions on store[sessionKey] for the same fields

Behavioral guarantee: /new and /reset clear stale context-budget telemetry
from the prior session so it doesn't leak into the new one. Same shape
as skillsSnapshot clearing (already tested).

Verified:
- pnpm vitest run src/auto-reply/reply/session.test.ts → 96/96 pass
- No type changes; only test-augmentation
- Restored hunk #1 only (lines 763-836); deliberately did NOT restore
  hunk #2 at lines 2287-2331 (cure-branch refactored to expectEntryFields
  helper which tests same things via different shape — keeping cure-branch
  shape per cohort cosign on continuation-feature test architecture)

Closes silas middle-10 (b)-RESTORE pair (webchat already landed via cael
b3030a1; this is the session.test.ts companion).

Cohort cosign chain:
- silas 1510729948 (middle-10 walk verdict)
- elliott 1510741775 (byte-cosign on verdict)
- elliott standing-offer to fire: 1510775926
- cael driver-call (option ii fold)/byte-cosign welcome on land

Refs: figs 1510750729 (RUN GATES RUNBOOK ON STABLE CANDIDATE)
Refs: figs 1510755488 (interim greenlight A on prince-deploy + validate)

Co-authored-by: Cael🩸 <[email protected]>
Co-authored-by: Silas🌫 <[email protected]>
cael-dandelion-cult added a commit that referenced this pull request Jun 1, 2026
Restores totalTokens/contextTokens/contextBudgetStatus field-undefined
assertions on session-reset that were dropped during re-derive cure cycle.

Surgical block-restore from upstream e76df69 (lines 766-832):
- Seeded session entry with totalTokens=64_000 + totalTokensFresh=false +
  contextTokens=128_000 + full contextBudgetStatus shape (schemaVersion=1
  through unwindowedMessageCount=8)
- Added 3 post-reset field-undefined assertions on result.sessionEntry
  (totalTokens / contextTokens / contextBudgetStatus all undefined)
- Augmented store type-narrowing record + added 3 post-reset
  field-undefined assertions on store[sessionKey] for the same fields

Behavioral guarantee: /new and /reset clear stale context-budget telemetry
from the prior session so it doesn't leak into the new one. Same shape
as skillsSnapshot clearing (already tested).

Verified:
- pnpm vitest run src/auto-reply/reply/session.test.ts → 96/96 pass
- No type changes; only test-augmentation
- Restored hunk #1 only (lines 763-836); deliberately did NOT restore
  hunk #2 at lines 2287-2331 (cure-branch refactored to expectEntryFields
  helper which tests same things via different shape — keeping cure-branch
  shape per cohort cosign on continuation-feature test architecture)

Closes silas middle-10 (b)-RESTORE pair (webchat already landed via cael
b3030a1; this is the session.test.ts companion).

Cohort cosign chain:
- silas 1510729948 (middle-10 walk verdict)
- elliott 1510741775 (byte-cosign on verdict)
- elliott standing-offer to fire: 1510775926
- cael driver-call (option ii fold)/byte-cosign welcome on land

Refs: figs 1510750729 (RUN GATES RUNBOOK ON STABLE CANDIDATE)
Refs: figs 1510755488 (interim greenlight A on prince-deploy + validate)

Co-authored-by: Cael🩸 <[email protected]>
Co-authored-by: Silas🌫 <[email protected]>
karmafeast pushed a commit that referenced this pull request Jul 2, 2026
…ixes

- post-compaction-durable-handoff.test.ts: claim->running, finalize-after-handoff,
  and startup recovery reset (#1)
- work-dispatch.test.ts: hot-disabled gate (#2), traceparent re-entry stays
  internal (#5), failed delivered-mark does not replay (#7)
- subagent-announce.continuation-drain.test.ts: durable delayed bracket delegate
  (#3), child-run token fold into drain cost basis (#8)
- agent-runner.finally-drain-hardening.test.ts: finally no longer claims queued
  delegates (#4)
- session-cost-usage.discoverAllSessions.test.ts: max(checkpoint, primary) mtime
  preserved regardless of scan order (#6)
- continue-delegate-tool.test.ts: per-turn admission reset at turn boundary (#9)

Updated post-compaction-release / mid-run-survival / post-compaction dispatch
test mocks for the new finalizeStagedPostCompactionDelegates export. tsgo core +
core-test + oxlint + oxfmt clean; all touched test files green.

Co-authored-by: Copilot <[email protected]>
karmafeast pushed a commit that referenced this pull request Jul 2, 2026
Autoreview (Codex) caught a P2: the post-compaction persist-failure path
finalized the claimed TaskFlow rows while the only fallback was the volatile
in-memory preserve list — a crash before the finally re-stage would drop the
delegate (the exact loss class #1 fixes).

- agent-runner: on persist failure, re-stage delegates to the durable TaskFlow
  queue BEFORE finalizing the claimed rows (no volatile-only window).
- post-compaction-delegate-dispatch: finalize only when the durable handoff
  fully succeeded (preserve list drained); otherwise leave rows `running` for
  startup recovery.

Full-suite regressions from the earlier commits, fixed:
- volatile-map-allowlist: register the new per-turn admission Map with a
  volatile/restart justification.
- continue-delegate-tool.crosssession-gate: reset the shared per-turn admission
  budget between cases.
- subagent-announce.continuation-parity-gate: the delayed bracket delegate now
  enqueues durably instead of firing a volatile timer; assert the enqueue and
  add enqueuePendingDelegate to the module mock.

Added a re-stage-before-finalize durability test. tsgo core + core-test, oxlint,
oxfmt clean; agents-core / auto-reply-reply / unit-fast shards fully green in
isolation (earlier mcp.example.com failures were network flakiness under the
parallel full-suite load).

Co-authored-by: Copilot <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants