typeclaw 0.43.1 → 0.45.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 (86) hide show
  1. package/README.md +1 -1
  2. package/auth.schema.json +92 -0
  3. package/package.json +7 -6
  4. package/secrets.schema.json +92 -0
  5. package/src/agent/index.ts +25 -2
  6. package/src/agent/model-fallback.ts +59 -40
  7. package/src/agent/multimodal/look-at.ts +29 -10
  8. package/src/agent/plugin-tools.ts +9 -4
  9. package/src/agent/provider-error.ts +71 -18
  10. package/src/agent/retry-same-ref.ts +139 -0
  11. package/src/agent/session-origin.ts +1 -0
  12. package/src/agent/subagents.ts +6 -2
  13. package/src/agent/tools/channel-edit.ts +144 -0
  14. package/src/agent/tools/channel-fetch-attachment.ts +51 -8
  15. package/src/agent/tools/channel-reply.ts +41 -18
  16. package/src/agent/tools/channel-send.ts +82 -13
  17. package/src/agent/tools/curl-impersonate.ts +40 -1
  18. package/src/agent/tools/webfetch/fetch.ts +86 -3
  19. package/src/agent/tools/webfetch/tool.ts +26 -3
  20. package/src/agent/tools/webfetch/types.ts +8 -0
  21. package/src/agent/turn-runner.ts +65 -36
  22. package/src/bundled-plugins/agent-browser/skills/agent-browser/SKILL.md +28 -11
  23. package/src/bundled-plugins/github-cli-auth/gh-review-detect.ts +101 -1
  24. package/src/bundled-plugins/github-cli-auth/review-recorder.ts +44 -3
  25. package/src/bundled-plugins/guard/policies/managed-config.ts +20 -4
  26. package/src/bundled-plugins/memory/README.md +9 -9
  27. package/src/bundled-plugins/memory/index.ts +40 -9
  28. package/src/bundled-plugins/reviewer/skills/code-review.ts +22 -2
  29. package/src/channels/adapters/discord-bot-edit.ts +49 -0
  30. package/src/channels/adapters/discord-bot.ts +5 -0
  31. package/src/channels/adapters/discord-edit.ts +51 -0
  32. package/src/channels/adapters/discord.ts +4 -0
  33. package/src/channels/adapters/github/inbound.ts +20 -14
  34. package/src/channels/adapters/github/review-thread-resolver.ts +38 -4
  35. package/src/channels/adapters/slack-bot-edit.ts +58 -0
  36. package/src/channels/adapters/slack-bot.ts +18 -6
  37. package/src/channels/adapters/slack-edit.ts +47 -0
  38. package/src/channels/adapters/slack.ts +5 -0
  39. package/src/channels/adapters/teams-classify.ts +144 -0
  40. package/src/channels/adapters/teams-edit.ts +61 -0
  41. package/src/channels/adapters/teams-id-token.ts +112 -0
  42. package/src/channels/adapters/teams-key.ts +32 -0
  43. package/src/channels/adapters/teams.ts +523 -0
  44. package/src/channels/adapters/telegram-bot-edit.ts +51 -0
  45. package/src/channels/adapters/telegram-bot.ts +5 -0
  46. package/src/channels/adapters/webex-bot.ts +5 -0
  47. package/src/channels/adapters/webex-edit.ts +47 -0
  48. package/src/channels/adapters/webex.ts +5 -0
  49. package/src/channels/continuation-willingness.ts +227 -35
  50. package/src/channels/github-review-turn-ledger.ts +43 -0
  51. package/src/channels/index.ts +1 -1
  52. package/src/channels/manager.ts +54 -1
  53. package/src/channels/router.ts +482 -53
  54. package/src/channels/schema.ts +33 -0
  55. package/src/channels/types.ts +36 -0
  56. package/src/cli/channel.ts +92 -4
  57. package/src/cli/hostd.ts +41 -0
  58. package/src/cli/init.ts +58 -1
  59. package/src/config/channels-mutation.ts +9 -1
  60. package/src/cron/index.ts +16 -4
  61. package/src/cron/reloadable.ts +25 -7
  62. package/src/cron/scheduler.ts +4 -0
  63. package/src/cron/schema.ts +143 -35
  64. package/src/doctor/channel-checks.ts +27 -0
  65. package/src/hostd/daemon.ts +23 -3
  66. package/src/hostd/protocol.ts +2 -0
  67. package/src/hostd/teams-renewal-manager.ts +212 -0
  68. package/src/init/checkpoint.ts +1 -1
  69. package/src/init/index.ts +68 -1
  70. package/src/init/run-owner-claim.ts +1 -0
  71. package/src/init/teams-auth.ts +111 -0
  72. package/src/inspect/label.ts +4 -0
  73. package/src/permissions/match-rule.ts +11 -1
  74. package/src/permissions/resolve.ts +1 -0
  75. package/src/role-claim/match-rule.ts +2 -1
  76. package/src/run/index.ts +35 -8
  77. package/src/run/llm-fetch-observer.ts +27 -5
  78. package/src/sandbox/build.ts +12 -0
  79. package/src/sandbox/policy.ts +13 -0
  80. package/src/sandbox/writable-zones.ts +46 -10
  81. package/src/secrets/schema.ts +32 -0
  82. package/src/secrets/teams-renewal.ts +229 -0
  83. package/src/secrets/teams-store.ts +108 -0
  84. package/src/server/command-runner.ts +2 -1
  85. package/src/server/index.ts +2 -1
  86. package/typeclaw.schema.json +163 -3
