typeclaw 0.34.0 → 0.35.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (36) hide show
  1. package/package.json +3 -1
  2. package/src/agent/plugin-tools.ts +53 -5
  3. package/src/agent/provider-error.ts +10 -0
  4. package/src/agent/session-origin.ts +26 -0
  5. package/src/agent/tools/channel-disengage.ts +13 -9
  6. package/src/bundled-plugins/github-cli-auth/gh-command.ts +124 -6
  7. package/src/bundled-plugins/github-cli-auth/git-askpass.ts +65 -0
  8. package/src/bundled-plugins/github-cli-auth/git-command.ts +638 -0
  9. package/src/bundled-plugins/github-cli-auth/index.ts +138 -38
  10. package/src/bundled-plugins/github-cli-auth/token-class.ts +13 -0
  11. package/src/bundled-plugins/security/policies/prompt-injection.ts +33 -2
  12. package/src/channels/adapters/github/inbound.ts +41 -3
  13. package/src/channels/adapters/slack-bot.ts +17 -9
  14. package/src/channels/continuation-willingness.ts +331 -0
  15. package/src/channels/github-review-claim.ts +105 -0
  16. package/src/channels/github-token-bridge.ts +7 -0
  17. package/src/channels/router.ts +103 -24
  18. package/src/cli/channel.ts +102 -11
  19. package/src/cli/qr.ts +130 -0
  20. package/src/config/config.ts +98 -2
  21. package/src/container/start.ts +12 -0
  22. package/src/init/dockerfile.ts +64 -0
  23. package/src/init/line-auth.ts +8 -3
  24. package/src/plugin/context.ts +5 -1
  25. package/src/plugin/manager.ts +2 -0
  26. package/src/plugin/types.ts +1 -0
  27. package/src/run/index.ts +1 -0
  28. package/src/sandbox/build.ts +27 -0
  29. package/src/sandbox/index.ts +6 -0
  30. package/src/sandbox/package-install.ts +23 -0
  31. package/src/sandbox/policy.ts +31 -0
  32. package/src/sandbox/symlinks.ts +34 -0
  33. package/src/sandbox/writable-zones.ts +164 -4
  34. package/src/skills/typeclaw-channel-github/SKILL.md +4 -2
  35. package/src/skills/typeclaw-github-contributing/SKILL.md +124 -0
  36. package/typeclaw.schema.json +32 -1
@@ -3,14 +3,28 @@ import { definePlugin } from '@/plugin'
3
3
 
4
4
  import { createApproveIdempotencyGuard } from './approve-idempotency'
5
5
  import { createGithubEffectiveApprovalResolver, createGithubHeadShaResolver } from './effective-approval'
6
- import { analyzeGhCommand } from './gh-command'
6
+ import { analyzeGhCommand, effectiveGhTokensForAuthenticatedUserEndpoint } from './gh-command'
7
+ import { ensureGitAskPassHelper } from './git-askpass'
8
+ import { analyzeGitCommand, defaultGitResolvers } from './git-command'
7
9
  import { checkGraphqlAuthNudge } from './graphql-auth-nudge'
8
10
  import { commitReviewIfSucceeded, noteReviewCommand } from './review-recorder'
9
- import { classifyGhToken } from './token-class'
11
+ import { classifyGhToken, shouldMintAppToken } from './token-class'
10
12
 
11
13
  export default definePlugin({
12
14
  plugin: async (ctx) => {
13
15
  const resolveTokenForRepo = ctx.github.resolveTokenForRepo
16
+ const hasAppTokenResolver = ctx.github.hasAppTokenResolver
17
+ // `/user` resolves the caller's USER identity. An App installation token is not
18
+ // a user, so GitHub rejects it on a token-class basis (403, or no-token error in
19
+ // the sandbox) no matter how valid the token is. We block-and-guide so the agent
20
+ // does not misread this as "I have no auth" — it does, for repo-scoped calls.
21
+ const appUserEndpointReason =
22
+ '`gh api /user` (and `/user/...`) resolves the calling USER. This agent authenticates ' +
23
+ 'as a GitHub App with a per-repo installation token, which is not a user identity — so ' +
24
+ '`/user` cannot work here, and this failure is NOT a sign that auth is missing (repo-' +
25
+ 'scoped calls still work). It is not a valid auth/login check. For repo data use ' +
26
+ '`gh <cmd> -R owner/repo` or `gh api /repos/owner/repo/...`; for the actor, read the ' +
27
+ 'PR/issue/comment context you were given instead of `gh api /user`.'
14
28
  const resolveToken = async (workspace: string) => {
15
29
  const result = await resolveTokenForRepo(workspace)
16
30
  return result.kind === 'token' ? result.token : null
@@ -19,48 +33,134 @@ export default definePlugin({
19
33
  resolveEffectiveApproval: createGithubEffectiveApprovalResolver({ resolveToken }),
20
34
  resolveHeadSha: createGithubHeadShaResolver({ resolveToken }),
21
35
  })
36
+
37
+ type HookResult = void | { block: true; reason: string }
38
+
39
+ // 'fall-through' means "not a repo-targeting gh command" so the caller can
40
+ // try the git path on the same command (e.g. `git ... # gh` substrings).
41
+ const handleGhCommand = async (params: {
42
+ event: { callId: string; args: Record<string, unknown> }
43
+ command: string
44
+ }): Promise<HookResult | 'fall-through'> => {
45
+ const { event, command } = params
46
+ const review = await noteReviewCommand({ callId: event.callId, command })
47
+ if (review.detected !== null) {
48
+ const block = await verdictGuard.guard({
49
+ callId: event.callId,
50
+ workspace: review.detected.workspace,
51
+ prNumber: review.detected.prNumber,
52
+ verdict: review.detected.verdict,
53
+ })
54
+ if (block !== null) return block
55
+ }
56
+ if (review.dump !== null) return review.dump
57
+
58
+ const decision = analyzeGhCommand(command)
59
+
60
+ // `/user` classifies as pass-through (no repo to mint for), so this block
61
+ // must run BEFORE the pass-through return. Resolve the EFFECTIVE token per
62
+ // `/user` invocation (a command-local `GH_TOKEN=…`/`GITHUB_TOKEN=…` overrides
63
+ // process env, matching gh) and block only when that token is App / none-with-
64
+ // minter — a command-local PAT override carries a user identity, so `/user`
65
+ // works for it and must not be blocked.
66
+ const userEndpointTokens = effectiveGhTokensForAuthenticatedUserEndpoint(command, {
67
+ GH_TOKEN: process.env.GH_TOKEN,
68
+ GITHUB_TOKEN: process.env.GITHUB_TOKEN,
69
+ })
70
+ if (userEndpointTokens.some((token) => shouldMintAppToken(token, hasAppTokenResolver()))) {
71
+ return { block: true, reason: appUserEndpointReason }
72
+ }
73
+
74
+ if (decision.kind === 'pass-through') return 'fall-through'
75
+
76
+ // The `-R` strip is a pure syntax fix (`gh api` rejects `-R`), independent
77
+ // of token minting, so apply it for EVERY token class — including the PAT
78
+ // paths below that return without injecting. Only `inject` decisions carry
79
+ // `rewrittenCommand`, and only after the single-bare/safe-pipeline gate in
80
+ // analyzeGhCommand, so this never rewrites a blocked or unsafe shape.
81
+ if (decision.kind === 'inject' && decision.rewrittenCommand !== undefined) {
82
+ event.args.command = decision.rewrittenCommand
83
+ }
84
+
85
+ const tokenClass = classifyGhToken(process.env.GH_TOKEN)
86
+ // Classic PATs reach every owner; nothing to inject or enforce.
87
+ if (tokenClass === 'cross-owner') return
88
+
89
+ if (decision.kind === 'block') return { block: true, reason: decision.reason }
90
+
91
+ // Fine-grained PATs are single-owner but cannot be re-minted per repo;
92
+ // the seeded GH_TOKEN is the only token we have. Leave it in place so
93
+ // `gh` fails honestly if the named repo is under a different owner.
94
+ if (tokenClass === 'fine-grained-pat') return
95
+
96
+ // No App auth (no App-class GH_TOKEN and no live minter): leave whatever
97
+ // is seeded so `gh` fails honestly rather than us guessing a token.
98
+ if (!shouldMintAppToken(process.env.GH_TOKEN, hasAppTokenResolver())) return
99
+
100
+ const result = await resolveTokenForRepo(decision.repoSlug)
101
+ if (result.kind === 'unavailable') return { block: true, reason: result.reason }
102
+ // Inject via the internal env overlay (delivered to the spawn / bwrap
103
+ // --setenv by the bash wrapper) so the token never enters the command
104
+ // string, where it could leak through logs or later hooks.
105
+ event.args[TYPECLAW_INTERNAL_BASH_ENV] = { GH_TOKEN: result.token }
106
+ return
107
+ }
108
+
109
+ const handleGitCommand = async (params: {
110
+ event: { args: Record<string, unknown> }
111
+ command: string
112
+ agentDir: string
113
+ }): Promise<HookResult> => {
114
+ const { event, command, agentDir } = params
115
+ // Only App auth re-mints per repo. Classic/fine-grained PATs and absent
116
+ // tokens are left untouched, exactly as the gh path treats them. App auth
117
+ // is detected by the live minter too, not just an App-class GH_TOKEN:
118
+ // multi-owner / no-repos App configs never seed GH_TOKEN yet can mint.
119
+ if (!shouldMintAppToken(process.env.GH_TOKEN, hasAppTokenResolver())) return
120
+
121
+ const decision = await analyzeGitCommand(command, { cwd: agentDir, resolvers: defaultGitResolvers })
122
+ if (decision.kind === 'pass-through') return
123
+ if (decision.kind === 'block') return { block: true, reason: decision.reason }
124
+
125
+ const result = await resolveTokenForRepo(decision.repoSlug)
126
+ if (result.kind === 'unavailable') return { block: true, reason: result.reason }
127
+
128
+ const askpass = await ensureGitAskPassHelper()
129
+ const existing = event.args[TYPECLAW_INTERNAL_BASH_ENV]
130
+ const overlay = existing !== null && typeof existing === 'object' ? (existing as Record<string, string>) : {}
131
+ // Token rides in TYPECLAW_GIT_TOKEN (read by the askpass helper), never in
132
+ // argv/config. insteadOf rewrites SSH/scp remotes to https so the helper's
133
+ // credential applies; GIT_TERMINAL_PROMPT=0 fails fast instead of hanging.
134
+ event.args[TYPECLAW_INTERNAL_BASH_ENV] = {
135
+ ...overlay,
136
+ GIT_ASKPASS: askpass,
137
+ TYPECLAW_GIT_TOKEN: result.token,
138
+ GIT_TERMINAL_PROMPT: '0',
139
+ GIT_CONFIG_COUNT: '2',
140
+ GIT_CONFIG_KEY_0: 'url.https://github.com/.insteadOf',
141
+ GIT_CONFIG_VALUE_0: 'git@github.com:',
142
+ GIT_CONFIG_KEY_1: 'url.https://github.com/.insteadOf',
143
+ GIT_CONFIG_VALUE_1: 'ssh://git@github.com/',
144
+ }
145
+ if (decision.rewrittenCommand !== undefined) event.args.command = decision.rewrittenCommand
146
+ return
147
+ }
148
+
22
149
  return {
23
150
  hooks: {
24
151
  'tool.before': async (event) => {
25
152
  if (event.tool !== 'bash') return
26
153
  const command = event.args.command
27
- if (typeof command !== 'string' || !command.includes('gh')) return
28
-
29
- const review = await noteReviewCommand({ callId: event.callId, command })
30
- if (review.detected !== null) {
31
- const block = await verdictGuard.guard({
32
- callId: event.callId,
33
- workspace: review.detected.workspace,
34
- prNumber: review.detected.prNumber,
35
- verdict: review.detected.verdict,
36
- })
37
- if (block !== null) return block
154
+ if (typeof command !== 'string') return
155
+
156
+ if (command.includes('gh')) {
157
+ const ghResult = await handleGhCommand({ event, command })
158
+ if (ghResult !== 'fall-through') return ghResult
159
+ }
160
+
161
+ if (command.includes('git')) {
162
+ return await handleGitCommand({ event, command, agentDir: ctx.agentDir })
38
163
  }
39
- if (review.dump !== null) return review.dump
40
-
41
- const decision = analyzeGhCommand(command)
42
- if (decision.kind === 'pass-through') return
43
-
44
- const tokenClass = classifyGhToken(process.env.GH_TOKEN)
45
- // Classic PATs reach every owner; nothing to inject or enforce.
46
- if (tokenClass === 'cross-owner') return
47
-
48
- if (decision.kind === 'block') return { block: true, reason: decision.reason }
49
-
50
- // Fine-grained PATs are single-owner but cannot be re-minted per repo;
51
- // the seeded GH_TOKEN is the only token we have. Leave it in place so
52
- // `gh` fails honestly if the named repo is under a different owner.
53
- if (tokenClass === 'fine-grained-pat') return
54
-
55
- const result = await resolveTokenForRepo(decision.repoSlug)
56
- if (result.kind === 'unavailable') return { block: true, reason: result.reason }
57
- // Inject via the internal env overlay (delivered to the spawn / bwrap
58
- // --setenv by the bash wrapper) so the token never enters the command
59
- // string, where it could leak through logs or later hooks.
60
- event.args[TYPECLAW_INTERNAL_BASH_ENV] = { GH_TOKEN: result.token }
61
- // graphql consumed `-R/--repo` as a mint hint; `gh api` rejects it, so
62
- // run the command with the flag stripped (token still rides in env).
63
- if (decision.rewrittenCommand !== undefined) event.args.command = decision.rewrittenCommand
64
164
  return
65
165
  },
66
166
  'tool.after': async (event) => {
@@ -9,3 +9,16 @@ export function classifyGhToken(token: string | undefined): GhTokenClass {
9
9
  // a per-repo token rather than silently using a possibly-wrong global one.
10
10
  return 'app'
11
11
  }
12
+
13
+ // Whether the per-repo App minter should fire for a repo-targeting command.
14
+ // App auth is detected via EITHER a seeded App-class GH_TOKEN OR a live App
15
+ // token resolver — the latter is the authority because multi-owner / no-repos
16
+ // App configs intentionally leave GH_TOKEN unseeded (the prefix would read
17
+ // 'none'), yet the per-repo minter is still registered and able to mint. Classic
18
+ // and fine-grained PATs are never re-minted: they pass through with whatever
19
+ // GH_TOKEN is seeded, exactly as before.
20
+ export function shouldMintAppToken(token: string | undefined, hasAppTokenResolver: boolean): boolean {
21
+ const tokenClass = classifyGhToken(token)
22
+ if (tokenClass === 'cross-owner' || tokenClass === 'fine-grained-pat') return false
23
+ return tokenClass === 'app' || hasAppTokenResolver
24
+ }
@@ -427,6 +427,37 @@ const GIT_EXFIL_VERBS = [
427
427
  'hub\\s+(?:create|push)',
428
428
  ].join('|')
429
429
 
430
+ // "backup" framing across the same major-language set the rest of this file
431
+ // covers. The narrow English+Korean-only version let "백업 해줘 to my repo"
432
+ // framings phrased in any other channel language slip the standalone-backup
433
+ // catch (the SECRET_DEMAND patterns still fire when a credential is named; this
434
+ // is only the no-secret-named "push to my backup repo" idiom). Entries are the
435
+ // noun/verb for "backup"/"back up" — kept tight so they only matter within the
436
+ // 80-char proximity-to-git-push window below, never on their own.
437
+ const BACKUP_NOUNS = [
438
+ 'backup',
439
+ 'back[-\\s]?up',
440
+ '\u{BC31}\u{C5C5}', // ko 백업
441
+ '\u30D0\u30C3\u30AF\u30A2\u30C3\u30D7', // ja バックアップ
442
+ '\u5907\u4EFD', // zh-hans 备份
443
+ '\u5099\u4EFD', // zh-hant 備份
444
+ 'copia\\s*de\\s*seguridad', // es
445
+ 'respald(?:o|ar|a)', // es respaldo/respaldar
446
+ 'sauvegard(?:e|er)', // fr
447
+ 'sicherungskopie', // de
448
+ 'sicher(?:n|ung)', // de Sicherung/sichern
449
+ 'c[\u00F3o]pia\\s*de\\s*seguran[\u00E7c]a', // pt
450
+ 'fazer\\s*backup', // pt
451
+ '\u0440\u0435\u0437\u0435\u0440\u0432\u043D(?:\u0430\u044F|\u0443\u044E)\\s*\u043A\u043E\u043F\u0438\u044F', // ru резервная копия
452
+ 'sao\\s*l\u01B0u', // vi sao lưu
453
+ 'cadang(?:an)?', // id cadangan/mencadangkan
454
+ '\u0646\u0633\u062E(?:\u0629)?\\s*\u0627\u062D\u062A\u064A\u0627\u0637\u064A(?:\u0629)?', // ar نسخة احتياطية
455
+ '\u092C\u0948\u0915\u0905\u092A', // hi बैकअप
456
+ 'yede(?:k|kle)', // tr yedek/yedekle
457
+ 'copia\\s*di\\s*sicurezza', // it
458
+ 'backup', // it (loanword, same token)
459
+ ].join('|')
460
+
430
461
  const GIT_EXFIL_PATTERNS: ReadonlyArray<RegExp> = [
431
462
  new RegExp(`(?:${GIT_EXFIL_VERBS})`, 'i'),
432
463
  // Urgency shorthand ("do it" / "go ahead" / "now") right after a git command,
@@ -440,8 +471,8 @@ const GIT_EXFIL_PATTERNS: ReadonlyArray<RegExp> = [
440
471
  // request - if the same message also names a credential or `.env`, the
441
472
  // SECRET_DEMAND_PATTERNS already fires; this catches the standalone
442
473
  // "push to my backup repo" framing that doesn't mention secrets.
443
- /(?:backup|back[-\s]?up|\u{BC31}\u{C5C5})[\s\S]{0,80}(?:git\s+push|github\.com|gitlab\.com|bitbucket\.org)/iu,
444
- /(?:git\s+push|github\.com|gitlab\.com|bitbucket\.org)[\s\S]{0,80}(?:backup|back[-\s]?up|\u{BC31}\u{C5C5})/iu,
474
+ new RegExp(`(?:${BACKUP_NOUNS})[\\s\\S]{0,80}(?:git\\s+push|github\\.com|gitlab\\.com|bitbucket\\.org)`, 'iu'),
475
+ new RegExp(`(?:git\\s+push|github\\.com|gitlab\\.com|bitbucket\\.org)[\\s\\S]{0,80}(?:${BACKUP_NOUNS})`, 'iu'),
445
476
  ]
446
477
 
447
478
  export type InjectionMatch = {
@@ -396,17 +396,24 @@ export function classifyGithubInbound(
396
396
  const root = parentId ?? id
397
397
  const parent =
398
398
  parentId !== null && options?.reviewCommentParent?.parentId === parentId ? options.reviewCommentParent : null
399
+ const commenter = readUser(comment.user)
400
+ const directedAtBot =
401
+ parentId === null &&
402
+ isSelfPr(readUser(pr.user), selfLogin, options?.authType ?? 'pat') &&
403
+ commenter !== null &&
404
+ !isSelfAuthor(commenter, null, selfLogin)
399
405
  return buildInbound(
400
406
  { ...base, chat: `pr:${number}`, thread: String(root) },
401
407
  comment.body,
402
408
  id,
403
- readUser(comment.user),
409
+ commenter,
404
410
  mention,
405
411
  comment.created_at,
406
412
  { kind: 'pr-review-comment', owner: repository.owner, repo: repository.name, commentId: id },
407
413
  false,
408
414
  {
409
415
  suppressSticky: true,
416
+ ...(directedAtBot ? { forceBotMention: true } : {}),
410
417
  replyToBotMessageId: parent?.isSelf === true ? String(parent.parentId) : null,
411
418
  replyToOtherMessageId: parent?.isSelf === false ? String(parent.parentId) : null,
412
419
  },
@@ -533,6 +540,11 @@ export function classifyGithubInbound(
533
540
  : reviewer !== null
534
541
  ? synthesizeReviewStateText(reviewer.login, number, readString(pr, 'title'), readString(review, 'state'))
535
542
  : ''
543
+ const directedAtBot =
544
+ isSelfPr(readUser(pr.user), selfLogin, options?.authType ?? 'pat') &&
545
+ reviewer !== null &&
546
+ !isSelfAuthor(reviewer, null, selfLogin) &&
547
+ isActionableReviewState(readString(review, 'state'))
536
548
  return buildInbound(
537
549
  { ...base, chat: `pr:${number}`, thread: null },
538
550
  text,
@@ -542,7 +554,7 @@ export function classifyGithubInbound(
542
554
  review.submitted_at,
543
555
  null,
544
556
  !hasBody,
545
- { suppressSticky: true },
557
+ { suppressSticky: true, ...(directedAtBot ? { forceBotMention: true } : {}) },
546
558
  )
547
559
  }
548
560
 
@@ -591,6 +603,12 @@ type BuildInboundOptions = {
591
603
  suppressSticky?: boolean
592
604
  replyToBotMessageId?: string | null
593
605
  replyToOtherMessageId?: string | null
606
+ // Forces isBotMention=true with no @-handle in the body. A review (or
607
+ // top-level review comment) on a PR the agent ITSELF authored is directed at
608
+ // the bot — the inverse of review_requested — so it engages even though the
609
+ // reviewer never types `@bot`. Paired with suppressSticky so reviews on OTHER
610
+ // people's PRs still observe-only (preserving the PR #672 fix).
611
+ forceBotMention?: boolean
594
612
  }
595
613
 
596
614
  // A GitHub App can never be a `requested_reviewer` — that field only holds
@@ -799,7 +817,7 @@ function buildInbound(
799
817
  // Synthesized awareness lines carry an `@author` prefix describing who acted;
800
818
  // that handle is the author, never a third-party mention of the bot, so the
801
819
  // body-text mention heuristic must not fire on it.
802
- const isBotMention = !synthesizedAwareness && textMentionsBot(text, mention)
820
+ const isBotMention = options?.forceBotMention === true || (!synthesizedAwareness && textMentionsBot(text, mention))
803
821
  const replyToBotMessageId = options?.replyToBotMessageId ?? null
804
822
  const replyToOtherMessageId = options?.replyToOtherMessageId ?? key.replyToOtherMessageId
805
823
  return {
@@ -854,6 +872,15 @@ function synthesizeReviewStateText(
854
872
  return `@${reviewer} ${verb} PR #${number}${label}.`
855
873
  }
856
874
 
875
+ // A review on the agent's own PR engages it only when there is something to act
876
+ // on. APPROVED clears the PR and needs no reply, so engaging would just produce
877
+ // "thanks" churn; it stays awareness-only. COMMENTED and CHANGES_REQUESTED (and
878
+ // any non-approval state) carry feedback the agent should address. State case
879
+ // varies by payload source (webhook vs REST), so normalize before matching.
880
+ function isActionableReviewState(state: string | null): boolean {
881
+ return state?.toLowerCase() !== 'approved'
882
+ }
883
+
857
884
  async function resolveTeamMembership(
858
885
  event: string,
859
886
  payload: Record<string, unknown>,
@@ -981,6 +1008,17 @@ function isSelfAuthor(author: GithubUser, selfId: string | null, selfLogin: stri
981
1008
  return false
982
1009
  }
983
1010
 
1011
+ // Whether the PR's OPENER is this agent. Distinct from isSelfAuthor (which
1012
+ // guards self-loops on the event ACTOR by id/login): here we have only the
1013
+ // `pull_request.user` from a review payload, no id to compare, and under App
1014
+ // auth the bot opens PRs as the decoy account (login = slug, e.g. `typeey`),
1015
+ // not the actor login `typeey[bot]`. So this matches selfLogin AND the decoy
1016
+ // slug — mirroring resolveBotMentionLogins.
1017
+ function isSelfPr(prUser: GithubUser | null, selfLogin: string | null, authType: 'pat' | 'app'): boolean {
1018
+ if (prUser === null || selfLogin === null) return false
1019
+ return resolveBotMentionLogins(selfLogin, authType).includes(prUser.login)
1020
+ }
1021
+
984
1022
  type GithubUser = { login: string; id: number; type?: string }
985
1023
 
986
1024
  function readUser(value: unknown): GithubUser | null {
@@ -359,18 +359,26 @@ export function createTypingCallback(deps: {
359
359
  // threads keep using `thread`. Either way the status is keyed on one ts.
360
360
  const statusThread =
361
361
  target.typingThread !== undefined && target.typingThread !== '' ? target.typingThread : target.thread
362
- const tag = formatChannelTag
363
- ? await formatChannelTag(target.workspace, statusThread ?? target.chat)
364
- : `channel=${statusThread ?? target.chat}`
365
362
  if (statusThread === undefined || statusThread === null || statusThread === '') {
366
- if (target.phase === 'tick') logger.info(`[slack-bot] typing (no-op, top-level chat) ${tag}`)
367
- return
368
- }
369
- if (target.phase === 'stop') {
370
- await typingTracker.clearAfterSend(target.chat, statusThread)
363
+ if (target.phase === 'tick') {
364
+ const tag = formatChannelTag
365
+ ? await formatChannelTag(target.workspace, statusThread ?? target.chat)
366
+ : `channel=${statusThread ?? target.chat}`
367
+ logger.info(`[slack-bot] typing (no-op, top-level chat) ${tag}`)
368
+ }
371
369
  return
372
370
  }
373
- await typingTracker.setStatus(target.chat, statusThread, 'is typing...')
371
+ // Append to the per-(chat,thread) FIFO BEFORE awaiting anything: the FIFO
372
+ // only orders calls once setStatus/clearAfterSend is reached, so awaiting
373
+ // `formatChannelTag` first opens an unordered gap where a fire-and-forget
374
+ // re-arm 'tick' (router send() after a reply) can enqueue "is typing..."
375
+ // AFTER the turn-end 'stop' clear. Flat DMs have no threaded-reply
376
+ // auto-clear, so that strands the indicator until Slack's ~2-min timeout.
377
+ const enqueued =
378
+ target.phase === 'stop'
379
+ ? typingTracker.clearAfterSend(target.chat, statusThread)
380
+ : typingTracker.setStatus(target.chat, statusThread, 'is typing...')
381
+ await enqueued
374
382
  }
375
383
  }
376
384