typeclaw 0.48.11 → 0.48.12

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 (40) hide show
  1. package/package.json +2 -2
  2. package/src/agent/index.ts +11 -1
  3. package/src/bundled-plugins/github-cli-auth/gh-command.ts +7 -1
  4. package/src/bundled-plugins/github-cli-auth/index.ts +1 -1
  5. package/src/bundled-plugins/github-cli-auth/review-checkout.ts +9 -1
  6. package/src/bundled-plugins/memory/dreaming.ts +21 -6
  7. package/src/channels/adapters/kakaotalk-channel-resolver.ts +86 -16
  8. package/src/channels/adapters/kakaotalk.ts +7 -8
  9. package/src/channels/adapters/teams-classify.ts +21 -0
  10. package/src/channels/adapters/teams-edit.ts +2 -1
  11. package/src/channels/adapters/teams-format.ts +16 -0
  12. package/src/channels/adapters/teams.ts +12 -5
  13. package/src/cli/compose.ts +3 -3
  14. package/src/cli/docker-preflight.ts +8 -4
  15. package/src/cli/restart.ts +89 -23
  16. package/src/cli/start.ts +68 -16
  17. package/src/cli/status.ts +38 -6
  18. package/src/cli/stop.ts +5 -2
  19. package/src/compose/stop.ts +5 -4
  20. package/src/container/build-cache.ts +807 -0
  21. package/src/container/compose-project.ts +4 -0
  22. package/src/container/docker-app.ts +74 -0
  23. package/src/container/log-archive.ts +33 -5
  24. package/src/container/memory-limit.ts +80 -0
  25. package/src/container/memory-oversubscription.ts +125 -0
  26. package/src/container/restart.ts +6 -1
  27. package/src/container/shared.ts +43 -16
  28. package/src/container/start.ts +280 -53
  29. package/src/container/stop.ts +19 -13
  30. package/src/container/verify-running.ts +12 -0
  31. package/src/cron/scheduler.ts +12 -4
  32. package/src/doctor/bounded-exec.ts +14 -0
  33. package/src/doctor/checks.ts +40 -15
  34. package/src/doctor/index.ts +14 -2
  35. package/src/doctor/plugin-bridge.ts +15 -3
  36. package/src/hostd/paths.ts +4 -0
  37. package/src/run/index.ts +16 -0
  38. package/src/run/resource-sample.ts +171 -0
  39. package/src/sandbox/index.ts +8 -1
  40. package/src/sandbox/session-tmp.ts +26 -1
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "typeclaw",
3
- "version": "0.48.11",
3
+ "version": "0.48.12",
4
4
  "homepage": "https://github.com/typeclaw/typeclaw#readme",
5
5
  "bugs": {
6
6
  "url": "https://github.com/typeclaw/typeclaw/issues"
@@ -50,7 +50,7 @@
50
50
  "@mariozechner/pi-tui": "^0.73.1",
51
51
  "@modelcontextprotocol/sdk": "^1.29.0",
52
52
  "@mozilla/readability": "^0.6.0",
53
- "agent-messenger": "^2.35.0",
53
+ "agent-messenger": "^2.37.2",
54
54
  "cheerio": "^1.2.0",
55
55
  "citty": "^0.2.2",
56
56
  "cron-parser": "^5.5.0",
@@ -36,7 +36,7 @@ import type {
36
36
  import { createHookBus, materializeSkills } from '@/plugin'
37
37
  import { CORE_SYSTEM_TOOL_NAMES } from '@/plugin/core-tool-names'
38
38
  import type { ReloadRegistry } from '@/reload'
39
- import { resolveHiddenPaths } from '@/sandbox'
39
+ import { enterSubagentTmpScope, resolveHiddenPaths } from '@/sandbox'
40
40
  import type { Stream } from '@/stream'
41
41
 
42
42
  import { applyAdaptiveThinkingCompat } from './adaptive-thinking-compat'
@@ -569,7 +569,17 @@ export async function createSessionWithDispose(options: CreateSessionOptions = {
569
569
 
570
570
  const unsubToolNudge = attachToolNotFoundNudge(session, intendedActiveToolNames)
571
571
 
572
+ // Registered only once creation can no longer fail, so a rejected creation
573
+ // leaves no scope entry behind; tools resolve the scope lazily at call time.
574
+ const releaseSubagentTmp =
575
+ options.origin?.kind === 'subagent' && options.origin.parentSessionId !== '<unknown>'
576
+ ? enterSubagentTmpScope(
577
+ options.plugins?.sessionId ?? sessionManager.getSessionId(),
578
+ options.origin.parentSessionId,
579
+ )
580
+ : undefined
572
581
  const dispose = async () => {
582
+ releaseSubagentTmp?.()
573
583
  unsubLoopGuardTurn()
574
584
  unsubRestart?.()
575
585
  unsubToolNudge()
@@ -11,6 +11,7 @@ export type GhBlockCode =
11
11
  | 'repo-selector-conflict'
12
12
  | 'credential-display'
13
13
  | 'credential-exposure'
14
+ | 'pathname-expansion'
14
15
 
15
16
  export type GhCommandDecision =
16
17
  | { kind: 'pass-through' }
@@ -59,6 +60,11 @@ const CREDENTIAL_DISPLAY_REASON =
59
60
  'In particular, `gh auth token` and `gh auth status --show-token` would print the command-scoped credential. ' +
60
61
  'Use host-side authentication setup or a redacted diagnostic instead.'
61
62
 
63
+ const PATHNAME_EXPANSION_REASON =
64
+ 'An unquoted `*`, `?`, or `[` in a gh command is a shell pathname pattern: the shell could expand it into ' +
65
+ 'different arguments than the ones TypeClaw authorized, so no credential is minted for it. ' +
66
+ "Quote the argument that contains it, e.g. `gh api '/repos/owner/repo/contents/path?ref=<sha>'`."
67
+
62
68
  const CREDENTIAL_EXPOSURE_REASON =
63
69
  'This gh command is not in TypeClaw’s credential-safe allowlist. Model-driven gh receives a command-scoped credential only for operations whose argv cannot read arbitrary files, render process environment values, upload arbitrary files, select another host, or start extensions. Use a supported direct gh operation, a first-class TypeClaw tool, or run this command host-side.'
64
70
 
@@ -194,7 +200,7 @@ export function analyzeGhCommand(command: string, fallbackRepo?: string): GhComm
194
200
  const ghStarts = findGhInvocations(tokens)
195
201
  if (ghStarts.length === 0) return { kind: 'pass-through' }
196
202
  if (containsUnquotedPathnameExpansion(command)) {
197
- return { kind: 'block', code: 'credential-exposure', reason: CREDENTIAL_EXPOSURE_REASON }
203
+ return { kind: 'block', code: 'pathname-expansion', reason: PATHNAME_EXPANSION_REASON }
198
204
  }
199
205
 
200
206
  for (let i = 0; i < ghStarts.length; i++) {
@@ -311,7 +311,7 @@ export default definePlugin({
311
311
  return {
312
312
  block: true,
313
313
  reason:
314
- decision.code === 'credential-display'
314
+ decision.code === 'credential-display' || decision.code === 'pathname-expansion'
315
315
  ? decision.reason
316
316
  : decision.reason + buildGhBlockGuidance(decision.code, fallbackRepo, command),
317
317
  }
@@ -80,7 +80,15 @@ export async function prepareReviewerCheckout(options: {
80
80
  ],
81
81
  { env: baseEnv },
82
82
  )
83
- return { path: checkout, repoSlug: options.repoSlug, headSha: options.headSha.toLocaleLowerCase() }
83
+ // The checkout lives in the session's `/tmp` backing dir, but the model only
84
+ // ever sees that dir AS `/tmp` (bwrap binds it there; file tools re-map
85
+ // `/tmp/*` into it). Returning the backing path would be re-mapped a second
86
+ // time and never resolve, so hand back the model-facing path.
87
+ return {
88
+ path: path.posix.join('/tmp', path.basename(checkout)),
89
+ repoSlug: options.repoSlug,
90
+ headSha: options.headSha.toLocaleLowerCase(),
91
+ }
84
92
  } catch (error) {
85
93
  await rm(checkout, { recursive: true, force: true }).catch(() => {})
86
94
  throw error
@@ -1,7 +1,7 @@
1
1
  import { createHash } from 'node:crypto'
2
2
  import { existsSync } from 'node:fs'
3
3
  import { mkdir, readdir, readFile, unlink, writeFile } from 'node:fs/promises'
4
- import { basename, join } from 'node:path'
4
+ import { basename, dirname, join } from 'node:path'
5
5
 
6
6
  import { z } from 'zod'
7
7
 
@@ -33,6 +33,7 @@ import { loadAllReferences, type Reference } from './references/load-references'
33
33
  import { captureShardSnapshot, restoreShardSnapshot } from './shard-snapshot'
34
34
  import type { StreamEvent } from './stream-events'
35
35
  import { readEvents, writeEventsAtomic } from './stream-io'
36
+ import { VECTOR_INDEX_REL_PATH } from './vector/doctor'
36
37
  import { embed, EMBEDDING_MODEL_ID } from './vector/embedder'
37
38
  import type { EmbedFn } from './vector/hybrid'
38
39
  import { topicPassage } from './vector/passages'
@@ -734,7 +735,17 @@ function isEnoent(err: unknown): boolean {
734
735
  return typeof err === 'object' && err !== null && 'code' in err && err.code === 'ENOENT'
735
736
  }
736
737
 
737
- const SNAPSHOT_PATHS = ['memory/'] as const
738
+ // The vector index is generated, rebuildable cache state, not durable memory.
739
+ // Keep force-adding the broad memory/ root so new durable artifact types are
740
+ // snapshotted automatically, while Git's exclusion pathspec keeps the SQLite
741
+ // DB and its WAL/SHM sidecars out of history.
742
+ const EXCLUDE_PATHSPEC_PREFIX = ':(exclude)'
743
+ const VECTOR_INDEX_DIRECTORY_REL_PATH = dirname(VECTOR_INDEX_REL_PATH)
744
+ const SNAPSHOT_PATHS = ['memory/', `${EXCLUDE_PATHSPEC_PREFIX}${VECTOR_INDEX_DIRECTORY_REL_PATH}/`] as const
745
+
746
+ function isSnapshotExclusionPathspec(pathspec: string): boolean {
747
+ return pathspec.startsWith(EXCLUDE_PATHSPEC_PREFIX)
748
+ }
738
749
 
739
750
  async function ensureMemoryFiles(agentDir: string): Promise<void> {
740
751
  const memoryDir = join(agentDir, 'memory')
@@ -767,10 +778,14 @@ async function commitMemorySnapshotUnlocked(cwd: string): Promise<void> {
767
778
 
768
779
  await clearSkipWorktree(bun, cwd, repo)
769
780
 
770
- // `git add -- foo bar/` fails with exit 128 if any pathspec matches no
771
- // path on disk. Filter to existing paths before passing them in.
772
- const presentPaths = SNAPSHOT_PATHS.filter((p) => existsSync(join(cwd, p)))
773
- if (presentPaths.length === 0) {
781
+ // `git add -- foo bar/` fails with exit 128 if any ordinary pathspec matches
782
+ // no path on disk. Keep exclusion pathspecs: they are Git syntax rather than
783
+ // filesystem paths, and must accompany the broad memory/ root everywhere it
784
+ // flows. Still return early when no ordinary root is present, so an exclusion
785
+ // by itself never reaches `git add`.
786
+ const presentPaths = SNAPSHOT_PATHS.filter((p) => isSnapshotExclusionPathspec(p) || existsSync(join(cwd, p)))
787
+ const hasPresentSnapshotRoot = presentPaths.some((p) => !isSnapshotExclusionPathspec(p))
788
+ if (!hasPresentSnapshotRoot) {
774
789
  await applySkipWorktree(bun, cwd, repo)
775
790
  return
776
791
  }
@@ -1,4 +1,10 @@
1
- import { classifyKakaoChat, type KakaoChat, type KakaoChatKind, type KakaoTalkClient } from 'agent-messenger/kakaotalk'
1
+ import {
2
+ classifyKakaoChat,
3
+ type KakaoChat,
4
+ type KakaoChatKind,
5
+ type KakaoMember,
6
+ type KakaoTalkClient,
7
+ } from 'agent-messenger/kakaotalk'
2
8
 
3
9
  import type { ChannelKey, ChannelNameResolver, ResolvedChannelNames } from '@/channels/types'
4
10
 
@@ -17,16 +23,51 @@ export function kakaoWorkspaceForType(kind: KakaoChatKind): KakaoWorkspace {
17
23
  export type KakaoChatLookupValue = {
18
24
  workspace: KakaoWorkspace
19
25
  isDm: boolean
20
- // True while the entry is a placeholder from `ingestProvisional` (a chat seen
21
- // on an inbound push but not yet surfaced by getChats). Its `workspace` is a
22
- // strict-bucket guess (@kakao-group), NOT the authoritative kind. Callers that
26
+ // True while the entry is a strict fallback guess (@kakao-group) — the chat
27
+ // is absent from getChats and its member roster proved nothing. Callers that
23
28
  // must know the real type decide per-feature: typing sends for provisional
24
29
  // entries (the @kakao-group guess is never @kakao-open, and a mis-guessed
25
30
  // OpenChat's linkless ACTION fails soft), while allow-rule enforcement keeps
26
- // treating the strict bucket as authoritative until a real refresh upgrades it.
31
+ // treating the strict bucket as authoritative until a real refresh upgrades
32
+ // it.
27
33
  provisional: boolean
28
34
  }
29
35
 
36
+ // What a member roster PROVES about a chat — never what it merely suggests.
37
+ //
38
+ // A roster read is only ever a SUBSET of the true membership: `getMembers`
39
+ // merges GETMEM with a CHATONROOM fallback whose failure it swallows, and that
40
+ // fallback can itself yield just `displayMembers`. So only conclusions that
41
+ // survive adding unseen members are sound:
42
+ //
43
+ // - an open marker present proves OpenChat — a subset cannot invent one
44
+ // (`open_token` / `open_profile_link_id` / `open_permission` are
45
+ // SDK-populated for OpenChat rooms only)
46
+ // - two or more counterparts proves not-a-DM — adding members keeps it true
47
+ //
48
+ // "Exactly one counterpart" proves NOTHING, because the remainder may simply be
49
+ // unobserved. So a DM is never inferred here; callers keep the strict bucket.
50
+ // Do NOT "restore" a `others.length <= 1 -> dm` branch: a truncated roster for a
51
+ // large room would then be cached as an authoritative DM, relaxing both the
52
+ // engagement ladder and `kakao:dm/*` allow-rule matching.
53
+ export function provenKindFromMembers(
54
+ members: readonly KakaoChatMemberSignal[],
55
+ selfUserId: string | null,
56
+ ): Extract<KakaoChatKind, 'open' | 'group'> | null {
57
+ if (members.some(isOpenChatMember)) return 'open'
58
+ const others = members.filter((member) => member.user_id !== selfUserId)
59
+ return others.length >= 2 ? 'group' : null
60
+ }
61
+
62
+ export type KakaoChatMemberSignal = Pick<
63
+ KakaoMember,
64
+ 'user_id' | 'open_token' | 'open_profile_link_id' | 'open_permission'
65
+ >
66
+
67
+ function isOpenChatMember(member: KakaoChatMemberSignal): boolean {
68
+ return member.open_token !== null || member.open_profile_link_id !== null || member.open_permission !== null
69
+ }
70
+
30
71
  export type KakaoChannelResolver = {
31
72
  resolve: ChannelNameResolver
32
73
  lookupChat: (chatId: string) => KakaoChatLookupValue | null
@@ -34,18 +75,20 @@ export type KakaoChannelResolver = {
34
75
  // Register a chat we learned about from an inbound push event, used as a
35
76
  // fallback when `refresh()` did not surface it (e.g. memo chats, certain
36
77
  // open chats, or chats whose membership has not yet propagated to
37
- // getChats({all:true})). Provisional entries default to @kakao-group —
38
- // the strictest bucket, matching the history callback's existing fallback
39
- // — so allow-rule enforcement stays strict. A subsequent real refresh
40
- // upgrades the entry to its authoritative kind.
41
- ingestProvisional: (chatId: string) => void
78
+ // getChats({all:true})). Upgrades the entry only to what a per-chat member
79
+ // read PROVES, and otherwise falls back to @kakao-group — the strictest
80
+ // bucket, matching the history callback's existing fallback — so allow-rule
81
+ // enforcement stays strict on chats the roster could not establish.
82
+ // Returns the bucket it settled on so callers can log the real outcome.
83
+ ingestProvisional: (chatId: string) => Promise<KakaoWorkspace>
42
84
  }
43
85
 
44
86
  export type KakaoChannelResolverOptions = {
45
- client: Pick<KakaoTalkClient, 'getChats'>
87
+ client: Pick<KakaoTalkClient, 'getChats' | 'getMembers'>
46
88
  now?: () => number
47
89
  ttlMs?: number
48
90
  logger?: { warn: (msg: string) => void }
91
+ selfUserId?: () => string | null
49
92
  }
50
93
 
51
94
  type Entry = {
@@ -117,16 +160,43 @@ export function createKakaoChannelResolver(options: KakaoChannelResolverOptions)
117
160
  return { workspace: entry.workspace, isDm: entry.isDm, provisional: entry.provisional }
118
161
  }
119
162
 
120
- const ingestProvisional = (chatId: string): void => {
121
- const existing = cache.get(chatId)
122
- if (existing !== undefined && existing.expiresAt > now()) return
163
+ const liveEntry = (chatId: string): Entry | null => {
164
+ const entry = cache.get(chatId)
165
+ return entry !== undefined && entry.expiresAt > now() ? entry : null
166
+ }
167
+
168
+ const provenKindFor = async (chatId: string): Promise<'open' | 'group' | null> => {
169
+ try {
170
+ const members = await options.client.getMembers(chatId)
171
+ return provenKindFromMembers(members, options.selfUserId?.() ?? null)
172
+ } catch (err) {
173
+ options.logger?.warn(`[kakaotalk] provisional member lookup failed chat=${chatId}: ${describeError(err)}`)
174
+ return null
175
+ }
176
+ }
177
+
178
+ const ingestProvisional = async (chatId: string): Promise<KakaoWorkspace> => {
179
+ const cached = liveEntry(chatId)
180
+ if (cached !== null) return cached.workspace
181
+
182
+ const kind = await provenKindFor(chatId)
183
+
184
+ // The member read was awaited, so a concurrent `refresh()` may have landed
185
+ // a getChats-authoritative entry meanwhile. Re-check instead of writing
186
+ // blind: clobbering it would replace a real classification with a weaker
187
+ // member-derived one — or with the strict fallback — for a whole TTL.
188
+ const current = liveEntry(chatId)
189
+ if (current !== null && !current.provisional) return current.workspace
190
+
191
+ const workspace = kind === null ? '@kakao-group' : kakaoWorkspaceForType(kind)
123
192
  cache.set(chatId, {
124
- workspace: '@kakao-group',
193
+ workspace,
125
194
  isDm: false,
126
195
  chatName: null,
127
196
  expiresAt: now() + ttlMs,
128
- provisional: true,
197
+ provisional: kind === null,
129
198
  })
199
+ return workspace
130
200
  }
131
201
 
132
202
  return { resolve, lookupChat, refresh, ingestProvisional }
@@ -378,7 +378,7 @@ export function createKakaotalkAdapter(options: KakaotalkAdapterOptions): Kakaot
378
378
  recoveryEpisode = null
379
379
  }
380
380
 
381
- const channelResolver = createKakaoChannelResolver({ client, logger })
381
+ const channelResolver = createKakaoChannelResolver({ client, logger, selfUserId: () => selfUserId })
382
382
  const authorResolver = createKakaoAuthorResolver({ client, logger })
383
383
  const membershipResolver = createKakaoMembershipResolver({
384
384
  client,
@@ -443,14 +443,13 @@ export function createKakaotalkAdapter(options: KakaotalkAdapterOptions): Kakaot
443
443
  // The push event itself proves the chat exists, even when
444
444
  // getChats({all:true}) does not surface it (e.g. memo chats,
445
445
  // certain open chats, recently-joined groups that haven't
446
- // propagated). Register a provisional @kakao-group entry (the
447
- // strictest workspace bucket — narrowest engagement assumptions)
448
- // so the message is no longer silently dropped as unknown_chat.
449
- // The next real refresh upgrades the entry if the chat is
450
- // actually a DM or open chat.
451
- channelResolver.ingestProvisional(event.chat_id)
446
+ // propagated). Resolve the real kind from a per-chat member read
447
+ // so the message is no longer silently dropped as unknown_chat,
448
+ // falling back to the strictest @kakao-group bucket when that read
449
+ // yields nothing. The next real refresh re-confirms the entry.
450
+ const bucket = await channelResolver.ingestProvisional(event.chat_id)
452
451
  logger.warn(
453
- `[kakaotalk] provisional chat=${event.chat_id} log_id=${event.log_id} bucket=@kakao-group reason=not_in_getchats`,
452
+ `[kakaotalk] provisional chat=${event.chat_id} log_id=${event.log_id} bucket=${bucket} reason=not_in_getchats`,
454
453
  )
455
454
  }
456
455
  }
@@ -142,3 +142,24 @@ function isAddressedToBot(event: TeamsInboundEvent, self: TeamsUser, selfAliases
142
142
  export function normalizeTeamsText(text: string): string {
143
143
  return text.replace(/\s+/g, ' ').trim()
144
144
  }
145
+
146
+ // Teams is the only adapter whose classifier never returns `self_author` — the
147
+ // user SDK reports `'ME'` for every author, so the send/echo fingerprint is the
148
+ // ONLY thing standing between the agent and answering its own message. That
149
+ // makes the comparison worth hardening: we fingerprint what we handed the SDK,
150
+ // but Teams stores messages as HTML, so the text comes back escaped-then-decoded
151
+ // and the two sides are not the same string. The decode is also lossy in one
152
+ // direction — it expands `&amp;` before `&lt;`, so a literal `&lt;` we wrote
153
+ // returns as `<` — which without this would miss its own reservation and route
154
+ // the agent's message back in as inbound. Decoding both sides identically makes
155
+ // the comparison survive the round trip; on text holding no entities it is a
156
+ // no-op. Order mirrors the SDK's decoder, and must keep mirroring it.
157
+ export function teamsEchoTextKey(text: string): string {
158
+ const decoded = text
159
+ .replace(/&amp;/g, '&')
160
+ .replace(/&lt;/g, '<')
161
+ .replace(/&gt;/g, '>')
162
+ .replace(/&quot;/g, '"')
163
+ .replace(/&#39;/g, "'")
164
+ return normalizeTeamsText(decoded)
165
+ }
@@ -3,6 +3,7 @@ import type { TeamsClient } from 'agent-messenger/teams'
3
3
  import type { EditMessageCallback, EditMessageResult } from '@/channels/types'
4
4
 
5
5
  import { describeError } from '../describe-error'
6
+ import { TEAMS_OUTBOUND_FORMAT } from './teams-format'
6
7
  import { decodeTeamsConversationKey } from './teams-key'
7
8
 
8
9
  // The Teams user-account SDK only exposes an edit primitive for 1:1/group
@@ -24,7 +25,7 @@ export function createTeamsEditMessageCallback(deps: {
24
25
  return { ok: false, error: 'Teams channel messages cannot be edited', code: 'not-supported' }
25
26
  }
26
27
  try {
27
- await deps.client.editChatMessage(decoded.chatId, req.messageId, req.text)
28
+ await deps.client.editChatMessage(decoded.chatId, req.messageId, req.text, TEAMS_OUTBOUND_FORMAT)
28
29
  } catch (err) {
29
30
  return { ok: false, error: describeError(err), code: classifyEditError(err) }
30
31
  }
@@ -0,0 +1,16 @@
1
+ import type { TeamsMessageFormat } from 'agent-messenger/teams'
2
+
3
+ // Teams posts every outbound as `RichText/Html`, so the SDK has to decide how
4
+ // our string becomes markup. TypeClaw's contract is PLAIN TEXT — `OutboundMessage`
5
+ // carries no format metadata and no tool or skill can ask for another rendering,
6
+ // so `text` (HTML-escape) is the only mode that shows what the agent wrote;
7
+ // `html`/`markdown` would promote arbitrary prose, which routinely relays text
8
+ // authored by untrusted channel users, into live markup. Native Teams mentions,
9
+ // if ever needed, belong in a structured mention field the adapter converts —
10
+ // not in a blanket format switch.
11
+ //
12
+ // Passed EXPLICITLY at every call site, never left to the SDK default: 2.35.0
13
+ // escaped the chat path but posted the team/channel path raw, and 2.37.2
14
+ // defaulted both to `text`. Naming it pins what lands in users' chats against a
15
+ // future upstream flip.
16
+ export const TEAMS_OUTBOUND_FORMAT: TeamsMessageFormat = 'text'
@@ -19,11 +19,12 @@ import { describeError } from '../describe-error'
19
19
  import {
20
20
  classifyChannelInbound,
21
21
  classifyChatInbound,
22
- normalizeTeamsText,
22
+ teamsEchoTextKey,
23
23
  type InboundDropReason,
24
24
  type TeamsInboundEvent,
25
25
  } from './teams-classify'
26
26
  import { createTeamsEditMessageCallback } from './teams-edit'
27
+ import { TEAMS_OUTBOUND_FORMAT } from './teams-format'
27
28
  import { ContainerTeamsClient } from './teams-id-token'
28
29
  import { decodeTeamsConversationKey } from './teams-key'
29
30
 
@@ -110,8 +111,14 @@ export function createOutboundCallback(deps: {
110
111
  try {
111
112
  const sent =
112
113
  decoded.kind === 'chat'
113
- ? await client.sendChatMessage(decoded.chatId, text)
114
- : await client.sendMessage(decoded.teamId, decoded.channelId, text, msg.thread ?? undefined)
114
+ ? await client.sendChatMessage(decoded.chatId, text, TEAMS_OUTBOUND_FORMAT)
115
+ : await client.sendMessage(
116
+ decoded.teamId,
117
+ decoded.channelId,
118
+ text,
119
+ msg.thread ?? undefined,
120
+ TEAMS_OUTBOUND_FORMAT,
121
+ )
115
122
  logger.info(`[teams] sent id=${sent.id} ${decoded.kind}=${conversationId}`)
116
123
  return { ok: true, messageId: sent.id, messageIds: [sent.id] }
117
124
  } catch (err) {
@@ -168,7 +175,7 @@ export function createTeamsAdapter(options: TeamsAdapterOptions): TeamsAdapter {
168
175
  self !== null ? { id: self.id, username: self.userPrincipalName ?? self.email ?? self.displayName } : null
169
176
 
170
177
  const reserveEcho = (chatId: string, text: string): (() => void) => {
171
- const echo: SentEcho = { chatId, textKey: normalizeTeamsText(text), sentAt: now(), consumed: false }
178
+ const echo: SentEcho = { chatId, textKey: teamsEchoTextKey(text), sentAt: now(), consumed: false }
172
179
  sentEchoes.push(echo)
173
180
  if (sentEchoes.length > MAX_SENT_ECHOES) sentEchoes = sentEchoes.slice(-MAX_SENT_ECHOES)
174
181
  return () => {
@@ -179,7 +186,7 @@ export function createTeamsAdapter(options: TeamsAdapterOptions): TeamsAdapter {
179
186
 
180
187
  const isSelfEcho = (event: TeamsInboundEvent): boolean => {
181
188
  const conversationId = echoConversationId(event)
182
- const textKey = normalizeTeamsText(event.content)
189
+ const textKey = teamsEchoTextKey(event.content)
183
190
  const authorName = event.author.displayName.trim().toLocaleLowerCase()
184
191
  const selfName = (self?.displayName ?? '').trim().toLocaleLowerCase()
185
192
  const nowMs = now()
@@ -366,9 +366,9 @@ function formatStartDone<T extends { alreadyRunning?: boolean; hostPort: number
366
366
  }
367
367
 
368
368
  function formatStopDone<T extends { running: boolean }>(result: AgentResult<T>): string {
369
- if (!result.ok) return `${c.red('✖')} ${c.red('failed:')} ${result.reason}`
370
- if (result.data.running) return `${c.green('✔')} stopped`
371
- return `${c.dim('○')} ${c.dim('not running')}`
369
+ if (!result.ok) return appendWarnings(`${c.red('✖')} ${c.red('failed:')} ${result.reason}`, result.warnings)
370
+ const head = result.data.running ? `${c.green('✔')} stopped` : `${c.dim('○')} ${c.dim('not running')}`
371
+ return appendWarnings(head, result.warnings)
372
372
  }
373
373
 
374
374
  function formatRestartDone<T extends { start: { hostPort: number } }>(result: AgentResult<T>): string {
@@ -3,6 +3,7 @@ import {
3
3
  detectInstalledDockerApps,
4
4
  pickRuntimeToNudge,
5
5
  renderDockerUnavailableGuidance,
6
+ type DockerAppProbes,
6
7
  type DockerExec,
7
8
  } from '@/container'
8
9
 
@@ -16,15 +17,18 @@ export type DockerPreflightResult = { ok: true } | { ok: false; summary: string;
16
17
  // then hands the friendly, runtime-specific guidance back to the caller so each
17
18
  // command renders it in its own style (spinner vs console) — no process.exit
18
19
  // here, that belongs to the command.
19
- export async function preflightDocker(exec?: DockerExec): Promise<DockerPreflightResult> {
20
+ export async function preflightDocker(exec?: DockerExec, probes?: DockerAppProbes): Promise<DockerPreflightResult> {
20
21
  const availability = exec ? await checkDockerAvailable(exec) : await checkDockerAvailable()
21
22
  if (availability.ok) return { ok: true }
22
23
 
23
24
  const detail = availability.reason === 'daemon-down' ? availability.detail : undefined
24
- const installed = detectInstalledDockerApps()
25
- const nudge = pickRuntimeToNudge(process.env, detail, installed)
25
+ // Probes are injectable so tests do not depend on which Docker runtimes
26
+ // happen to be installed on the machine running them.
27
+ const installed = detectInstalledDockerApps(probes)
28
+ const env = probes?.env ?? process.env
29
+ const nudge = pickRuntimeToNudge(env, detail, installed)
26
30
  const { summary, lines } = renderDockerUnavailableGuidance(availability, {
27
- platform: process.platform,
31
+ platform: probes?.platform ?? process.platform,
28
32
  nudge,
29
33
  installed,
30
34
  })
@@ -2,13 +2,60 @@ import { confirm, isCancel } from '@clack/prompts'
2
2
  import { defineCommand } from 'citty'
3
3
 
4
4
  import { config, validateConfig } from '@/config'
5
- import { resolveController } from '@/container'
5
+ import { type Controller, resolveController } from '@/container'
6
6
  import { findAgentDir, isInitialized } from '@/init'
7
7
 
8
8
  import { preflightDocker, printDockerGuidance } from './docker-preflight'
9
9
  import { guardIncompleteInit } from './incomplete-init'
10
10
  import { c, errorLine, renderStartSuccess, reportConfigWarnings, spinner } from './ui'
11
11
 
12
+ export type RestartCommandEvent =
13
+ | { kind: 'stop-spinner-start'; message: string }
14
+ | { kind: 'stop-spinner-stop'; message: string }
15
+ | { kind: 'stop-spinner-error'; message: string }
16
+ | { kind: 'start-spinner-start'; message: string }
17
+ | { kind: 'start-spinner-stop'; message: string }
18
+ | { kind: 'start-spinner-error'; message: string }
19
+ | { kind: 'warnings'; warnings: string[] }
20
+ | { kind: 'success'; output: string }
21
+
22
+ export type RestartCommandDeps = {
23
+ restart: Controller['restart']
24
+ onEvent: (event: RestartCommandEvent) => void
25
+ }
26
+
27
+ export async function runRestartCommand(
28
+ options: { cwd: string; preferredHostPort: number; forceBuild: boolean; cliEntry?: string },
29
+ deps: RestartCommandDeps,
30
+ ): Promise<{ ok: boolean }> {
31
+ deps.onEvent({ kind: 'stop-spinner-start', message: 'Stopping container...' })
32
+ let stopped = false
33
+ const warnings: string[] = []
34
+ const result = await deps.restart({
35
+ ...options,
36
+ onWarning: (warning) => warnings.push(warning),
37
+ onStopped: (stopResult) => {
38
+ stopped = true
39
+ deps.onEvent({
40
+ kind: 'stop-spinner-stop',
41
+ message: stopResult.running ? `Stopped ${c.cyan(stopResult.containerName)}.` : 'Already stopped.',
42
+ })
43
+ deps.onEvent({ kind: 'start-spinner-start', message: 'Starting container...' })
44
+ },
45
+ })
46
+ if (!result.ok) {
47
+ deps.onEvent({ kind: stopped ? 'start-spinner-error' : 'stop-spinner-error', message: result.reason })
48
+ deps.onEvent({ kind: 'warnings', warnings })
49
+ return { ok: false }
50
+ }
51
+
52
+ deps.onEvent({ kind: 'start-spinner-stop', message: 'Started.' })
53
+ deps.onEvent({ kind: 'warnings', warnings })
54
+ deps.onEvent({ kind: 'warnings', warnings: result.start.dockerfileWarnings })
55
+ deps.onEvent({ kind: 'success', output: renderStartSuccess(result.start) })
56
+ return { ok: true }
57
+ }
58
+
12
59
  export const restartCommand = defineCommand({
13
60
  meta: {
14
61
  name: 'restart',
@@ -70,30 +117,49 @@ export const restartCommand = defineCommand({
70
117
  process.exit(1)
71
118
  }
72
119
 
73
- const controller = resolveController()
74
-
75
120
  const stopSpin = spinner()
76
- stopSpin.start('Stopping container...')
121
+ const controller = resolveController()
77
122
  let startSpin: ReturnType<typeof spinner> | undefined
78
- const restarted = await controller.restart({
79
- cwd,
80
- preferredHostPort: Number(args.port),
81
- forceBuild: args.build,
82
- cliEntry: process.argv[1],
83
- onStopped: (stopped) => {
84
- stopSpin.stop(stopped.running ? `Stopped ${c.cyan(stopped.containerName)}.` : 'Already stopped.')
85
- startSpin = spinner()
86
- startSpin.start('Starting container...')
123
+ const result = await runRestartCommand(
124
+ {
125
+ cwd,
126
+ preferredHostPort: Number(args.port),
127
+ forceBuild: args.build,
128
+ cliEntry: process.argv[1],
87
129
  },
88
- })
89
- if (!restarted.ok) {
90
- if (startSpin === undefined) stopSpin.error(restarted.reason)
91
- else startSpin.error(restarted.reason)
92
- process.exit(1)
93
- }
94
- startSpin?.stop('Started.')
95
-
96
- reportConfigWarnings(restarted.start.dockerfileWarnings)
97
- console.log(renderStartSuccess(restarted.start))
130
+ {
131
+ restart: (restartOptions) => controller.restart(restartOptions),
132
+ onEvent: (event) => {
133
+ switch (event.kind) {
134
+ case 'stop-spinner-start':
135
+ stopSpin.start(event.message)
136
+ break
137
+ case 'stop-spinner-stop':
138
+ stopSpin.stop(event.message)
139
+ break
140
+ case 'stop-spinner-error':
141
+ stopSpin.error(event.message)
142
+ break
143
+ case 'start-spinner-start':
144
+ startSpin = spinner()
145
+ startSpin.start(event.message)
146
+ break
147
+ case 'start-spinner-stop':
148
+ startSpin?.stop(event.message)
149
+ break
150
+ case 'start-spinner-error':
151
+ startSpin?.error(event.message)
152
+ break
153
+ case 'warnings':
154
+ reportConfigWarnings(event.warnings)
155
+ break
156
+ case 'success':
157
+ console.log(event.output)
158
+ break
159
+ }
160
+ },
161
+ },
162
+ )
163
+ if (!result.ok) process.exit(1)
98
164
  },
99
165
  })