package/README.md CHANGED
@@ -26,7 +26,7 @@
26
26
 
27
27
  ## Channels — one agent, many inboxes
28
28
 
29
- - 📨 **Supported channels** — Slack, Discord, Telegram, Webex, Instagram, LINE, KakaoTalk, GitHub, and a websocket TUI, driven by the same agent
29
+ - 📨 **Supported channels** — Slack, Discord, Telegram, Webex, Teams, Instagram, LINE, KakaoTalk, GitHub, and a websocket TUI, driven by the same agent
30
30
  - 🔎 **Cross-channel reading** — beyond the conversation it's in, it can read another channel's history, pull a single message by id, or list a workspace's channels on demand, so "check what's going on in #general" or "what do you make of this message?" just works
31
31
  - ✅ **Pull-request review** — treats a GitHub PR as a conversation, reviewing as a participant, with guards against claiming a verdict it didn't actually post and against leaving a PR stranded
32
32
 
package/auth.schema.json CHANGED
@@ -716,6 +716,98 @@
716
716
  "accounts"
717
717
  ]
718
718
  },
719
+ "teams": {
720
+ "type": "object",
721
+ "properties": {
722
+ "currentAccount": {
723
+ "anyOf": [
724
+ {
725
+ "type": "string"
726
+ },
727
+ {
728
+ "type": "null"
729
+ }
730
+ ]
731
+ },
732
+ "accounts": {
733
+ "type": "object",
734
+ "propertyNames": {
735
+ "type": "string"
736
+ },
737
+ "additionalProperties": {
738
+ "type": "object",
739
+ "properties": {
740
+ "account_id": {
741
+ "type": "string"
742
+ },
743
+ "access_token": {
744
+ "type": "string"
745
+ },
746
+ "token_expires_at": {
747
+ "type": "string"
748
+ },
749
+ "account_type": {
750
+ "anyOf": [
751
+ {
752
+ "type": "string",
753
+ "const": "work"
754
+ },
755
+ {
756
+ "type": "string",
757
+ "const": "personal"
758
+ }
759
+ ]
760
+ },
761
+ "region": {
762
+ "anyOf": [
763
+ {
764
+ "type": "string",
765
+ "const": "amer"
766
+ },
767
+ {
768
+ "type": "string",
769
+ "const": "emea"
770
+ },
771
+ {
772
+ "type": "string",
773
+ "const": "apac"
774
+ }
775
+ ]
776
+ },
777
+ "user_name": {
778
+ "type": "string"
779
+ },
780
+ "aad_refresh_token": {
781
+ "type": "string"
782
+ },
783
+ "aad_client_id": {
784
+ "type": "string"
785
+ },
786
+ "aad_tenant_id": {
787
+ "type": "string"
788
+ },
789
+ "created_at": {
790
+ "type": "string"
791
+ },
792
+ "updated_at": {
793
+ "type": "string"
794
+ }
795
+ },
796
+ "required": [
797
+ "account_id",
798
+ "access_token",
799
+ "account_type",
800
+ "created_at",
801
+ "updated_at"
802
+ ]
803
+ }
804
+ }
805
+ },
806
+ "required": [
807
+ "currentAccount",
808
+ "accounts"
809
+ ]
810
+ },
719
811
  "slack": {
720
812
  "type": "object",
721
813
  "properties": {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "typeclaw",
3
- "version": "0.43.1",
3
+ "version": "0.45.0",
4
4
  "homepage": "https://github.com/typeclaw/typeclaw#readme",
5
5
  "bugs": {
6
6
  "url": "https://github.com/typeclaw/typeclaw/issues"
@@ -31,7 +31,7 @@
31
31
  "access": "public"
32
32
  },
33
33
  "scripts": {
34
- "typecheck": "tsgo --noEmit",
34
+ "typecheck": "tsc --noEmit",
35
35
  "lint": "oxlint",
36
36
  "format": "oxfmt --write .",
37
37
  "format:check": "oxfmt --check .",
@@ -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.29.0",
53
+ "agent-messenger": "^2.30.0",
54
54
  "cheerio": "^1.2.0",
55
55
  "citty": "^0.2.2",
56
56
  "cron-parser": "^5.5.0",
@@ -69,12 +69,13 @@
69
69
  "@types/qrcode": "^1.5.6",
70
70
  "@types/sinonjs__fake-timers": "^15.0.1",
71
71
  "@types/turndown": "^5.0.6",
72
- "@typescript/native-preview": "^7.0.0-dev.20260416.1",
72
+ "@typescript/typescript6": "^6.0.2",
73
73
  "oxfmt": "^0.45.0",
74
- "oxlint": "^1.60.0"
74
+ "oxlint": "^1.60.0",
75
+ "typescript": "^7.0.2"
75
76
  },
76
77
  "peerDependencies": {
77
- "typescript": "^5"
78
+ "typescript": "^5 || ^6 || ^7"
78
79
  },
79
80
  "engines": {
80
81
  "bun": ">=1.1.0"
@@ -716,6 +716,98 @@
716
716
  "accounts"
717
717
  ]
718
718
  },
719
+ "teams": {
720
+ "type": "object",
721
+ "properties": {
722
+ "currentAccount": {
723
+ "anyOf": [
724
+ {
725
+ "type": "string"
726
+ },
727
+ {
728
+ "type": "null"
729
+ }
730
+ ]
731
+ },
732
+ "accounts": {
733
+ "type": "object",
734
+ "propertyNames": {
735
+ "type": "string"
736
+ },
737
+ "additionalProperties": {
738
+ "type": "object",
739
+ "properties": {
740
+ "account_id": {
741
+ "type": "string"
742
+ },
743
+ "access_token": {
744
+ "type": "string"
745
+ },
746
+ "token_expires_at": {
747
+ "type": "string"
748
+ },
749
+ "account_type": {
750
+ "anyOf": [
751
+ {
752
+ "type": "string",
753
+ "const": "work"
754
+ },
755
+ {
756
+ "type": "string",
757
+ "const": "personal"
758
+ }
759
+ ]
760
+ },
761
+ "region": {
762
+ "anyOf": [
763
+ {
764
+ "type": "string",
765
+ "const": "amer"
766
+ },
767
+ {
768
+ "type": "string",
769
+ "const": "emea"
770
+ },
771
+ {
772
+ "type": "string",
773
+ "const": "apac"
774
+ }
775
+ ]
776
+ },
777
+ "user_name": {
778
+ "type": "string"
779
+ },
780
+ "aad_refresh_token": {
781
+ "type": "string"
782
+ },
783
+ "aad_client_id": {
784
+ "type": "string"
785
+ },
786
+ "aad_tenant_id": {
787
+ "type": "string"
788
+ },
789
+ "created_at": {
790
+ "type": "string"
791
+ },
792
+ "updated_at": {
793
+ "type": "string"
794
+ }
795
+ },
796
+ "required": [
797
+ "account_id",
798
+ "access_token",
799
+ "account_type",
800
+ "created_at",
801
+ "updated_at"
802
+ ]
803
+ }
804
+ }
805
+ },
806
+ "required": [
807
+ "currentAccount",
808
+ "accounts"
809
+ ]
810
+ },
719
811
  "slack": {
720
812
  "type": "object",
721
813
  "properties": {
@@ -72,7 +72,8 @@ import {
72
72
  import { attachToolNotFoundNudge } from './tool-not-found-nudge'
73
73
  import { createBudgetState, type ToolResultBudget, wrapToolDefinitionWithBudget } from './tool-result-budget'
74
74
  import { createChannelDisengageTool } from './tools/channel-disengage'
75
- import { createChannelFetchAttachmentTool } from './tools/channel-fetch-attachment'
75
+ import { createChannelEditTool } from './tools/channel-edit'
76
+ import { createChannelFetchAttachmentTool, resolveInboxBaseDir } from './tools/channel-fetch-attachment'
76
77
  import { createChannelHistoryTool } from './tools/channel-history'
77
78
  import { createChannelReactTool } from './tools/channel-react'
78
79
  import { createChannelReadTool } from './tools/channel-read'
@@ -390,7 +391,14 @@ export async function createSessionWithDispose(options: CreateSessionOptions = {
390
391
  ...(options.mcpManager ? buildMcpDispatcherToolDefinitions(options.mcpManager) : []),
391
392
  ...(options.reloadRegistry ? [createReloadTool({ registry: options.reloadRegistry })] : []),
392
393
  ...(options.stream ? [createStreamSnapshotTool({ stream: options.stream })] : []),
393
- ...buildChannelTools(options.channelRouter, options.origin, sessionManager.getSessionId(), getOrigin),
394
+ ...buildChannelTools(
395
+ options.channelRouter,
396
+ options.origin,
397
+ sessionManager.getSessionId(),
398
+ getOrigin,
399
+ options.permissions,
400
+ options.plugins?.agentDir,
401
+ ),
394
402
  ...(options.containerName
395
403
  ? [
396
404
  createRestartTool({
@@ -473,6 +481,14 @@ export async function createSessionWithDispose(options: CreateSessionOptions = {
473
481
  customTools,
474
482
  ...(thinkingLevel ? { thinkingLevel } : {}),
475
483
  })
484
+ // typeclaw owns retry/fallback in its turn drivers, so the SDK's own
485
+ // same-model auto-retry must be OFF. Leaving it on races typeclaw's
486
+ // soft-error capture: the SDK can silently recover a `stopReason:'error'` turn
487
+ // while typeclaw has already latched the failure, reporting a recovered turn as
488
+ // failed (and burning an unnecessary failover). Disabling it makes a soft error
489
+ // a deterministic, typeclaw-owned signal. Compaction/context-overflow recovery
490
+ // is independent (gated on compaction settings), so this does not disable those.
491
+ ;(session as { setAutoRetryEnabled?: (enabled: boolean) => void }).setAutoRetryEnabled?.(false)
476
492
  const getAbortReason = () => abortHolder.reason
477
493
  const sessionWithAbortReason = Object.assign(session, { getAbortReason })
478
494
 
@@ -669,6 +685,8 @@ export function buildChannelTools(
669
685
  origin: SessionOrigin | undefined,
670
686
  sessionId?: string,
671
687
  getOrigin?: () => SessionOrigin | undefined,
688
+ permissions?: PermissionService,
689
+ agentDir?: string,
672
690
  ): ToolDefinition[] {
673
691
  if (!channelRouter) return []
674
692
  const tools: ToolDefinition[] = []
@@ -695,6 +713,7 @@ export function buildChannelTools(
695
713
  ...(sessionId !== undefined ? { sessionId } : {}),
696
714
  }),
697
715
  )
716
+ tools.push(createChannelEditTool({ router: channelRouter }))
698
717
  // Read the live turn origin, falling back to the static snapshot when no
699
718
  // getter is wired (composition tests). `reactionRef` is per-turn, so the
700
719
  // getter is what makes reactions work outside tests.
@@ -713,6 +732,9 @@ export function buildChannelTools(
713
732
  createChannelFetchAttachmentTool({
714
733
  router: channelRouter,
715
734
  origin: channelOrigin,
735
+ ...(permissions !== undefined && agentDir !== undefined
736
+ ? { resolveBaseDir: () => resolveInboxBaseDir(permissions, getOrigin?.() ?? origin, agentDir) }
737
+ : {}),
716
738
  }),
717
739
  )
718
740
  tools.push(createChannelLookAtTool(channelRouter, channelOrigin))
@@ -723,6 +745,7 @@ export function buildChannelTools(
723
745
  } else {
724
746
  tools.push(createChannelSendTool({ router: channelRouter }))
725
747
  tools.push(createChannelReadTool({ router: channelRouter }))
748
+ tools.push(createChannelEditTool({ router: channelRouter }))
726
749
  }
727
750
  return tools
728
751
  }
@@ -3,7 +3,8 @@ import type { Models } from '@/config/config'
3
3
  import type { KnownModelRef, ModelRef } from '@/config/providers'
4
4
 
5
5
  import type { AgentSession } from './index'
6
- import { subscribeProviderErrors } from './provider-error'
6
+ import { isRetryableSameRef, subscribeProviderErrors } from './provider-error'
7
+ import { RETRIES_PER_REF, sleepBackoff } from './retry-same-ref'
7
8
  import { renderTurnTimeAnchor } from './system-prompt'
8
9
 
9
10
  // Result of a single fallback-aware prompt run.
@@ -87,53 +88,71 @@ export async function promptWithFallback<TRef extends FallbackModelRef>(opts: {
87
88
  for (let i = 0; i < opts.refs.length; i++) {
88
89
  const ref = opts.refs[i]!
89
90
  const isLast = i === opts.refs.length - 1
91
+ // Try this ref, replaying the SAME ref on a transient failure before we give
92
+ // up on it. Cron sessions are cheap and fresh-per-attempt, so a same-ref
93
+ // retry just recreates the session — no state surgery needed.
94
+ const outcome = await attemptRefWithRetry(ref, opts)
95
+ if (outcome.kind === 'success') {
96
+ attempts.push({ ref, outcome: 'success' })
97
+ return { success: true, refUsed: ref, attempts, session: outcome.session, dispose: outcome.dispose }
98
+ }
99
+ attempts.push({ ref, outcome: outcome.kind, errorMessage: outcome.error.message })
100
+ lastError = outcome.error
101
+ const stop = isLast || !failoverGate(outcome.error)
102
+ if (!stop) opts.onAttemptFailed?.({ ref, outcome: outcome.kind, errorMessage: outcome.error.message })
103
+ // The failed ref's session is spent either way — dispose it. On stop we still
104
+ // hand the caller the (now-disposed) session for its final surface, with a
105
+ // no-op dispose so a double-dispose can't happen.
106
+ await outcome.dispose()
107
+ if (stop) {
108
+ return { success: false, refUsed: ref, attempts, session: outcome.session, dispose: async () => {}, lastError }
109
+ }
110
+ }
111
+ throw new Error('promptWithFallback: unreachable — loop terminated without returning')
112
+ }
113
+
114
+ type RefAttemptOutcome =
115
+ | { kind: 'success'; session: AgentSession; dispose: () => Promise<void> }
116
+ | { kind: 'hard' | 'soft'; error: Error; session: AgentSession; dispose: () => Promise<void> }
117
+
118
+ // One ref, with same-ref retry. Each attempt gets a fresh session (cron's
119
+ // pattern); a retryable failure disposes it and recreates the same ref up to
120
+ // RETRIES_PER_REF times before returning failure to the chain. The returned
121
+ // session/dispose is always from the LAST attempt so the caller can surface or
122
+ // keep it exactly as before.
123
+ async function attemptRefWithRetry<TRef extends FallbackModelRef>(
124
+ ref: TRef,
125
+ opts: {
126
+ text: string
127
+ createSessionForRef: (ref: TRef) => Promise<{ session: AgentSession; dispose: () => Promise<void> }>
128
+ },
129
+ ): Promise<RefAttemptOutcome> {
130
+ for (let attempt = 0; ; attempt++) {
90
131
  const { session, dispose } = await opts.createSessionForRef(ref)
91
- // Capture the first soft error per attempt. The `subscribeProviderErrors`
92
- // listener fires synchronously off the `message_end` event, which lands
93
- // BEFORE `session.prompt()` resolves — so by the time `await` returns,
94
- // `softError` is populated if a soft error occurred.
132
+ // Capture the first soft error per attempt. The listener fires synchronously
133
+ // off `message_end`, which lands BEFORE `session.prompt()` resolves, so by
134
+ // the time `await` returns `softError` is populated if one occurred.
95
135
  let softError: Error | undefined
96
136
  const unsub = subscribeProviderErrors(session, (err) => {
97
137
  if (!softError) softError = new Error(err.message)
98
138
  })
139
+ let outcome: RefAttemptOutcome
99
140
  try {
100
- try {
101
- await session.prompt(`${renderTurnTimeAnchor()}\n\n${opts.text}`)
102
- } catch (err) {
103
- const error = err instanceof Error ? err : new Error(String(err))
104
- const attempt: FallbackAttempt<TRef> = { ref, outcome: 'hard', errorMessage: error.message }
105
- attempts.push(attempt)
106
- lastError = error
107
- const stop = isLast || !failoverGate(error)
108
- if (!stop) opts.onAttemptFailed?.(attempt)
109
- unsub()
110
- await dispose()
111
- if (stop) {
112
- return { success: false, refUsed: ref, attempts, session, dispose: async () => {}, lastError }
113
- }
114
- continue
115
- }
116
- if (softError !== undefined) {
117
- const attempt: FallbackAttempt<TRef> = { ref, outcome: 'soft', errorMessage: softError.message }
118
- attempts.push(attempt)
119
- lastError = softError
120
- const stop = isLast || !failoverGate(softError)
121
- if (!stop) opts.onAttemptFailed?.(attempt)
122
- unsub()
123
- await dispose()
124
- if (stop) {
125
- return { success: false, refUsed: ref, attempts, session, dispose: async () => {}, lastError }
126
- }
127
- continue
128
- }
129
- attempts.push({ ref, outcome: 'success' })
130
- unsub()
131
- return { success: true, refUsed: ref, attempts, session, dispose }
141
+ await session.prompt(`${renderTurnTimeAnchor()}\n\n${opts.text}`)
142
+ outcome =
143
+ softError === undefined
144
+ ? { kind: 'success', session, dispose }
145
+ : { kind: 'soft', error: softError, session, dispose }
132
146
  } catch (err) {
147
+ outcome = { kind: 'hard', error: err instanceof Error ? err : new Error(String(err)), session, dispose }
148
+ } finally {
133
149
  unsub()
134
- await dispose()
135
- throw err
136
150
  }
151
+ if (outcome.kind === 'success') return outcome
152
+ const canRetry = attempt < RETRIES_PER_REF && isRetryableSameRef(outcome.error.message)
153
+ if (!canRetry) return outcome
154
+ // Retryable and budget remains: drop this session and replay the same ref.
155
+ await dispose()
156
+ await sleepBackoff(attempt)
137
157
  }
138
- throw new Error('promptWithFallback: unreachable — loop terminated without returning')
139
158
  }
@@ -9,8 +9,10 @@ import type { ChannelRouter } from '@/channels/router'
9
9
  import type { AdapterId } from '@/channels/schema'
10
10
  import { getConfig, resolveModel, resolveProfile } from '@/config'
11
11
  import { providerForModelRef } from '@/config/providers'
12
+ import { LLM_FETCH_OBSERVER_TIMEOUTS, type LlmFetchObservedRequestInit } from '@/run/llm-fetch-observer'
12
13
  import { SecretsBackend } from '@/secrets'
13
14
 
15
+ import { promptWithSameRefRetryOnly } from '../retry-same-ref'
14
16
  import { buildMultimodalLookerSystemPrompt, resolveImage, type ImageInput } from './looker'
15
17
 
16
18
  type ImageParam = { url: string } | { path: string } | { data: string; mimeType: string }
@@ -187,7 +189,7 @@ async function runLookAtImages(imageContents: ImageContent[], prompt: string | u
187
189
  })
188
190
 
189
191
  try {
190
- await session.prompt(userText, { images: imageContents })
192
+ await promptWithSameRefRetryOnly(session, userText, { images: imageContents })
191
193
  const text = extractLastAssistantText(session.messages)
192
194
  if (text === null) {
193
195
  return errorResult('multimodal-looker returned no text response', {
@@ -207,6 +209,21 @@ const GLM_VISION_MODEL = 'glm-4.6v'
207
209
  const GLM_VISION_ENDPOINT = 'https://api.z.ai/api/coding/paas/v4/chat/completions'
208
210
  const GLM_VISION_MAX_TOKENS = 32768
209
211
 
212
+ // Vision requests carry a base64 image body the server must decode before it can
213
+ // send response headers, so the observer's 15s default TTFB (tuned for ~1s text
214
+ // completions) is too tight and flakes on cold connections. 45s is 3x the
215
+ // observed-under-load window; env-overridable for operators who need more.
216
+ export const GLM_VISION_TTFB_MS = 45_000
217
+ const ENV_GLM_VISION_TTFB_MS = 'TYPECLAW_GLM_VISION_TTFB_MS'
218
+
219
+ export function resolveGlmVisionTtfbMs(env: NodeJS.ProcessEnv = process.env): number {
220
+ const raw = env[ENV_GLM_VISION_TTFB_MS]
221
+ if (raw === undefined || raw === '') return GLM_VISION_TTFB_MS
222
+ const parsed = Number.parseInt(raw, 10)
223
+ if (!Number.isFinite(parsed) || parsed < 0) return GLM_VISION_TTFB_MS
224
+ return parsed
225
+ }
226
+
210
227
  function shouldUseGlmCodingPlanVision(): boolean {
211
228
  const ref = resolveProfile(getConfig().models, 'vision').ref
212
229
  return providerForModelRef(ref) === GLM_VISION_PROVIDER && !resolveModel(ref).input.includes('image')
@@ -219,17 +236,19 @@ async function analyzeWithGlmCodingPlanVision(imageContents: ImageContent[], pro
219
236
  return errorResult('GLM Coding Plan vision unavailable: no zai-coding API key', details)
220
237
  }
221
238
 
239
+ const requestInit: LlmFetchObservedRequestInit = {
240
+ method: 'POST',
241
+ headers: { Authorization: `Bearer ${apiKey}`, 'Content-Type': 'application/json' },
242
+ body: JSON.stringify({
243
+ model: GLM_VISION_MODEL,
244
+ max_tokens: GLM_VISION_MAX_TOKENS,
245
+ messages: buildGlmVisionMessages(imageContents, prompt),
246
+ }),
247
+ [LLM_FETCH_OBSERVER_TIMEOUTS]: { ttfbMs: resolveGlmVisionTtfbMs() },
248
+ }
222
249
  let response: Response
223
250
  try {
224
- response = await fetch(GLM_VISION_ENDPOINT, {
225
- method: 'POST',
226
- headers: { Authorization: `Bearer ${apiKey}`, 'Content-Type': 'application/json' },
227
- body: JSON.stringify({
228
- model: GLM_VISION_MODEL,
229
- max_tokens: GLM_VISION_MAX_TOKENS,
230
- messages: buildGlmVisionMessages(imageContents, prompt),
231
- }),
232
- })
251
+ response = await fetch(GLM_VISION_ENDPOINT, requestInit)
233
252
  } catch (error) {
234
253
  return errorResult(`GLM vision request failed: ${error instanceof Error ? error.message : String(error)}`, details)
235
254
  }
@@ -619,7 +619,12 @@ async function applyBashSandbox(
619
619
  { type: 'bind', source: sessionTmp, dest: '/tmp' },
620
620
  ],
621
621
  ...(packageInstall !== undefined
622
- ? { writableRoot: { dir: packageInstall.root }, masks: maskTargets, protected: packageInstall.protected }
622
+ ? {
623
+ writableRoot: { dir: packageInstall.root },
624
+ masks: maskTargets,
625
+ protected: packageInstall.protected,
626
+ blockedCreation: { files: packageInstall.blockedCreation },
627
+ }
623
628
  : { masks: maskTargets, writable, protected: protectedZones }),
624
629
  symlinks,
625
630
  network: 'inherit',
@@ -652,11 +657,11 @@ function buildRoleScopedConfigEnv(
652
657
  }
653
658
 
654
659
  function subtractMaskedProtected(
655
- zones: { root: string; protected: { dirs: string[]; files: string[] } },
660
+ zones: { root: string; protected: { dirs: string[]; files: string[] }; blockedCreation: string[] },
656
661
  masked: { dirs: string[]; files: string[] },
657
- ): { root: string; protected: { dirs: string[]; files: string[] } } {
662
+ ): { root: string; protected: { dirs: string[]; files: string[] }; blockedCreation: string[] } {
658
663
  const filtered = subtractMasked(zones.protected, masked)
659
- return { root: zones.root, protected: filtered }
664
+ return { root: zones.root, protected: filtered, blockedCreation: zones.blockedCreation }
660
665
  }
661
666
 
662
667
  // Picks the /proc strategy for a sandboxed bash call. The branch order is: