typeclaw 0.48.4 → 0.48.6

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 (44) hide show
  1. package/package.json +1 -1
  2. package/src/agent/index.ts +6 -1
  3. package/src/agent/live-subagents.ts +15 -0
  4. package/src/agent/plugin-tools.ts +1 -1
  5. package/src/agent/session-origin.ts +104 -16
  6. package/src/agent/subagent-completion-reminder.ts +1 -1
  7. package/src/agent/subagent-drain.ts +11 -1
  8. package/src/agent/subagents.ts +52 -7
  9. package/src/agent/tools/post-github-review.ts +101 -1
  10. package/src/agent/tools/spawn-subagent.ts +88 -7
  11. package/src/agent/tools/subagent-cancel.ts +1 -0
  12. package/src/agent/tools/subagent-output.ts +7 -2
  13. package/src/agent/tools/webfetch/adaptive-html.ts +319 -0
  14. package/src/agent/tools/webfetch/html-lexical.ts +841 -0
  15. package/src/agent/tools/webfetch/inline-style-visibility.ts +281 -0
  16. package/src/agent/tools/webfetch/strategies/readability.ts +306 -5
  17. package/src/agent/tools/webfetch/tool.ts +45 -2
  18. package/src/agent/tools/webfetch/types.ts +7 -0
  19. package/src/agent/turn-runner.ts +7 -3
  20. package/src/bundled-plugins/github-cli-auth/gh-command.ts +187 -8
  21. package/src/bundled-plugins/memory/dreaming.ts +3 -2
  22. package/src/bundled-plugins/reviewer/reviewer.ts +32 -5
  23. package/src/bundled-plugins/reviewer/skills/code-review.ts +5 -3
  24. package/src/bundled-plugins/reviewer/skills/doc-review.ts +1 -1
  25. package/src/bundled-plugins/reviewer/skills/plan-review.ts +1 -1
  26. package/src/channels/github-review-verdict-coordinator.ts +23 -5
  27. package/src/channels/router.ts +15 -5
  28. package/src/cli/inspect.ts +2 -2
  29. package/src/container/start.ts +16 -0
  30. package/src/git/resolve-identity.ts +66 -0
  31. package/src/git/run.ts +2 -0
  32. package/src/git/system-commit.ts +2 -2
  33. package/src/inspect/item-list.ts +2 -11
  34. package/src/inspect/session-list.ts +29 -15
  35. package/src/plugin/types.ts +0 -10
  36. package/src/run/channel-session-factory.ts +3 -1
  37. package/src/run/index.ts +29 -29
  38. package/src/run/subagent-coalescing.ts +24 -0
  39. package/src/sandbox/env-exposure.ts +20 -7
  40. package/src/server/index.ts +4 -1
  41. package/src/skills/typeclaw-channel-github/SKILL.md +10 -10
  42. package/src/skills/typeclaw-channel-instagram/SKILL.md +1 -1
  43. package/src/skills/typeclaw-channel-kakaotalk/SKILL.md +1 -1
  44. package/src/skills/typeclaw-channel-line/SKILL.md +1 -1
@@ -1286,6 +1286,10 @@ export type SendSource = 'tool' | 'system'
1286
1286
 
1287
1287
  export type SendOptions = {
1288
1288
  source?: SendSource
1289
+ // Apply tool-send accounting to the originating conversation while delivering
1290
+ // elsewhere. The outbound target remains unchanged; only per-turn cap/dedup,
1291
+ // output bookkeeping, and continuation state use this key.
1292
+ accountingTarget?: ChannelKey
1289
1293
  // Classifies what the human saw, independently of which router path sent it.
1290
1294
  // Tool calls omit this: substantive text is the default, while the shared
1291
1295
  // multilingual willingness detector recognizes status updates. System paths
@@ -4601,14 +4605,20 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
4601
4605
  if (!flood.ok) return { ok: false, error: OUTBOUND_FLOOD_ERROR, code: 'outbound-flood' }
4602
4606
  }
4603
4607
 
4604
- const keyId = channelKeyId({
4608
+ const accountingTarget = opts?.accountingTarget ?? {
4605
4609
  adapter: msg.adapter,
4606
4610
  workspace: msg.workspace,
4607
4611
  chat: msg.chat,
4608
4612
  thread: msg.thread ?? null,
4609
- })
4613
+ }
4614
+ const deliveryMatchesAccounting =
4615
+ accountingTarget.adapter === msg.adapter &&
4616
+ accountingTarget.workspace === msg.workspace &&
4617
+ accountingTarget.chat === msg.chat &&
4618
+ accountingTarget.thread === (msg.thread ?? null)
4619
+ const keyId = channelKeyId(accountingTarget)
4610
4620
  const live = liveSessions.get(keyId)
4611
- const sendKey = consecutiveSendKey(msg.chat, msg.thread)
4621
+ const sendKey = consecutiveSendKey(accountingTarget.chat, accountingTarget.thread)
4612
4622
  // Tool-source sends consume the captured quote candidate exactly
4613
4623
  // once per turn — the intervening-observed check runs HERE against
4614
4624
  // the live buffer so the relevant signal is actual channel chatter
@@ -4618,7 +4628,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
4618
4628
  // before the model's own first reply lands. Even when the decision
