typeclaw 0.48.9 → 0.48.11

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 (48) hide show
  1. package/package.json +1 -1
  2. package/scripts/apparmor/typeclaw-bwrap +43 -0
  3. package/scripts/verify-apparmor-signals.sh +161 -0
  4. package/scripts/verify-mask-fd-sandbox.sh +176 -0
  5. package/src/agent/index.ts +9 -0
  6. package/src/agent/live-subagents.ts +98 -0
  7. package/src/agent/session-origin.ts +5 -1
  8. package/src/agent/tools/channel-reply.ts +30 -2
  9. package/src/agent/tools/channel-send.ts +19 -2
  10. package/src/agent/tools/spawn-subagent.ts +37 -1
  11. package/src/agent/tools/subagent-cancel.ts +14 -2
  12. package/src/bundled-plugins/backup/README.md +4 -3
  13. package/src/bundled-plugins/backup/runner.ts +125 -32
  14. package/src/bundled-plugins/github-cli-auth/gh-command.ts +106 -9
  15. package/src/bundled-plugins/github-cli-auth/git-command.ts +94 -9
  16. package/src/bundled-plugins/github-cli-auth/index.ts +45 -5
  17. package/src/channels/adapters/github/inbound.ts +210 -27
  18. package/src/channels/adapters/github/index.ts +16 -18
  19. package/src/channels/adapters/github/reconcile-cooldown-store.ts +15 -1
  20. package/src/channels/adapters/github/recover-failed-deliveries.ts +7 -2
  21. package/src/channels/adapters/github/review-submitter.ts +28 -0
  22. package/src/channels/adapters/instagram-continuity-store.ts +141 -0
  23. package/src/channels/adapters/instagram.ts +149 -4
  24. package/src/channels/github-repo.ts +11 -0
  25. package/src/channels/github-review-verdict-coordinator.ts +179 -29
  26. package/src/channels/github-verdict-activity.ts +12 -6
  27. package/src/channels/manager.ts +10 -0
  28. package/src/channels/persistence.ts +28 -2
  29. package/src/channels/router.ts +371 -33
  30. package/src/channels/schema.ts +18 -0
  31. package/src/channels/types.ts +11 -0
  32. package/src/cli/compose.ts +7 -4
  33. package/src/compose/restart.ts +26 -16
  34. package/src/compose/start.ts +24 -14
  35. package/src/config/config.ts +9 -1
  36. package/src/container/restart.ts +4 -0
  37. package/src/container/shared.ts +30 -3
  38. package/src/container/start.ts +137 -56
  39. package/src/doctor/apparmor.ts +101 -0
  40. package/src/doctor/checks.ts +2 -0
  41. package/src/hostd/daemon.ts +40 -17
  42. package/src/init/dockerfile.ts +7 -6
  43. package/src/init/windows-dev-link.ts +34 -2
  44. package/src/run/channel-session-factory.ts +35 -15
  45. package/src/run/index.ts +1 -0
  46. package/src/sandbox/availability.ts +7 -5
  47. package/src/skills/typeclaw-channel-github/SKILL.md +4 -2
  48. package/typeclaw.schema.json +7 -0
