typeclaw 0.36.8 → 0.37.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 (111) hide show
  1. package/README.md +2 -2
  2. package/package.json +3 -2
  3. package/src/agent/index.ts +31 -11
  4. package/src/agent/live-sessions.ts +12 -0
  5. package/src/agent/model-fallback.ts +17 -15
  6. package/src/agent/model-overrides.ts +2 -2
  7. package/src/agent/session-meta.ts +10 -0
  8. package/src/agent/subagents.ts +11 -2
  9. package/src/agent/system-prompt.ts +9 -3
  10. package/src/agent/todo/continuation-policy.ts +6 -3
  11. package/src/agent/todo/continuation-wiring.ts +4 -2
  12. package/src/agent/todo/continuation.ts +3 -3
  13. package/src/agent/tools/todo/index.ts +27 -4
  14. package/src/bundled-plugins/agent-browser/index.ts +33 -108
  15. package/src/bundled-plugins/agent-browser/shim.ts +3 -94
  16. package/src/bundled-plugins/agent-browser/skills/agent-browser/SKILL.md +8 -33
  17. package/src/bundled-plugins/doc-render/skills/typeclaw-render-pdf/SKILL.md +2 -2
  18. package/src/bundled-plugins/guard/policies/memory-retrieval-cache-write.ts +7 -1
  19. package/src/bundled-plugins/memory/README.md +80 -23
  20. package/src/bundled-plugins/memory/append-tool.ts +74 -53
  21. package/src/bundled-plugins/memory/citation-superset.ts +4 -0
  22. package/src/bundled-plugins/memory/citations.ts +54 -0
  23. package/src/bundled-plugins/memory/dreaming-metrics.ts +30 -0
  24. package/src/bundled-plugins/memory/dreaming.ts +444 -21
  25. package/src/bundled-plugins/memory/index.ts +544 -400
  26. package/src/bundled-plugins/memory/load-memory.ts +87 -10
  27. package/src/bundled-plugins/memory/load-shards.ts +48 -22
  28. package/src/bundled-plugins/memory/memory-logger.ts +95 -106
  29. package/src/bundled-plugins/memory/memory-retrieval.ts +3 -3
  30. package/src/bundled-plugins/memory/parent-link.ts +33 -0
  31. package/src/bundled-plugins/memory/paths.ts +12 -0
  32. package/src/bundled-plugins/memory/references/frontmatter.ts +197 -0
  33. package/src/bundled-plugins/memory/references/load-references.ts +212 -0
  34. package/src/bundled-plugins/memory/references/store-reference-tool.ts +59 -0
  35. package/src/bundled-plugins/memory/search-tool.ts +282 -45
  36. package/src/bundled-plugins/memory/stream-events.ts +1 -0
  37. package/src/bundled-plugins/memory/stream-io.ts +28 -3
  38. package/src/bundled-plugins/memory/turn-dedup.ts +40 -0
  39. package/src/bundled-plugins/memory/vector/cache-write.ts +19 -0
  40. package/src/bundled-plugins/memory/vector/config.ts +28 -0
  41. package/src/bundled-plugins/memory/vector/doctor.ts +124 -0
  42. package/src/bundled-plugins/memory/vector/embedder.ts +246 -0
  43. package/src/bundled-plugins/memory/vector/hybrid.ts +439 -0
  44. package/src/bundled-plugins/memory/vector/index-on-write.ts +34 -0
  45. package/src/bundled-plugins/memory/vector/inspect.ts +111 -0
  46. package/src/bundled-plugins/memory/vector/passages.ts +125 -0
  47. package/src/bundled-plugins/memory/vector/reference-index-on-write.ts +50 -0
  48. package/src/bundled-plugins/memory/vector/relevance-gate.ts +93 -0
  49. package/src/bundled-plugins/memory/vector/startup.ts +71 -0
  50. package/src/bundled-plugins/memory/vector/store.ts +203 -0
  51. package/src/bundled-plugins/memory/vector/truncation.ts +124 -0
  52. package/src/bundled-plugins/security/policies/outbound-secret-scan.ts +2 -0
  53. package/src/channels/router.ts +239 -40
  54. package/src/cli/incomplete-init.ts +57 -0
  55. package/src/cli/init.ts +143 -12
  56. package/src/cli/inspect.ts +11 -5
  57. package/src/cli/model.ts +112 -34
  58. package/src/cli/restart.ts +24 -0
  59. package/src/cli/start.ts +24 -0
  60. package/src/cli/tunnel.ts +53 -8
  61. package/src/config/config.ts +110 -19
  62. package/src/config/index.ts +5 -1
  63. package/src/config/models-mutation.ts +29 -11
  64. package/src/config/providers-mutation.ts +2 -2
  65. package/src/config/providers.ts +146 -12
  66. package/src/container/shared.ts +9 -0
  67. package/src/container/start.ts +87 -4
  68. package/src/cron/consumer.ts +13 -7
  69. package/src/hostd/models.ts +64 -0
  70. package/src/hostd/paths.ts +6 -0
  71. package/src/hostd/portbroker-manager.ts +2 -2
  72. package/src/init/checkpoint.ts +201 -0
  73. package/src/init/dockerfile.ts +121 -34
  74. package/src/init/gitignore.ts +7 -7
  75. package/src/init/index.ts +41 -9
  76. package/src/init/models-dev.ts +96 -21
  77. package/src/init/oauth-login.ts +3 -3
  78. package/src/init/progress.ts +29 -0
  79. package/src/init/validate-api-key.ts +4 -0
  80. package/src/inspect/index.ts +13 -6
  81. package/src/inspect/item-list.ts +11 -2
  82. package/src/inspect/live-list.ts +65 -0
  83. package/src/inspect/open-item.ts +22 -1
  84. package/src/inspect/session-list.ts +29 -0
  85. package/src/models/embedding-model.ts +114 -0
  86. package/src/models/transformers-version.ts +55 -0
  87. package/src/plugin/types.ts +3 -0
  88. package/src/portbroker/container-server.ts +23 -0
  89. package/src/portbroker/forward-request-bus.ts +35 -0
  90. package/src/portbroker/forward-result-bus.ts +2 -3
  91. package/src/portbroker/hostd-client.ts +182 -36
  92. package/src/portbroker/index.ts +6 -1
  93. package/src/portbroker/protocol.ts +9 -2
  94. package/src/run/channel-session-factory.ts +11 -1
  95. package/src/run/index.ts +41 -7
  96. package/src/server/command-runner.ts +24 -1
  97. package/src/server/index.ts +42 -8
  98. package/src/shared/index.ts +2 -0
  99. package/src/shared/protocol.ts +31 -0
  100. package/src/skills/typeclaw-channels/SKILL.md +4 -4
  101. package/src/skills/typeclaw-config/SKILL.md +2 -2
  102. package/src/skills/typeclaw-memory/SKILL.md +3 -1
  103. package/src/skills/typeclaw-permissions/SKILL.md +3 -3
  104. package/src/skills/typeclaw-skills/SKILL.md +1 -1
  105. package/src/skills/typeclaw-tunnels/SKILL.md +22 -1
  106. package/src/tunnels/providers/cloudflare-quick.ts +65 -7
  107. package/src/tunnels/upstream-probe.ts +25 -0
  108. package/typeclaw.schema.json +156 -67
  109. package/src/bundled-plugins/agent-browser/dashboard-discovery.ts +0 -170
  110. package/src/bundled-plugins/agent-browser/dashboard-proxy.ts +0 -421
  111. package/src/portbroker/bind-with-forward.ts +0 -102
@@ -1,421 +0,0 @@
1
- import type { Server } from 'bun'
2
-
3
- import { discoverDashboardPort } from './dashboard-discovery'
4
-
5
- export type DashboardProxyOptions = {
6
- listenPort?: number
7
- upstreamPort?: number
8
- resolveUpstreamPort?: () => Promise<number | null>
9
- upstreamHost?: string
10
- listenHost?: string
11
- fetchImpl?: typeof fetch
12
- onLog?: (event: DashboardProxyLogEvent) => void
13
- }
14
-
15
- export type DashboardProxyLogEvent =
16
- | { kind: 'started'; listenHost: string; listenPort: number; upstreamHost: string }
17
- | { kind: 'http-proxy'; port: number; path: string }
18
- | { kind: 'ws-proxy'; port: number; path: string }
19
- | { kind: 'invalid-proxy-target'; prefix: string; pathname: string }
20
- | { kind: 'proxy-target-denied'; port: number; path: string; reason: string }
21
- | { kind: 'upstream-error'; target: string; reason: string }
22
- | { kind: 'no-upstream'; path: string }
23
-
24
- export type DashboardProxy = {
25
- server: Server<WebSocketData>
26
- stop: () => void
27
- }
28
-
29
- type WebSocketData = {
30
- port: number
31
- path: string
32
- upstream?: WebSocket
33
- pending: Array<string | ArrayBuffer>
34
- }
35
-
36
- const DEFAULT_PROXY_PORT = 4848
37
- const DEFAULT_UPSTREAM_PORT = 4849
38
- const DEFAULT_HOST = '127.0.0.1'
39
- const DEFAULT_LISTEN_HOST = '0.0.0.0'
40
- const HTTP_PROXY_PREFIX = '/__typeclaw_agent_browser_http/'
41
- const WS_PROXY_PREFIX = '/__typeclaw_agent_browser_ws/'
42
- const TYPECLAW_AGENT_PORT = 8973
43
- const TYPECLAW_HOSTD_CONTROL_PORT = 8974
44
- const UPSTREAM_PORT_CACHE_MS = 1_000
45
-
46
- export function startDashboardProxy(opts: DashboardProxyOptions = {}): DashboardProxy {
47
- const listenPort = opts.listenPort ?? DEFAULT_PROXY_PORT
48
- const upstreamHost = opts.upstreamHost ?? DEFAULT_HOST
49
- const listenHost = opts.listenHost ?? DEFAULT_LISTEN_HOST
50
- const fetcher = opts.fetchImpl ?? fetch
51
- const log = opts.onLog ?? (() => {})
52
-
53
- const resolveUpstreamPort = makeResolverWithCache(opts, listenPort)
54
- const reservedPorts = new Set([listenPort, TYPECLAW_AGENT_PORT, TYPECLAW_HOSTD_CONTROL_PORT])
55
-
56
- const server = Bun.serve<WebSocketData>({
57
- hostname: listenHost,
58
- port: listenPort,
59
- async fetch(request, bunServer) {
60
- const url = new URL(request.url)
61
-
62
- const wsTarget = parsePortPath(url.pathname, WS_PROXY_PREFIX)
63
- if (wsTarget) {
64
- const upstreamPort = await resolveUpstreamPort()
65
- const denied = await denyProxyTarget({
66
- target: wsTarget,
67
- reservedPorts,
68
- upstreamPort,
69
- fetcher,
70
- upstreamHost,
71
- })
72
- if (denied) {
73
- log({ kind: 'proxy-target-denied', port: wsTarget.port, path: wsTarget.path, reason: denied })
74
- return new Response(denied, { status: 403 })
75
- }
76
- if (
77
- bunServer.upgrade(request, {
78
- data: { port: wsTarget.port, path: `${wsTarget.path}${url.search}`, pending: [] },
79
- })
80
- ) {
81
- log({ kind: 'ws-proxy', port: wsTarget.port, path: wsTarget.path })
82
- return undefined
83
- }
84
- return new Response('WebSocket upgrade failed', { status: 400 })
85
- }
86
-
87
- if (url.pathname.startsWith(WS_PROXY_PREFIX)) {
88
- log({ kind: 'invalid-proxy-target', prefix: WS_PROXY_PREFIX, pathname: url.pathname })
89
- return new Response('Invalid WebSocket proxy target', { status: 400 })
90
- }
91
-
92
- const httpTarget = parsePortPath(url.pathname, HTTP_PROXY_PREFIX)
93
- if (httpTarget) {
94
- const upstreamPort = await resolveUpstreamPort()
95
- const denied = await denyProxyTarget({
96
- target: httpTarget,
97
- reservedPorts,
98
- upstreamPort,
99
- fetcher,
100
- upstreamHost,
101
- })
102
- if (denied) {
103
- log({ kind: 'proxy-target-denied', port: httpTarget.port, path: httpTarget.path, reason: denied })
104
- return new Response(denied, { status: 403 })
105
- }
106
- log({ kind: 'http-proxy', port: httpTarget.port, path: httpTarget.path })
107
- return proxyHttp({
108
- request,
109
- fetcher,
110
- host: DEFAULT_HOST,
111
- port: httpTarget.port,
112
- path: `${httpTarget.path}${url.search}`,
113
- })
114
- }
115
-
116
- if (url.pathname.startsWith(HTTP_PROXY_PREFIX)) {
117
- log({ kind: 'invalid-proxy-target', prefix: HTTP_PROXY_PREFIX, pathname: url.pathname })
118
- return new Response('Invalid HTTP proxy target', { status: 400 })
119
- }
120
-
121
- const upstreamPort = await resolveUpstreamPort()
122
- if (upstreamPort === null) {
123
- log({ kind: 'no-upstream', path: url.pathname })
124
- return new Response('agent-browser dashboard is not running. Start it with `agent-browser dashboard start`.', {
125
- status: 502,
126
- })
127
- }
128
-
129
- const upstreamPath = `${url.pathname}${url.search}`
130
- const response = await proxyHttp({ request, fetcher, host: upstreamHost, port: upstreamPort, path: upstreamPath })
131
- return maybeInjectDashboardPatch(response)
132
- },
133
- websocket: {
134
- open(ws) {
135
- const data = ws.data
136
- const upstream = new WebSocket(`ws://${DEFAULT_HOST}:${data.port}${data.path}`)
137
- data.upstream = upstream
138
- upstream.binaryType = 'arraybuffer'
139
- upstream.addEventListener('open', () => flushPending(data))
140
- upstream.addEventListener('message', (event) => ws.send(toBunWebSocketPayload(event.data)))
141
- upstream.addEventListener('close', () => ws.close())
142
- upstream.addEventListener('error', () => ws.close())
143
- },
144
- message(ws, message) {
145
- const data = ws.data
146
- if (data.upstream?.readyState === WebSocket.OPEN) {
147
- data.upstream.send(toWebSocketPayload(message))
148
- return
149
- }
150
- data.pending.push(toWebSocketPayload(message))
151
- },
152
- close(ws) {
153
- ws.data.upstream?.close()
154
- ws.data.pending = []
155
- },
156
- },
157
- })
158
-
159
- if (server.port !== undefined) reservedPorts.add(server.port)
160
- log({ kind: 'started', listenHost, listenPort: server.port ?? listenPort, upstreamHost })
161
-
162
- return {
163
- server,
164
- stop: () => server.stop(true),
165
- }
166
- }
167
-
168
- function makeResolverWithCache(opts: DashboardProxyOptions, listenPort: number): () => Promise<number | null> {
169
- // The resolver is called on every proxied request; cache for a short
170
- // window so concurrent dashboard fetches do not each spawn a procfs walk
171
- // and a /api/sessions probe. UPSTREAM_PORT_CACHE_MS is below the
172
- // perceptible-latency threshold and well under the time it takes to
173
- // start/stop a dashboard, so a stale entry resolves itself within one
174
- // tick of the user noticing.
175
- if (opts.resolveUpstreamPort) {
176
- let cached: { port: number | null; at: number } | null = null
177
- return async () => {
178
- const now = Date.now()
179
- if (cached !== null && now - cached.at < UPSTREAM_PORT_CACHE_MS) return cached.port
180
- const port = await opts.resolveUpstreamPort!()
181
- cached = { port, at: now }
182
- return port
183
- }
184
- }
185
- if (opts.upstreamPort !== undefined) {
186
- const fixed = opts.upstreamPort
187
- return async () => fixed
188
- }
189
- let cached: { port: number | null; at: number } | null = null
190
- return async () => {
191
- const now = Date.now()
192
- if (cached !== null && now - cached.at < UPSTREAM_PORT_CACHE_MS) return cached.port
193
- const port = await discoverDashboardPort({ excludePort: listenPort })
194
- cached = { port, at: now }
195
- return port
196
- }
197
- }
198
-
199
- export function buildDashboardPatchScript(): string {
200
- return `<script>${dashboardPatchBody()}</script>`
201
- }
202
-
203
- export async function maybeInjectDashboardPatch(response: Response): Promise<Response> {
204
- const contentType = response.headers.get('content-type') ?? ''
205
- if (!contentType.includes('text/html')) return response
206
-
207
- const html = await response.text()
208
- const patch = buildDashboardPatchScript()
209
- const patched = injectPatch(html, patch)
210
- const headers = new Headers(response.headers)
211
- headers.delete('content-length')
212
- return new Response(patched, { status: response.status, statusText: response.statusText, headers })
213
- }
214
-
215
- function injectPatch(html: string, patch: string): string {
216
- const closingHead = html.match(/<\/head\s*>/i)
217
- if (closingHead && closingHead.index !== undefined) {
218
- return html.slice(0, closingHead.index) + patch + html.slice(closingHead.index)
219
- }
220
- const openingHead = html.match(/<head\b[^>]*>/i)
221
- if (openingHead && openingHead.index !== undefined) {
222
- const insertAt = openingHead.index + openingHead[0].length
223
- return html.slice(0, insertAt) + patch + html.slice(insertAt)
224
- }
225
- const openingHtml = html.match(/<html\b[^>]*>/i)
226
- if (openingHtml && openingHtml.index !== undefined) {
227
- const insertAt = openingHtml.index + openingHtml[0].length
228
- return html.slice(0, insertAt) + patch + html.slice(insertAt)
229
- }
230
- return patch + html
231
- }
232
-
233
- export function parsePortPath(pathname: string, prefix: string): { port: number; path: string } | null {
234
- if (!pathname.startsWith(prefix)) return null
235
- const rest = pathname.slice(prefix.length)
236
- const slash = rest.indexOf('/')
237
- const encodedPort = slash === -1 ? rest : rest.slice(0, slash)
238
- const port = Number.parseInt(decodeURIComponent(encodedPort), 10)
239
- if (!Number.isInteger(port) || port <= 0 || port > 65535) return null
240
- return { port, path: slash === -1 ? '/' : rest.slice(slash) }
241
- }
242
-
243
- function dashboardPatchBody(): string {
244
- return String.raw`
245
- (() => {
246
- const httpPrefix = '${HTTP_PROXY_PREFIX}';
247
- const wsPrefix = '${WS_PROXY_PREFIX}';
248
-
249
- function isLoopbackHost(hostname) {
250
- return hostname === 'localhost' || hostname === '127.0.0.1' || hostname === '[::1]' || hostname === '::1';
251
- }
252
-
253
- function rewriteHttp(input) {
254
- const raw = typeof input === 'string' ? input : input && input.url;
255
- if (!raw) return input;
256
-
257
- let url;
258
- try { url = new URL(raw, window.location.href); } catch { return input; }
259
- if (!isLoopbackHost(url.hostname) || !url.port) return input;
260
-
261
- const currentPort = String(window.location.port || (window.location.protocol === 'https:' ? 443 : 80));
262
- if (url.port === currentPort) return url.pathname + url.search + url.hash;
263
- return httpPrefix + encodeURIComponent(url.port) + url.pathname + url.search + url.hash;
264
- }
265
-
266
- const nativeFetch = window.fetch.bind(window);
267
- window.fetch = (input, init) => nativeFetch(rewriteHttp(input), init);
268
-
269
- const NativeWebSocket = window.WebSocket;
270
- window.WebSocket = function(url, protocols) {
271
- let next = url;
272
- try {
273
- const parsed = new URL(String(url), window.location.href);
274
- if (isLoopbackHost(parsed.hostname) && parsed.port) {
275
- const scheme = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
276
- next = scheme + '//' + window.location.host + wsPrefix + encodeURIComponent(parsed.port) + parsed.pathname + parsed.search + parsed.hash;
277
- }
278
- } catch {}
279
- return protocols === undefined ? new NativeWebSocket(next) : new NativeWebSocket(next, protocols);
280
- };
281
- window.WebSocket.prototype = NativeWebSocket.prototype;
282
- for (const key of ['CONNECTING', 'OPEN', 'CLOSING', 'CLOSED']) {
283
- Object.defineProperty(window.WebSocket, key, { value: NativeWebSocket[key] });
284
- }
285
- })();`
286
- }
287
-
288
- async function proxyHttp({
289
- request,
290
- fetcher,
291
- host,
292
- port,
293
- path,
294
- }: {
295
- request: Request
296
- fetcher: typeof fetch
297
- host: string
298
- port: number
299
- path: string
300
- }): Promise<Response> {
301
- const target = `http://${host}:${port}${path}`
302
- try {
303
- const response = await fetcher(target, {
304
- method: request.method,
305
- headers: hopHeaders(request.headers),
306
- body: request.body,
307
- redirect: 'manual',
308
- })
309
- return rewriteCorsHeaders(response, request)
310
- } catch (err) {
311
- const reason = err instanceof Error ? err.message : String(err)
312
- return new Response(`Failed to proxy ${target}: ${reason}`, { status: 502 })
313
- }
314
- }
315
-
316
- function rewriteCorsHeaders(response: Response, request: Request): Response {
317
- const origin = request.headers.get('origin')
318
- if (origin === null) return response
319
-
320
- const allowOrigin = response.headers.get('access-control-allow-origin')
321
- if (allowOrigin === null || !isLoopbackOrigin(allowOrigin)) return response
322
-
323
- const headers = new Headers(response.headers)
324
- headers.set('access-control-allow-origin', origin)
325
- return new Response(response.body, { status: response.status, statusText: response.statusText, headers })
326
- }
327
-
328
- function isLoopbackOrigin(value: string): boolean {
329
- try {
330
- const url = new URL(value)
331
- return (
332
- url.hostname === 'localhost' || url.hostname === '127.0.0.1' || url.hostname === '[::1]' || url.hostname === '::1'
333
- )
334
- } catch {
335
- return false
336
- }
337
- }
338
-
339
- function hopHeaders(headers: Headers): Headers {
340
- const next = new Headers(headers)
341
- for (const name of [
342
- 'host',
343
- 'connection',
344
- 'upgrade',
345
- 'sec-websocket-key',
346
- 'sec-websocket-version',
347
- 'sec-websocket-extensions',
348
- 'sec-websocket-protocol',
349
- ]) {
350
- next.delete(name)
351
- }
352
- return next
353
- }
354
-
355
- function flushPending(data: WebSocketData): void {
356
- const upstream = data.upstream
357
- if (!upstream || upstream.readyState !== WebSocket.OPEN) return
358
- const pending = data.pending.splice(0)
359
- for (const message of pending) upstream.send(message)
360
- }
361
-
362
- function toBunWebSocketPayload(data: unknown): string | Uint8Array {
363
- if (typeof data === 'string') return data
364
- if (data instanceof ArrayBuffer) return new Uint8Array(data)
365
- if (ArrayBuffer.isView(data))
366
- return new Uint8Array(data.buffer.slice(data.byteOffset, data.byteOffset + data.byteLength))
367
- return String(data)
368
- }
369
-
370
- function toWebSocketPayload(data: string | Buffer): string | ArrayBuffer {
371
- if (typeof data === 'string') return data
372
- const copy = new Uint8Array(data.byteLength)
373
- copy.set(data)
374
- return copy.buffer
375
- }
376
-
377
- async function denyProxyTarget({
378
- target,
379
- reservedPorts,
380
- upstreamPort,
381
- fetcher,
382
- upstreamHost,
383
- }: {
384
- target: { port: number; path: string }
385
- reservedPorts: Set<number>
386
- upstreamPort: number | null
387
- fetcher: typeof fetch
388
- upstreamHost: string
389
- }): Promise<string | null> {
390
- if (reservedPorts.has(target.port)) return `port ${target.port} is reserved`
391
- if (upstreamPort !== null && target.port === upstreamPort) return `port ${target.port} is reserved`
392
- if (upstreamPort === null) return 'agent-browser dashboard is not running; cannot validate session port'
393
- const allowed = await discoverSessionPorts({ fetcher, upstreamHost, upstreamPort })
394
- if (!allowed.has(target.port)) return `port ${target.port} is not an active agent-browser session port`
395
- return null
396
- }
397
-
398
- async function discoverSessionPorts({
399
- fetcher,
400
- upstreamHost,
401
- upstreamPort,
402
- }: {
403
- fetcher: typeof fetch
404
- upstreamHost: string
405
- upstreamPort: number
406
- }): Promise<Set<number>> {
407
- const response = await fetcher(`http://${upstreamHost}:${upstreamPort}/api/sessions`)
408
- if (!response.ok) return new Set()
409
- const raw: unknown = await response.json().catch(() => [])
410
- if (!Array.isArray(raw)) return new Set()
411
- const ports = new Set<number>()
412
- for (const entry of raw) {
413
- if (typeof entry !== 'object' || entry === null) continue
414
- const port = (entry as { port?: unknown }).port
415
- if (typeof port === 'number' && Number.isInteger(port) && port > 0 && port <= 65535) ports.add(port)
416
- }
417
- return ports
418
- }
419
-
420
- export const AGENT_BROWSER_DASHBOARD_PROXY_PORT = DEFAULT_PROXY_PORT
421
- export const AGENT_BROWSER_DASHBOARD_UPSTREAM_PORT = DEFAULT_UPSTREAM_PORT
@@ -1,102 +0,0 @@
1
- // Allocate an in-container port whose host-side forward succeeds.
2
- //
3
- // In-container LISTEN succeeds even when the host-side forward collides with
4
- // another container — each container has its own netns, so the procfs check
5
- // can't tell us anything about host-side availability. This helper closes
6
- // that gap: it calls a factory to bind a candidate port internally, waits
7
- // for the broker's `port-forward-result` event, and on failure tears the
8
- // candidate down and tries the next port. Used today by the agent-browser
9
- // plugin's dashboard proxy bind, where multiple typeclaw containers on one
10
- // host all want port 4848 externally and only the first to register wins.
11
- //
12
- // Returns the bound result on first success, or null after exhausting the
13
- // candidate list. Callers MUST treat null as "give up, no host-reachable
14
- // port available" — there is no further recourse without operator action
15
- // (e.g. stopping the colliding container).
16
- //
17
- // If the broker isn't reachable (no TYPECLAW_HOSTD_BROKER_TOKEN, broker
18
- // disconnected, etc.) the bus never receives results. The helper falls
19
- // through to optimistic mode: the first successful in-container bind is
20
- // returned without waiting, on the assumption that no broker means no
21
- // host-side cross-container collision is possible.
22
-
23
- import { subscribeForwardResult } from './forward-result-bus'
24
-
25
- export type BindResult<T> = {
26
- port: number
27
- hostPort: number | null
28
- resource: T
29
- }
30
-
31
- export type BindFactory<T> = (port: number) => Promise<{ resource: T; close: () => void } | null>
32
-
33
- export type BindWithForwardOptions<T> = {
34
- candidates: number[]
35
- factory: BindFactory<T>
36
- timeoutMs?: number
37
- brokerEnabled?: boolean
38
- onLog?: (msg: string) => void
39
- }
40
-
41
- const DEFAULT_TIMEOUT_MS = 2_000
42
-
43
- export async function bindWithForward<T>(opts: BindWithForwardOptions<T>): Promise<BindResult<T> | null> {
44
- const log = opts.onLog ?? (() => {})
45
- const timeoutMs = opts.timeoutMs ?? DEFAULT_TIMEOUT_MS
46
- const brokerEnabled = opts.brokerEnabled ?? defaultBrokerEnabled()
47
-
48
- for (const port of opts.candidates) {
49
- const bound = await opts.factory(port)
50
- if (bound === null) {
51
- log(`bind ${port}: factory returned null (in-container bind failed); trying next`)
52
- continue
53
- }
54
-
55
- if (!brokerEnabled) {
56
- log(`bind ${port}: broker disabled; returning optimistically`)
57
- return { port, hostPort: null, resource: bound.resource }
58
- }
59
-
60
- const forward = await waitForForwardResult(port, timeoutMs)
61
- if (forward.kind === 'ok') {
62
- log(`bind ${port}: forwarded to host:${forward.hostPort}`)
63
- return { port, hostPort: forward.hostPort, resource: bound.resource }
64
- }
65
-
66
- log(`bind ${port}: forward ${forward.kind === 'failed' ? `failed (${forward.reason})` : 'timed out'}; tearing down`)
67
- try {
68
- bound.close()
69
- } catch {
70
- // Close failures are non-fatal here; the next factory call may pick a
71
- // different port and the orphaned listener will be reaped on process
72
- // exit. Logging would just be noise.
73
- }
74
- }
75
- return null
76
- }
77
-
78
- type WaitResult = { kind: 'ok'; hostPort: number } | { kind: 'failed'; reason: string } | { kind: 'timeout' }
79
-
80
- function waitForForwardResult(port: number, timeoutMs: number): Promise<WaitResult> {
81
- return new Promise((resolve) => {
82
- let settled = false
83
- const timer = setTimeout(() => {
84
- if (settled) return
85
- settled = true
86
- unsubscribe()
87
- resolve({ kind: 'timeout' })
88
- }, timeoutMs)
89
- const unsubscribe = subscribeForwardResult((event) => {
90
- if (event.port !== port || settled) return
91
- settled = true
92
- clearTimeout(timer)
93
- unsubscribe()
94
- resolve(event.ok ? { kind: 'ok', hostPort: event.hostPort } : { kind: 'failed', reason: event.reason })
95
- })
96
- })
97
- }
98
-
99
- function defaultBrokerEnabled(): boolean {
100
- const token = process.env['TYPECLAW_HOSTD_BROKER_TOKEN']
101
- return token !== undefined && token.length > 0
102
- }