4619
4629
  // returns null (nothing intervened), the candidate is cleared — a
4620
4630
  // multi-part reply must not retroactively anchor chunk 2.
4621
- if (live && source === 'tool' && live.pendingQuoteCandidate !== null) {
4631
+ if (live && deliveryMatchesAccounting && source === 'tool' && live.pendingQuoteCandidate !== null) {
4622
4632
  const quoteCandidate = refreshQuoteCandidate(live.pendingQuoteCandidate, live.contextBuffer)
4623
4633
  const anchor = decideQuoteAnchor(quoteCandidate, now(), options.configForAdapter(msg.adapter))
4624
4634
  if (anchor !== null) {
@@ -4713,7 +4723,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
4713
4723
  // The adapter needs the typing anchor to clear a flat-DM status (msg.thread
4714
4724
  // is null there, so a thread-keyed clear would no-op). Kept off msg.thread
4715
4725
  // to leave reply threading untouched.
4716
- if (live?.currentTurnTypingThread != null && msg.typingThread === undefined) {
4726
+ if (live?.currentTurnTypingThread != null && deliveryMatchesAccounting && msg.typingThread === undefined) {
4717
4727
  msg = { ...msg, typingThread: live.currentTurnTypingThread }
4718
4728
  }
4719
4729
 
@@ -344,10 +344,10 @@ function itemHint(item: ViewerItem): { hint: string } {
344
344
  return { hint: '(no prompt)' }
345
345
  }
346
346
 
347
- function sessionRowLabel(s: SessionSummary): string {
347
+ export function sessionRowLabel(s: SessionSummary): string {
348
348
  const id = shortSessionId(s.sessionId)
349
349
  const label = s.origin === null ? '(unknown origin)' : originLabel(s.origin)
350
- const when = s.live === true ? c.green('live · replying') : c.dim(formatRelative(s.mtimeMs))
350
+ const when = s.live === true ? c.green('live') : c.dim(formatRelative(s.mtimeMs))
351
351
  return `${c.cyan(id)} ${label} ${when}`
352
352
  }
353
353
 
@@ -8,6 +8,7 @@ import { migrateAgentMessengerConfigDir, resolveAgentMessengerConfigPolicy } fro
8
8
  import { expandMountPath, loadConfigSync, withDefaultPlugins, type Config, type PortForward } from '@/config'
9
9
  import { applyBoundGcConfig } from '@/git/bound-gc-config'
10
10
  import { commitGitignoreWithUntracks, untrackTrulyIgnoredFiles } from '@/git/reconcile-ignored'
11
+ import { resolveGitIdentity, type GitIdentity } from '@/git/resolve-identity'
11
12
  import { commitSystemFile as commitSystemFileShared } from '@/git/system-commit'
12
13
  import { send as sendToDaemon } from '@/hostd/client'
13
14
  import { ensureModels as ensureHostModels } from '@/hostd/models'
@@ -92,6 +93,7 @@ export type PlanStartOptions = {
92
93
  // POSIX identity whose ownership bind-mounted runtime writes must retain.
93
94
  // Omitted when unavailable (native Windows and unusual JS hosts).
94
95
  hostIdentity?: { uid: number; gid: number } | null
96
+ gitIdentity?: GitIdentity | null
95
97
  }
96
98
 
97
99
  export type HostDaemonControl = {
@@ -703,6 +705,7 @@ export async function planStart({
703
705
  tuiToken = null,
704
706
  platform = process.platform,
705
707
  hostIdentity = currentHostIdentity(),
708
+ gitIdentity,
706
709
  }: PlanStartOptions): Promise<StartPlan> {
707
710
  const containerName = containerNameFromCwd(cwd)
708
711
  const imageTag = imageTagFromCwd(cwd)
@@ -856,6 +859,19 @@ export async function planStart({
856
859
  if (existsSync(join(cwd, ENV_FILE))) {
857
860
  runArgs.push('--env-file', join(cwd, ENV_FILE))
858
861
  }
862
+ const resolvedGitIdentity = gitIdentity === undefined ? await resolveGitIdentity(cwd) : gitIdentity
863
+ if (resolvedGitIdentity !== null) {
864
+ runArgs.push(
865
+ '-e',
866
+ `GIT_AUTHOR_NAME=${resolvedGitIdentity.name}`,
867
+ '-e',
868
+ `GIT_AUTHOR_EMAIL=${resolvedGitIdentity.email}`,
869
+ '-e',
870
+ `GIT_COMMITTER_NAME=${resolvedGitIdentity.name}`,
871
+ '-e',
872
+ `GIT_COMMITTER_EMAIL=${resolvedGitIdentity.email}`,
873
+ )
874
+ }
859
875
  const agentMessengerPolicy = resolveAgentMessengerConfigPolicy(cwd)
860
876
  if (agentMessengerPolicy.override === null) {
861
877
  runArgs.push('-e', `AGENT_MESSENGER_CONFIG_DIR=${agentMessengerPolicy.containerDir}`)
@@ -0,0 +1,66 @@
1
+ import { resolveAgentGit } from './resolve-agent-git'
2
+ import { runGit } from './run'
3
+
4
+ export type GitIdentity = { name: string; email: string }
5
+
6
+ const GIT_CONFIG_ENV = {
7
+ GIT_CONFIG_GLOBAL: '/dev/null',
8
+ GIT_CONFIG_NOSYSTEM: '1',
9
+ GIT_TERMINAL_PROMPT: '0',
10
+ } as const
11
+
12
+ const GIT_REPOSITORY_ENV_NAMES = new Set([
13
+ 'GIT_COMMON_DIR',
14
+ 'GIT_DIR',
15
+ 'GIT_INDEX_FILE',
16
+ 'GIT_OBJECT_DIRECTORY',
17
+ 'GIT_WORK_TREE',
18
+ ])
19
+
20
+ export async function resolveGitIdentity(cwd: string): Promise<GitIdentity | null> {
21
+ const repo = resolveAgentGit(cwd)
22
+ if (repo === null) return null
23
+
24
+ const values = await readRepositoryIdentity(cwd, repo.gitArgs)
25
+ const name = values.get('user.name')?.at(-1)?.trim() || null
26
+ const email = values.get('user.email')?.at(-1)?.trim() || null
27
+ return name !== null && email !== null ? { name, email } : null
28
+ }
29
+
30
+ async function readRepositoryIdentity(cwd: string, gitArgs: readonly string[]): Promise<Map<string, string[]>> {
31
+ try {
32
+ const result = await runGit(Bun, cwd, [...gitArgs, 'config', '--null', '--get-regexp', '^user\\.(name|email)$'], {
33
+ env: { ...withoutGitOverrides(process.env), ...GIT_CONFIG_ENV },
34
+ })
35
+ if (result.exitCode !== 0) return new Map()
36
+ return parseNullConfigEntries(result.stdout)
37
+ } catch {
38
+ return new Map()
39
+ }
40
+ }
41
+
42
+ function parseNullConfigEntries(output: string): Map<string, string[]> {
43
+ const values = new Map<string, string[]>()
44
+ for (const entry of output.split('\0')) {
45
+ if (entry.length === 0) continue
46
+ const separator = entry.indexOf('\n')
47
+ if (separator < 0) continue
48
+ const key = entry.slice(0, separator)
49
+ const value = entry.slice(separator + 1)
50
+ const existing = values.get(key)
51
+ if (existing === undefined) values.set(key, [value])
52
+ else existing.push(value)
53
+ }
54
+ return values
55
+ }
56
+
57
+ function withoutGitOverrides(env: NodeJS.ProcessEnv): NodeJS.ProcessEnv {
58
+ return Object.fromEntries(
59
+ Object.entries(env).filter(([name]) => {
60
+ const normalized = name.toUpperCase()
61
+ return !normalized.startsWith('GIT_CONFIG') && !GIT_REPOSITORY_ENV_NAMES.has(normalized)
62
+ }),
63
+ )
64
+ }
65
+
66
+ export const _internal = { withoutGitOverrides }
package/src/git/run.ts CHANGED
@@ -33,10 +33,12 @@ export async function runGit(
33
33
  bun: { spawn: typeof Bun.spawn },
34
34
  cwd: string,
35
35
  args: readonly string[],
36
+ options: { env?: NodeJS.ProcessEnv } = {},
36
37
  ): Promise<RunGitResult> {
37
38
  const proc = bun.spawn({
38
39
  cmd: ['git', ...hooklessGitArgs(args)],
39
40
  cwd,
41
+ env: options.env,
40
42
  stdout: 'pipe',
41
43
  stderr: 'pipe',
42
44
  })
@@ -4,8 +4,8 @@ import { resolveAgentGit } from './resolve-agent-git'
4
4
  // Commits TypeClaw-owned tracked files (.gitignore, package.json,
5
5
  // typeclaw.json) if any are dirty in git. Skips silently when the agent
6
6
  // folder is not a git repo, when Bun is unavailable, or when every named
7
- // file is clean. Uses the user's global git config for authorship —
8
- // TypeClaw does not impersonate the user here.
7
+ // file is clean. Uses Git's ambient identity: host config in host-stage calls,
8
+ // or the agent repo identity injected into the container process at start.
9
9
  //
10
10
  // Accepts a single file or an array; the array form produces a single
11
11
  // atomic commit covering all listed paths (used for migrations that touch
@@ -1,7 +1,5 @@
1
- import type { LiveSessionPayload } from '@/shared'
2
-
3
1
  import type { ViewerItem } from './item'
4
- import { listSessions, type ListSessionsOptions, mergeLiveSessions, type SessionSummary } from './session-list'
2
+ import { listSessions, type ListSessionsOptions, type SessionSummary } from './session-list'
5
3
 
6
4
  export type ListViewerItemsOptions = ListSessionsOptions & {
7
5
  containerRunning: boolean
@@ -16,9 +14,6 @@ export type ListViewerItemsOptions = ListSessionsOptions & {
16
14
  // (most-recent) tui transcript — and any older tui transcript the heuristic
17
15
  // would otherwise promote — must NOT be offered as a writable live row.
18
16
  allowWritable?: boolean
19
- // Registry sessions not yet flushed to disk, fetched by the CLI over the
20
- // /inspect WS. The lib layer stays I/O-free; the caller owns the connection.
21
- liveSessions?: LiveSessionPayload[]
22
17
  }
23
18
 
24
19
  export type ViewerList = {
@@ -34,11 +29,7 @@ export type ViewerList = {
34
29
  // `logs` row is appended last (container stdout, available offline) so it sits
35
30
  // below the divider in the picker.
36
31
  export async function listViewerItems(opts: ListViewerItemsOptions): Promise<ViewerList> {
37
- const diskSessions = await listSessions(opts)
38
- const sessions =
39
- opts.liveSessions !== undefined && opts.liveSessions.length > 0
40
- ? mergeLiveSessions(diskSessions, opts.liveSessions)
41
- : diskSessions
32
+ const sessions = await listSessions(opts)
42
33
  const allowWritable = opts.interactive && opts.allowWritable !== false
43
34
  const writableSessionId = opts.containerRunning && allowWritable ? pickWritableSession(sessions) : null
44
35
 
@@ -14,10 +14,9 @@ export type SessionSummary = {
14
14
  mtimeMs: number
15
15
  origin: MinimalSessionOrigin | null
16
16
  firstPrompt: string | null
17
- // True only for a registry-derived session with no .jsonl on disk yet (a
18
- // reply is in flight). Disk sessions leave this undefined. Selecting one tails
19
- // live-only: streamSessionEvents replays an empty file, then the WS delivers
20
- // events as they happen.
17
+ // True only for a registered session with no .jsonl on disk yet. Registration
18
+ // means the session is warm, not that a reply is currently in flight. Disk
19
+ // sessions leave this undefined.
21
20
  live?: boolean
22
21
  }
23
22
 
@@ -26,6 +25,7 @@ export type ListSessionsOptions = {
26
25
  limit?: number
27
26
  sinceMs?: number
28
27
  onWarn?: (msg: string) => void
28
+ liveSessions?: LiveSessionPayload[]
29
29
  }
30
30
 
31
31
  // pi-coding-agent writes session files as `${ISO_TIMESTAMP}_${SESSION_ID}.jsonl`,
@@ -72,17 +72,23 @@ type StatEntry = { path: string; basename: string; sessionId: string; mtimeMs: n
72
72
  // Split from listSessions so resolveSession can match ids first and peek only the
73
73
  // candidates, instead of reading every file body on disk. Reads no file content.
74
74
  async function statSessionFiles(opts: ListSessionsOptions): Promise<StatEntry[]> {
75
+ return (await scanSessionFiles(opts)).eligible
76
+ }
77
+
78
+ async function scanSessionFiles(
79
+ opts: ListSessionsOptions,
80
+ ): Promise<{ eligible: StatEntry[]; onDiskSessionIds: Set<string> }> {
75
81
  const entries = await readSessionFiles(opts.sessionsDir, opts.onWarn)
76
82
  const withStats = await mapConcurrent(entries, SESSION_IO_CONCURRENCY, async (entry) => {
77
83
  const s = await safeStat(entry.path)
78
84
  if (s === null) return null
79
85
  const mtimeMs = s.mtimeMs
80
- if (opts.sinceMs !== undefined && mtimeMs < opts.sinceMs) return null
81
86
  return { ...entry, mtimeMs }
82
87
  })
83
88
  const valid = withStats.filter((v): v is StatEntry => v !== null)
84
- valid.sort((a, b) => b.mtimeMs - a.mtimeMs)
85
- return valid
89
+ const eligible = opts.sinceMs === undefined ? valid : valid.filter((entry) => entry.mtimeMs >= opts.sinceMs!)
90
+ eligible.sort((a, b) => b.mtimeMs - a.mtimeMs)
91
+ return { eligible, onDiskSessionIds: new Set(valid.map((entry) => entry.sessionId)) }
86
92
  }
87
93
 
88
94
  async function summarizeEntry(entry: StatEntry, onWarn?: (msg: string) => void): Promise<SessionSummary> {
@@ -98,18 +104,25 @@ async function summarizeEntry(entry: StatEntry, onWarn?: (msg: string) => void):
98
104
  }
99
105
 
100
106
  export async function listSessions(opts: ListSessionsOptions): Promise<SessionSummary[]> {
101
- const valid = await statSessionFiles(opts)
102
- const limited = opts.limit !== undefined ? valid.slice(0, opts.limit) : valid
103
- return mapConcurrent(limited, SESSION_IO_CONCURRENCY, (entry) => summarizeEntry(entry, opts.onWarn))
107
+ const { eligible, onDiskSessionIds } = await scanSessionFiles(opts)
108
+ const limited = opts.limit !== undefined ? eligible.slice(0, opts.limit) : eligible
109
+ const disk = await mapConcurrent(limited, SESSION_IO_CONCURRENCY, (entry) => summarizeEntry(entry, opts.onWarn))
110
+ if (opts.liveSessions === undefined || opts.liveSessions.length === 0) return disk
111
+ return mergeLiveSessions(disk, opts.liveSessions, { onDiskSessionIds, limit: opts.limit })
104
112
  }
105
113
 
106
114
  // Overlay container-registry sessions onto the disk listing. A live session
107
- // already flushed to disk (post-reply) is dropped from the overlay — the disk
115
+ // already flushed to disk is dropped from the overlay — the disk
108
116
  // summary wins, carrying its real mtime and prompt preview. Only sessions with
109
117
  // no .jsonl yet become synthetic live rows, sorted to the top by registration
110
- // time so an in-flight reply surfaces above settled history.
111
- export function mergeLiveSessions(disk: SessionSummary[], live: LiveSessionPayload[]): SessionSummary[] {
112
- const onDisk = new Set(disk.map((s) => s.sessionId))
118
+ // time. The final limit applies after merging, so registry-only rows displace
119
+ // older history rather than expanding the picker.
120
+ export function mergeLiveSessions(
121
+ disk: SessionSummary[],
122
+ live: LiveSessionPayload[],
123
+ opts: { onDiskSessionIds?: ReadonlySet<string>; limit?: number } = {},
124
+ ): SessionSummary[] {
125
+ const onDisk = opts.onDiskSessionIds ?? new Set(disk.map((s) => s.sessionId))
113
126
  const liveOnly = live
114
127
  .filter((l) => !onDisk.has(l.sessionId))
115
128
  .map(
@@ -123,7 +136,8 @@ export function mergeLiveSessions(disk: SessionSummary[], live: LiveSessionPaylo
123
136
  live: true,
124
137
  }),
125
138
  )
126
- return [...liveOnly, ...disk].sort((a, b) => b.mtimeMs - a.mtimeMs)
139
+ const merged = [...liveOnly, ...disk].sort((a, b) => b.mtimeMs - a.mtimeMs)
140
+ return opts.limit !== undefined ? merged.slice(0, opts.limit) : merged
127
141
  }
128
142
 
129
143
  export type ResolveResult =
@@ -65,19 +65,9 @@ export type RunSession = (override?: { userPrompt?: string }) => Promise<void>
65
65
  // so a new shared field surfaces on both types in one edit. See
66
66
  // `SubagentShared`'s doc-comment for the regression history.
67
67
  //
68
- // `inFlightKey` lives here only (not on the shared shape) because it is
69
- // consumed exclusively by the `SubagentConsumer` via the
70
- // `pluginSubagentByName` map, which holds the original plugin reference —
71
- // the registry-flowing shim never needs to carry it.
72
68
  export type Subagent<P = unknown> = SubagentShared<P> & {
73
69
  tools?: BuiltinToolRef[]
74
70
  customTools?: Tool<any>[]
75
- // Coalescing key for the SubagentConsumer's in-flight set. Default is the
76
- // subagent name alone (only one instance of the subagent runs at a time).
77
- // Override to allow per-payload concurrency, e.g. memory-logger keyed by
78
- // parentSessionId so different parent sessions run in parallel while
79
- // duplicate runs against the same session deduplicate.
80
- inFlightKey?: (payload: P) => string
81
71
  }
82
72
 
83
73
  // Cron job map keys are local; the runtime prefixes with `__plugin_<plugin-name>_`
@@ -6,7 +6,7 @@ import { createSession as defaultCreateSession } from '@/agent'
6
6
  import type { LiveSessionRegistry } from '@/agent/live-sessions'
7
7
  import type { LiveSubagentRegistry } from '@/agent/live-subagents'
8
8
  import { sessionMetaPayload } from '@/agent/session-meta'
9
- import type { CreateSessionForSubagent, SubagentRegistry } from '@/agent/subagents'
9
+ import type { CreateSessionForSubagent, SubagentCoalescer, SubagentRegistry } from '@/agent/subagents'
10
10
  import { capJsonlFileInPlace } from '@/bundled-plugins/tool-result-cap/cap-jsonl'
11
11
  import type { CapOptions } from '@/bundled-plugins/tool-result-cap/cap-result'
12
12
  import type { CreateSessionForChannel, ChannelRouter } from '@/channels'
@@ -70,6 +70,7 @@ export type BuildChannelSessionFactoryDeps = {
70
70
  // createSessionForSubagent, which needs channelManager.router. Same shape
71
71
  // as `getChannelRouter` above.
72
72
  liveSubagentRegistry?: LiveSubagentRegistry
73
+ subagentCoalescer?: SubagentCoalescer
73
74
  subagentRegistry?: SubagentRegistry
74
75
  getCreateSessionForSubagent?: () => CreateSessionForSubagent
75
76
  liveSessionRegistry?: LiveSessionRegistry
@@ -136,6 +137,7 @@ export function buildChannelSessionFactory(deps: BuildChannelSessionFactoryDeps)
136
137
  ...(deps.permissions !== undefined ? { permissions: deps.permissions } : {}),
137
138
  ...(deps.reloadRoles !== undefined ? { reloadRoles: deps.reloadRoles } : {}),
138
139
  ...(deps.liveSubagentRegistry !== undefined ? { liveSubagentRegistry: deps.liveSubagentRegistry } : {}),
140
+ ...(deps.subagentCoalescer !== undefined ? { subagentCoalescer: deps.subagentCoalescer } : {}),
139
141
  ...(deps.subagentRegistry !== undefined ? { subagentRegistry: deps.subagentRegistry } : {}),
140
142
  ...(deps.getCreateSessionForSubagent !== undefined
141
143
  ? { createSessionForSubagent: deps.getCreateSessionForSubagent() }
package/src/run/index.ts CHANGED
@@ -17,6 +17,7 @@ import {
17
17
  invokeSubagent,
18
18
  isSubagentTimeoutError,
19
19
  resolveSubagentProfile,
20
+ SubagentCoalescer,
20
21
  type Subagent as InternalSubagent,
21
22
  type SubagentConsumer,
22
23
  type SubagentRegistry,
@@ -90,6 +91,7 @@ import { installFatalGuard } from './fatal-guard'
90
91
  import { installLlmFetchObserver } from './llm-fetch-observer'
91
92
  import { createPluginRuntime, type PluginRuntime, type PluginSubagentEntry } from './plugin-runtime'
92
93
  import { logResourceReport } from './resource-report'
94
+ import { acquireSubagentCoalesceLease } from './subagent-coalescing'
93
95
 
94
96
  type BunServer = ReturnType<Server['start']>
95
97
 
@@ -439,6 +441,7 @@ async function startAgentRuntime(
439
441
  })
440
442
 
441
443
  const liveSubagentRegistry = new LiveSubagentRegistry()
444
+ const subagentCoalescer = new SubagentCoalescer()
442
445
  const liveSessionRegistry = new LiveSessionRegistry()
443
446
 
444
447
  const channelManager = createChannelManagerFor({
@@ -459,6 +462,7 @@ async function startAgentRuntime(
459
462
  permissions: pluginsLoaded.permissions,
460
463
  reloadRoles: () => reloadRolesFromDisk(cwd),
461
464
  liveSubagentRegistry,
465
+ subagentCoalescer,
462
466
  liveSessionRegistry,
463
467
  subagentRegistry: pluginRuntime.get().subagents,
464
468
  getCreateSessionForSubagent: () => createSessionForSubagent,
@@ -569,6 +573,7 @@ async function startAgentRuntime(
569
573
  ...(entry.pluginSubagent.canSpawnSubagents === true
570
574
  ? {
571
575
  liveSubagentRegistry,
576
+ subagentCoalescer,
572
577
  subagentRegistry: snap.subagents,
573
578
  createSessionForSubagent,
574
579
  allowBackgroundFromSubagent,
@@ -637,17 +642,18 @@ async function startAgentRuntime(
637
642
  getRegistry: () => pluginRuntime.get().subagents,
638
643
  agentDir: cwd,
639
644
  createSessionForSubagent,
640
- inFlightKey: (name, payload) => {
641
- const entry = pluginSubagentByName.get(name)
642
- const fn = entry?.pluginSubagent.inFlightKey
645
+ coalescer: subagentCoalescer,
646
+ inFlightKey: (name, payload, parentSessionId) => {
647
+ const fn = pluginRuntime.get().subagents[name]?.inFlightKey
643
648
  if (fn !== undefined) {
644
649
  try {
645
- return `${name}:${fn(payload)}`
650
+ const key = `${name}:${fn(payload)}`
651
+ return parentSessionId === undefined ? key : `${parentSessionId}:${key}`
646
652
  } catch {
647
- return name
653
+ return parentSessionId === undefined ? name : `${parentSessionId}:${name}`
648
654
  }
649
655
  }
650
- return name
656
+ return parentSessionId === undefined ? name : `${parentSessionId}:${name}`
651
657
  },
652
658
  })
653
659
  registerBootCleanup(() => subagentConsumer.stop())
@@ -755,6 +761,7 @@ async function startAgentRuntime(
755
761
  }
756
762
  : {}),
757
763
  liveSubagentRegistry,
764
+ subagentCoalescer,
758
765
  subagentRegistry: pluginRuntime.get().subagents,
759
766
  createSessionForSubagent,
760
767
  ...containerNameOpt,
@@ -911,23 +918,19 @@ async function startAgentRuntime(
911
918
  // subagent declares one, else just `${name}`. Collisions resolve cleanly
912
919
  // (logged + return) instead of rejecting, because callers from
913
920
  // session.prompt are detached and a colliding spawn is a noop, not an error.
914
- const directSpawnInFlight = new Set<string>()
915
921
  const dispatchSpawnSubagent: CommandSpawnSubagent = async (name, payload, options) => {
916
- const entry = pluginSubagentByName.get(name)
917
- const keyFn = entry?.pluginSubagent.inFlightKey
918
- let coalesceKey = name
919
- if (keyFn !== undefined) {
920
- try {
921
- coalesceKey = `${name}:${keyFn(payload)}`
922
- } catch {
923
- coalesceKey = name
924
- }
925
- }
926
- if (directSpawnInFlight.has(coalesceKey)) {
927
- console.warn(`[subagent] ${coalesceKey}: previous direct spawn still in progress, skipping`)
922
+ const registry = pluginRuntime.get().subagents
923
+ const lease = acquireSubagentCoalesceLease({
924
+ coalescer: subagentCoalescer,
925
+ subagentName: name,
926
+ subagent: registry[name],
927
+ payload,
928
+ ...(options?.parentSessionId !== undefined ? { parentSessionId: options.parentSessionId } : {}),
929
+ })
930
+ if (lease === null) {
931
+ console.warn(`[subagent] ${name}: previous direct spawn still in progress, skipping`)
928
932
  return
929
933
  }
930
- directSpawnInFlight.add(coalesceKey)
931
934
  try {
932
935
  // Resolve the spawning session's role from its origin so the subagent
933
936
  // inherits it. Callers (hooks like session.idle) pass the parent origin
@@ -937,7 +940,6 @@ async function startAgentRuntime(
937
940
  options?.spawnedByOrigin !== undefined
938
941
  ? pluginsLoaded.permissions.resolveRole(options.spawnedByOrigin)
939
942
  : undefined
940
- const registry = pluginRuntime.get().subagents
941
943
  try {
942
944
  await awaitWithSubagentTimeout(
943
945
  invokeSubagent(name, {
@@ -952,18 +954,18 @@ async function startAgentRuntime(
952
954
  ...(options?.spawnedByOrigin !== undefined ? { spawnedByOrigin: options.spawnedByOrigin } : {}),
953
955
  }),
954
956
  name,
955
- coalesceKey,
957
+ lease.key,
956
958
  registry[name]?.timeoutMs,
957
959
  )
958
960
  } catch (err) {
959
961
  if (isSubagentTimeoutError(err)) {
960
- console.warn(`[subagent] ${coalesceKey} timed out after ${err.timeoutMs}ms; releasing coalesce key`)
962
+ console.warn(`[subagent] ${lease.key} timed out after ${err.timeoutMs}ms; releasing coalesce key`)
961
963
  return
962
964
  }
963
965
  throw err
964
966
  }
965
967
  } finally {
966
- directSpawnInFlight.delete(coalesceKey)
968
+ lease.release()
967
969
  }
968
970
  }
969
971
  pluginsLoaded.setSpawnSubagent(dispatchSpawnSubagent)
@@ -1031,6 +1033,7 @@ async function startAgentRuntime(
1031
1033
  commandRunnerFactory,
1032
1034
  tunnelManager,
1033
1035
  liveSubagentRegistry,
1036
+ subagentCoalescer,
1034
1037
  createSessionForSubagent,
1035
1038
  liveSessionRegistry,
1036
1039
  ...containerNameOpt,
@@ -1310,7 +1313,6 @@ type PluginOnlySubagentKeys = Exclude<keyof import('@/plugin').Subagent<any>, ke
1310
1313
  const PLUGIN_ONLY_KEYS_DROPPED_BY_SHIM = {
1311
1314
  tools: true,
1312
1315
  customTools: true,
1313
- inFlightKey: true,
1314
1316
  } satisfies Record<PluginOnlySubagentKeys, true>
1315
1317
  // Reference the table so it's not dead code. The value is a runtime no-op;
1316
1318
  // the load-bearing work is the `satisfies` clause above which forces
@@ -1322,15 +1324,13 @@ function pluginSubagentShim(subagent: import('@/plugin').Subagent<any>): Interna
1322
1324
  // `AgentSessionTools` internal-side; `customTools` similarly differs) are
1323
1325
  // resolved later in `createSessionForSubagent` via the
1324
1326
  // `pluginSubagentByShim` lookup, which recovers the original plugin
1325
- // reference. `inFlightKey` is consumed only by the SubagentConsumer via
1326
- // `pluginSubagentByName`, not through this shim's registry path. Every
1327
- // other plugin-side field lives on `SubagentShared` and is structurally
1327
+ // reference. Every other plugin-side field lives on `SubagentShared` and is structurally
1328
1328
  // assignable to the internal `Subagent`, so a rest-spread carries them
1329
1329
  // verbatim — including `visibility` and `requiresSpecificPermission`,
1330
1330
  // whose silent drop in the previous shim made every plugin-contributed
1331
1331
  // public subagent (scout, explorer, operator) invisible to the
1332
1332
  // `spawn_subagent` tool. The list of keys removed here is enforced
1333
1333
  // exhaustive at compile time by `PLUGIN_ONLY_KEYS_DROPPED_BY_SHIM` above.
1334
- const { tools: _tools, customTools: _customTools, inFlightKey: _inFlightKey, ...shared } = subagent
1334
+ const { tools: _tools, customTools: _customTools, ...shared } = subagent
1335
1335
  return shared
1336
1336
  }
@@ -0,0 +1,24 @@
1
+ import { type Subagent, SubagentCoalescer, subagentCoalesceKey } from '@/agent/subagents'
2
+
3
+ export type SubagentCoalesceLease = {
4
+ key: string
5
+ release: () => void
6
+ }
7
+
8
+ export function acquireSubagentCoalesceLease<P>(options: {
9
+ coalescer: SubagentCoalescer
10
+ subagentName: string
11
+ subagent: Subagent<P> | undefined
12
+ payload: P
13
+ parentSessionId?: string
14
+ }): SubagentCoalesceLease | null {
15
+ const key = subagentCoalesceKey({
16
+ subagentName: options.subagentName,
17
+ payload: options.payload,
18
+ fallbackKey: options.subagentName,
19
+ ...(options.subagent?.inFlightKey !== undefined ? { inFlightKey: options.subagent.inFlightKey } : {}),
20
+ ...(options.parentSessionId !== undefined ? { parentSessionId: options.parentSessionId } : {}),
21
+ })
22
+ if (!options.coalescer.tryAcquire(key)) return null
23
+ return { key, release: () => options.coalescer.release(key) }
24
+ }
@@ -54,6 +54,13 @@ const EXECUTION_CONTROL_ENV_NAMES = new Set<string>([
54
54
 
55
55
  const EXECUTION_CONTROL_ENV_PREFIXES = ['GIT_CONFIG', 'BASH_FUNC_'] as const
56
56
 
57
+ const GIT_IDENTITY_ENV_NAMES = [
58
+ 'GIT_AUTHOR_NAME',
59
+ 'GIT_AUTHOR_EMAIL',
60
+ 'GIT_COMMITTER_NAME',
61
+ 'GIT_COMMITTER_EMAIL',
62
+ ] as const
63
+
57
64
  // Withheld ONLY when the name would compromise sandbox integrity or claim a
58
65
  // host/container-injected runtime token — not for being credential-shaped. `.env`
59
66
  // is the operator's expose-to-the-agent surface: every value they declare there
@@ -66,18 +73,24 @@ function isWithheldEnvName(name: string): boolean {
66
73
  return EXECUTION_CONTROL_ENV_PREFIXES.some((prefix) => name === prefix || name.startsWith(prefix))
67
74
  }
68
75
 
69
- // Every name an operator declared in the `.env` FILE with a non-empty value,
70
- // minus the sandbox-integrity/broker withholds. Eligibility is decided from the
71
- // PARSED `.env` value, never process.env: an empty `.env` line (`X=`) is not an
72
- // operator expose-choice even if hydrateChannelEnvFromSecrets later fills
73
- // process.env[X] from secrets.json. The inherited VALUE is still snapshotted
74
- // from process.env at spawn time.
75
- export function resolveExposableEnvNames(declaredEnv: ReadonlyMap<string, string>): string[] {
76
+ // Every non-empty name declared in `.env`, minus sandbox-integrity/broker
77
+ // withholds, plus the four Git identity names that `typeclaw start` resolves
78
+ // from the agent repository and owns in the container environment. No other
79
+ // process.env-only name is eligible: an empty `.env` line (`X=`) remains hidden
80
+ // even if secrets.json hydration later fills process.env[X]. Inherited VALUES
81
+ // are snapshotted from process.env at spawn time.
82
+ export function resolveExposableEnvNames(
83
+ declaredEnv: ReadonlyMap<string, string>,
84
+ runtimeEnv: Readonly<Record<string, string | undefined>> = {},
85
+ ): string[] {
76
86
  const out: string[] = []
77
87
  for (const [name, fileValue] of declaredEnv) {
78
88
  if (fileValue.length === 0) continue
79
89
  if (isWithheldEnvName(name)) continue
80
90
  out.push(name)
81
91
  }
92
+ for (const name of GIT_IDENTITY_ENV_NAMES) {
93
+ if (runtimeEnv[name]?.length && !out.includes(name)) out.push(name)
94
+ }
82
95
  return out
83
96
  }
@@ -22,7 +22,7 @@ import { promptWithSameRefRetryOnly } from '@/agent/retry-same-ref'
22
22
  import { sessionMetaPayload } from '@/agent/session-meta'
23
23
  import type { SessionOrigin } from '@/agent/session-origin'
24
24
  import { parseSubagentCompletedPayload, renderSubagentCompletionReminder } from '@/agent/subagent-completion-reminder'
25
- import type { CreateSessionForSubagent } from '@/agent/subagents'
25
+ import type { CreateSessionForSubagent, SubagentCoalescer } from '@/agent/subagents'
26
26
  import { TODO_CONTINUATION_SOURCE } from '@/agent/todo/continuation'
27
27
  import {
28
28
  armRestartKickForOrigin,
@@ -135,6 +135,7 @@ export type ServerOptions = {
135
135
  // surface diverges across origin kinds — exactly the gap PR #281 flagged
136
136
  // as out-of-scope follow-up.
137
137
  liveSubagentRegistry?: LiveSubagentRegistry
138
+ subagentCoalescer?: SubagentCoalescer
138
139
  createSessionForSubagent?: CreateSessionForSubagent
139
140
  // Id-keyed registry of live AgentSessions, used by `/inspect` (and any
140
141
  // future read-only session-event consumer) to subscribe to session
@@ -293,6 +294,7 @@ export function createServer({
293
294
  claimController,
294
295
  commandRunnerFactory,
295
296
  liveSubagentRegistry,
297
+ subagentCoalescer,
296
298
  createSessionForSubagent,
297
299
  liveSessionRegistry,
298
300
  }: ServerOptions) {
@@ -538,6 +540,7 @@ export function createServer({
538
540
  ...(containerName !== undefined ? { containerName } : {}),
539
541
  ...(runtimeVersion !== undefined ? { runtimeVersion } : {}),
540
542
  ...(liveSubagentRegistry !== undefined ? { liveSubagentRegistry } : {}),
543
+ ...(subagentCoalescer !== undefined ? { subagentCoalescer } : {}),
541
544
  ...(subagentRegistry !== undefined ? { subagentRegistry } : {}),
542
545
  ...(createSessionForSubagent !== undefined ? { createSessionForSubagent } : {}),
543
546
  })