@@ -47,9 +47,41 @@ export async function linkWindowsDevTypeclaw(
47
47
  ): Promise<string | null> {
48
48
  const platform = options.platform ?? process.platform
49
49
  if (!isWindows(platform)) return null
50
+ const env = options.env ?? process.env
50
51
  const runLink = options.runBunLink ?? defaultRunBunLink
51
- await runLink(typeclawRoot)
52
- return resolveBunLinkedPackage(TYPECLAW_DEP, options.env ?? process.env) ?? typeclawRoot
52
+ try {
53
+ await runLink(typeclawRoot)
54
+ } catch (error) {
55
+ // `bun link` is not idempotent on Windows. It deletes any existing
56
+ // <globalDir>/node_modules/<name> entry and then creates the junction, but
57
+ // the delete is best-effort (its error is discarded) and the pair is not
58
+ // atomic — so a junction that resists deletion, or a second `bun link`
59
+ // racing the first, dies on EEXIST. Re-running `typeclaw init` from a dev
60
+ // checkout then aborts on a step that had nothing left to do. Swallow the
61
+ // failure ONLY when the end state we wanted is already true: the global
62
+ // entry resolves to THIS checkout. An entry pointing at a different
63
+ // checkout, or no entry at all, still propagates, so a link that genuinely
64
+ // failed is never mistaken for a success.
65
+ if (!isLinkedTo(typeclawRoot, env)) throw error
66
+ }
67
+ return resolveBunLinkedPackage(TYPECLAW_DEP, env) ?? typeclawRoot
68
+ }
69
+
70
+ function isLinkedTo(typeclawRoot: string, env: NodeJS.ProcessEnv): boolean {
71
+ const linked = resolveBunLinkedPackage(TYPECLAW_DEP, env)
72
+ if (linked === null) return false
73
+ // Both sides are realpath'd so a junction target compares equal to the
74
+ // checkout path we were handed, and case-folded because Windows paths are
75
+ // case-insensitive while the two resolutions need not agree on casing.
76
+ return linked.toLowerCase() === canonicalize(typeclawRoot).toLowerCase()
77
+ }
78
+
79
+ function canonicalize(path: string): string {
80
+ try {
81
+ return realpathSync(path)
82
+ } catch {
83
+ return path
84
+ }
53
85
  }
54
86
 
55
87
  async function defaultRunBunLink(cwd: string): Promise<void> {
@@ -89,6 +89,21 @@ function isValidSessionFileBasename(name: string): boolean {
89
89
  return name.endsWith('.jsonl')
90
90
  }
91
91
 
92
+ function errorChainHasCode(error: unknown, expectedCode: string): boolean {
93
+ const seen = new Set<object>()
94
+ let current = error
95
+ while (typeof current === 'object' && current !== null && !seen.has(current)) {
96
+ seen.add(current)
97
+ try {
98
+ if ('code' in current && current.code === expectedCode) return true
99
+ current = 'cause' in current ? current.cause : undefined
100
+ } catch {
101
+ return false
102
+ }
103
+ }
104
+ return false
105
+ }
106
+
92
107
  // The production wiring for channel-routed sessions. Channel inbounds arrive
93
108
  // at the router, the router calls this factory to get an AgentSession, and
94
109
  // the agent uses `channel_send` to reply. If `channelRouter` is missing here
@@ -181,41 +196,46 @@ function tryReopenOrCreate(
181
196
  logger: FactoryLogger,
182
197
  ): SessionManager {
183
198
  if (existingSessionFile === undefined) {
184
- logger.warn(
185
- `[channels] session ${existingSessionId} has no sessionFile (v2 mapping not yet migrated); creating new`,
186
- )
199
+ logger.warn('[channels] persisted session has no session file; creating new')
187
200
  return SessionManager.create(cwd, sessionDir)
188
201
  }
189
202
  if (!isValidSessionFileBasename(existingSessionFile)) {
190
- logger.warn(
191
- `[channels] session ${existingSessionId} has invalid sessionFile (${JSON.stringify(existingSessionFile)}); creating new`,
192
- )
203
+ logger.warn('[channels] persisted session file is invalid; creating new')
193
204
  return SessionManager.create(cwd, sessionDir)
194
205
  }
195
206
  const path = join(sessionDir, existingSessionFile)
207
+ let missingDuringCap = false
196
208
  if (capOptions !== null) {
197
209
  try {
198
210
  const stats = capJsonlFileInPlace(path, capOptions)
199
211
  if (stats.entriesMutated > 0) {
200
212
  logger.info(
201
- `[channels] rehydrate-cap ${existingSessionFile}: entriesMutated=${stats.entriesMutated} imagesReplaced=${stats.imagesReplaced} textsTruncated=${stats.textsTruncated} bytesElided=${stats.bytesElided}`,
213
+ `[channels] rehydrate-cap complete: entriesMutated=${stats.entriesMutated} imagesReplaced=${stats.imagesReplaced} textsTruncated=${stats.textsTruncated} bytesElided=${stats.bytesElided}`,
202
214
  )
203
215
  }
204
216
  } catch (err) {
205
217
  // Capping is best-effort: if the rewrite fails, fall through to the
206
218
  // regular open path so the session still rehydrates uncapped rather
207
- // than being killed by a transient FS error.
208
- const reason = err instanceof Error ? err.message : String(err)
209
- logger.warn(`[channels] rehydrate-cap failed for ${existingSessionFile}: ${reason}; continuing with open`)
219
+ // than being killed by a transient FS error. Missing files are expected
220
+ // during concurrent cleanup; open either creates a fresh transcript or
221
+ // reaches the fallback below.
222
+ if (errorChainHasCode(err, 'ENOENT')) {
223
+ missingDuringCap = true
224
+ } else {
225
+ logger.warn('[channels] rehydrate-cap unavailable; continuing with open')
226
+ }
210
227
  }
211
228
  }
212
229
  try {
213
- return SessionManager.open(path)
230
+ const sessionManager = SessionManager.open(path)
231
+ if (sessionManager.getSessionId() !== existingSessionId && !missingDuringCap) {
232
+ logger.warn('[channels] persisted session was replaced during rehydrate')
233
+ }
234
+ return sessionManager
214
235
  } catch (err) {
215
- const reason = err instanceof Error ? err.message : String(err)
216
- logger.warn(
217
- `[channels] could not rehydrate session ${existingSessionId} from ${existingSessionFile}: ${reason}; creating new`,
218
- )
236
+ if (!errorChainHasCode(err, 'ENOENT')) {
237
+ logger.warn('[channels] persisted session rehydrate failed; creating new')
238
+ }
219
239
  return SessionManager.create(cwd, sessionDir)
220
240
  }
221
241
  }
package/src/run/index.ts CHANGED
@@ -504,6 +504,7 @@ async function startAgentRuntime(
504
504
  .list({ parentSessionId: sessionId })
505
505
  .filter((child) => child.status === 'running' && child.background === true)
506
506
  .map((child) => child.subagentName),
507
+ cancelRunningSubagentsByWorkKey: (workKey, reason) => liveSubagentRegistry.cancelRunningByWorkKey(workKey, reason),
507
508
  onReload: async () => {
508
509
  const { results } = await reloadAllNonDestructive()
509
510
  return formatChannelReloadSummary(results)
@@ -64,11 +64,13 @@ export function _resetBwrapAvailabilityCacheForTests(): void {
64
64
  // --mount --mount-proc`, which mounts a fresh procfs in a new PID namespace.
65
65
  // That mount needs REAL CAP_SYS_ADMIN. `typeclaw start` grants the container
66
66
  // `--cap-add=SYS_ADMIN` when sandbox.realProc is on, but the grant is a no-op
67
- // on runtimes that virtualize or strip caps: rootless Docker (userns-capped
68
- // caps), gVisor/runsc (caps never reach the host kernel), Docker Desktop
69
- // Enhanced Container Isolation (intercepts mount), and AppArmor-enforcing
70
- // hosts (Ubuntu 24.04+ restricts unprivileged userns even with the cap). On
71
- // those the `unshare` fails fast with "Operation not permitted" (exit != 0)
67
+ // on runtimes that virtualize or strip caps: the production entrypoint's
68
+ // non-root UID (empty cap set), rootless Docker (userns-capped caps),
69
+ // gVisor/runsc (caps never reach the host kernel), and Docker Desktop Enhanced
70
+ // Container Isolation (intercepts mount). AppArmor hosts need the configured
71
+ // host-loaded profile before bwrap reaches this strategy probe; selecting
72
+ // apparmor=unconfined alone is insufficient on stock Ubuntu 23.10+. On
73
+ // unsupported runtimes `unshare` fails fast with "Operation not permitted"
72
74
  // before bwrap runs. Probing once at the first sandboxed bash call lets the
73
75
  // consumer fall back to the '--tmpfs /proc' strategy instead of failing every
74
76
  // low-trust bash call — restoring the pre-realProc behavior on unsupported
@@ -117,7 +117,7 @@ The `reviewer` subagent is the analyst; you are the integration layer between it
117
117
 
118
118
  **The reviewer's `<review>` block is the only source of the verdict and the findings.** You do not review the PR yourself. Between spawning the reviewer and reading its result you do **no analysis of this PR** — do not run `gh pr diff`, do not read the changed files to form an opinion, do not draft a verdict. The reviewer runs on the `deep` model precisely so this judgment is not yours to make on the parent model. If you analyze the diff and post your own assessment while the reviewer is still running, you will post one verdict now and the reviewer's (often different) verdict when it completes — **two contradictory reviews on the same PR**, the exact failure this flow exists to prevent. Wait for the reviewer; post what it returns; nothing before that.
119
119
 
120
- **Reply-triggered re-review carrier rule.** Obey the session-origin carrier status before delegating. If you are not the carrier, do not spawn a reviewer or publish findings anywhere; once the carrier's verdict lands, close out only your own thread.
120
+ **Reply-triggered re-review carrier rule.** Obey the session-origin carrier status before delegating. If you are not the carrier, do not spawn a reviewer or publish findings anywhere; stay silent with `skip_response` while waiting, then close out only your own thread once the carrier's verdict lands. A "waiting for the verdict" status comment is process narration, not useful review feedback.
121
121
 
122
122
  **HARD RULE — a review with actionable findings is a formal review, never a flat comment.** If the reviewer returns **one or more** actionable findings (`blocker`/`concern`/`nit`), the ONLY acceptable way to deliver them is a formal review via `POST /pulls/<N>/reviews` (step 4) — `REQUEST_CHANGES`, `COMMENT`, or `APPROVE` per the verdict, with the line-anchored findings in `comments[]`. You may **never** flatten those findings into a `channel_reply` or a top-level issue comment, **even when** the `gh api` call fails. A 422 means an anchor is wrong (almost always a `line` not in the diff): re-anchor it or move that one finding into the top-level review `body`, then resubmit the formal review — do **not** abandon the formal review and post prose instead. A flat "## Review … two blockers" comment is a bug, not a fallback: it strands the findings without line anchors and is the exact failure this rule exists to prevent. The flat/issue-comment path is reserved for the **zero-actionable-findings** branch only (see below). **Narrow exception:** when `post_github_review` finds that this bot's identical `CHANGES_REQUESTED` verdict is already effective, the tool itself converts the redundant submission into one substantive root PR comment while the existing formal block remains authoritative. This is a successful tool-managed fallback, not permission to replace a failed or invalid formal review manually. **That conversion fires at most once per pull request per head.** If another session already landed it — a sibling thread session of the same PR is the usual case — your call is denied outright instead, and the denial says the prior verdict is still live. That denial is final: the findings for this head have already been published by the sibling, so **stand down and close out only your own thread**. Do not re-post them as a `channel_reply`, a top-level comment, or a reply in your thread; the HARD RULE above applies with full force to this case. If you genuinely cannot land a formal review after fixing anchors, say so plainly and post nothing that claims a review happened — silence beats a false receipt.
123
123
 
@@ -189,7 +189,7 @@ The `reviewer` subagent is the analyst; you are the integration layer between it
189
189
 
190
190
  **Operator approval policy.** If the inbound carries a note that PR approval is disabled (`channels.github.review.approve: false` — the adapter appends "Operator policy: PR approval is disabled for this agent" to the message), you must **not** submit an `APPROVE`. Map an `approve` verdict to `COMMENT` instead: post the same `<summary>` and all inline `comments[]` as a `COMMENT` review, just without the formal approval. `request-changes` and `comment` verdicts are unaffected (they never approve). Absent that note, approval is enabled and the table above applies unchanged.
191
191
 
192
- **Re-review.** On a reply-triggered re-review round, obey the session-origin carrier status. If you are **not** the carrier, do not spawn a reviewer, do not publish findings anywhere, and close out only your own thread once the carrier's verdict lands. If step 1 established this is a re-review (an unresolved blocking obligation of yours — a formal `CHANGES_REQUESTED` **or** an unretracted flat-comment blocker), the result MUST clear or re-assert that block. The only top-level-comment exception is the tool-managed duplicate fallback described above: the existing identical `CHANGES_REQUESTED` already re-asserts the formal block, so the new summary/findings may be added as one root comment without posting another blocking review — once per head. If a sibling session already landed that comment, your attempt is denied and the block stands re-asserted by both the formal review and the sibling's comment; discharge your obligation by closing out your own thread, not by publishing again. The clearing mechanics depend on which form the prior block took:
192
+ **Re-review.** On a reply-triggered re-review round, obey the session-origin carrier status. If you are **not** the carrier, do not spawn a reviewer or publish findings anywhere; stay silent with `skip_response` while waiting, then close out only your own thread in one participant-facing message once the carrier's verdict lands. Never narrate the carrier, round, session, verdict registration, or sticky state into the PR. If step 1 established this is a re-review (an unresolved blocking obligation of yours — a formal `CHANGES_REQUESTED` **or** an unretracted flat-comment blocker), the result MUST clear or re-assert that block. The only top-level-comment exception is the tool-managed duplicate fallback described above: the existing identical `CHANGES_REQUESTED` already re-asserts the formal block, so the new summary/findings may be added as one root comment without posting another blocking review — once per head. If a sibling session already landed that comment, your attempt is denied and the block stands re-asserted by both the formal review and the sibling's comment; discharge your obligation by closing out your own thread, not by publishing again. The clearing mechanics depend on which form the prior block took:
193
193
  - **Prior block was a formal `CHANGES_REQUESTED`.** It is sticky: **only** a fresh `APPROVE` from you, or a dismissal of your prior review, clears it. A plain issue comment does **not** clear it, and — critically — **neither does a `COMMENT` review.**
194
194
  - **Prior block was a flat comment** (no formal `CHANGES_REQUESTED` exists). There is no sticky GitHub state to clear, but the obligation is still yours to discharge as a **formal** review so the verdict finally lands as review state: submit `APPROVE` (resolved, approval enabled) or `REQUEST_CHANGES` (not resolved). Do not discharge a flat-comment block with another flat comment — that re-strands the verdict, the original bug.
195
195
 
@@ -242,6 +242,8 @@ The bundled `agent-browser` is **not** for PR reviews — `gh api` is faster and
242
242
 
243
243
  A review you posted leaves inline comment threads open on the PR. When one of **your** threads is addressed — the author pushed a fix, or replied that they handled it — close it out by **resolving the thread**. Leaving it open after the concern is settled reads as if you never noticed; a resolved thread is the signal that the loop is closed.
244
244
 
245
+ **No process narration.** A PR participant needs the technical outcome, not your coordination machinery. While another carrier is working, stay silent with `skip_response`; do not post that you are waiting or will clean up later. Once actionable, use one participant-facing message: acknowledge and resolve if addressed, or state the specific technical reason it remains open.
246
+
245
247
  **The base principle: whoever opened the thread closes it.** Resolve only threads whose root comment **you** authored. Never resolve a human reviewer's thread on your behalf — that erases their open question. The thread you can resolve is the one you started; the inbound that brings you here is a **review-thread reply on `pr:N` with `thread` set**, replying inside a thread you opened.
246
248
 
247
249
  > **Thread cleanup is not the same as discharging a PR-level block.** Resolving an inline thread closes that one thread; it carries **no** review state and does **not** clear a PR-level blocking obligation (a sticky `CHANGES_REQUESTED`, or a flat blocker you authored on the PR conversation). Those are two separate duties. If triage #1 found a live PR-level block, that inbound is a **re-review** and the PR review flow wins over this section — you owe a formal `APPROVE`/`REQUEST_CHANGES`, and resolving threads (or a chat ✅) must **not** be your final response. Reach this section only for a thread-scoped reply on a PR where you owe no PR-level verdict (triage #1 came back clean). When in doubt, re-run triage #1 first.
@@ -1020,6 +1020,7 @@
1020
1020
  "discussion_comment.created",
1021
1021
  "issues.opened",
1022
1022
  "pull_request.opened",
1023
+ "pull_request.converted_to_draft",
1023
1024
  "pull_request.ready_for_review",
1024
1025
  "pull_request.review_requested",
1025
1026
  "pull_request.review_request_removed",
@@ -2567,12 +2568,18 @@
2567
2568
  },
2568
2569
  "sandbox": {
2569
2570
  "default": {
2571
+ "apparmorProfile": "unconfined",
2570
2572
  "realProc": false,
2571
2573
  "writablePaths": [],
2572
2574
  "symlinks": []
2573
2575
  },
2574
2576
  "type": "object",
2575
2577
  "properties": {
2578
+ "apparmorProfile": {
2579
+ "default": "unconfined",
2580
+ "type": "string",
2581
+ "pattern": "^[A-Za-z0-9_.-]+$"
2582
+ },
2576
2583
  "realProc": {
2577
2584
  "default": false,
2578
2585
  "type": "boolean"