@swarmclawai/swarmclaw 1.9.26 → 1.9.28

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.
package/README.md CHANGED
@@ -151,14 +151,15 @@ clawhub install swarmclaw
151
151
 
152
152
  [Browse on ClawHub](https://clawhub.ai/skills/swarmclaw)
153
153
 
154
- ## v1.9.26 Highlights
154
+ ## v1.9.28 Highlights
155
155
 
156
- Output hygiene follow-up: empty successful LLM turns now stay silent instead of being rewritten as user-visible errors.
156
+ Issue-fix release for installed CLI groups, email bridge TLS handling, built-in model overrides, and Windows desktop native modules.
157
157
 
158
- - **Silent empty completions.** Blank successful runs no longer become `Error: Run completed...` assistant messages.
159
- - **Connector-safe final text.** Slack and other connectors no longer receive synthetic error text for intentional silence or quiet no-op turns.
160
- - **Real errors preserved.** Explicit provider failures and streamed provider errors still surface as terminal errors.
161
- - **Regression coverage.** Chat-execution tests now lock the distinction between empty success and real failure.
158
+ - **Installed CLI groups.** Global npm installs route legacy API-backed group commands through the bundled TS runtime when installed under `node_modules`, avoiding Node 22.6+/25 type-stripping failures.
159
+ - **Email bridge TLS resilience.** The email connector logs IMAP socket errors without crashing the daemon and supports `tlsRejectUnauthorized=false` for local self-signed IMAP/SMTP servers.
160
+ - **Provider model override persistence.** Built-in provider live model saves now reload array-valued overrides instead of falling back to catalog defaults.
161
+ - **Windows desktop native modules.** Desktop packaging syncs rebuilt Electron-native modules into traced `.next/node_modules` aliases so packaged Windows installs start against the correct ABI.
162
+ - **Regression coverage.** CLI, email, provider route, and Electron after-pack tests cover the reported failure modes.
162
163
 
163
164
  ## Hosted Deploys
164
165
 
@@ -410,6 +411,25 @@ Operational docs: https://swarmclaw.ai/docs/observability
410
411
 
411
412
  ## Releases
412
413
 
414
+ ### v1.9.28 Highlights
415
+
416
+ Issue-fix release for installed CLI groups, email bridge TLS handling, built-in model overrides, and Windows desktop native modules.
417
+
418
+ - **Installed CLI groups.** Global npm installs route legacy API-backed group commands through the bundled TS runtime when installed under `node_modules`, avoiding Node 22.6+/25 type-stripping failures.
419
+ - **Email bridge TLS resilience.** The email connector logs IMAP socket errors without crashing the daemon and supports `tlsRejectUnauthorized=false` for local self-signed IMAP/SMTP servers.
420
+ - **Provider model override persistence.** Built-in provider live model saves now reload array-valued overrides instead of falling back to catalog defaults.
421
+ - **Windows desktop native modules.** Desktop packaging syncs rebuilt Electron-native modules into traced `.next/node_modules` aliases so packaged Windows installs start against the correct ABI.
422
+ - **Regression coverage.** CLI, email, provider route, and Electron after-pack tests cover the reported failure modes.
423
+
424
+ ### v1.9.27 Highlights
425
+
426
+ Desktop compatibility and provider-save repair for Intel Mac users and OpenRouter setup.
427
+
428
+ - **Intel macOS native modules.** The desktop packaging hook now rebuilds Electron-loaded native modules with the target architecture and blocks a release if an x64 macOS bundle contains an arm64-only required addon.
429
+ - **OpenRouter save repair.** Provider updates now tolerate UI metadata fields like `id`, `type`, `createdAt`, and `updatedAt` without persisting them, while still rejecting unrelated unknown fields.
430
+ - **Downloads clarity.** The downloads page no longer guesses Apple Silicon when a browser hides the Mac architecture, so Intel users can choose the x64 DMG explicitly.
431
+ - **Regression coverage.** Provider route and Electron after-pack tests cover the reported failure modes.
432
+
413
433
  ### v1.9.26 Highlights
414
434
 
415
435
  Output hygiene follow-up: empty successful LLM turns now stay silent instead of being rewritten as user-visible errors.
package/bin/swarmclaw.js CHANGED
@@ -55,9 +55,19 @@ function hasTsxRuntime() {
55
55
  }
56
56
  }
57
57
 
58
+ function pathIsInsideNodeModules(filePath) {
59
+ return path.resolve(filePath).split(path.sep).includes('node_modules')
60
+ }
61
+
58
62
  function buildLegacyTsCliArgs(cliPath, argv, options = {}) {
63
+ const ext = path.extname(cliPath).toLowerCase()
64
+ if (ext === '.js' || ext === '.cjs' || ext === '.mjs') {
65
+ return [cliPath, ...argv]
66
+ }
67
+
68
+ const insideNodeModules = options.insideNodeModules ?? pathIsInsideNodeModules(cliPath)
59
69
  const stripTypesSupported = options.supportsStripTypes ?? supportsStripTypes()
60
- if (stripTypesSupported) {
70
+ if (stripTypesSupported && !insideNodeModules) {
61
71
  return ['--no-warnings', '--experimental-strip-types', cliPath, ...argv]
62
72
  }
63
73
 
@@ -69,6 +79,10 @@ function buildLegacyTsCliArgs(cliPath, argv, options = {}) {
69
79
  return null
70
80
  }
71
81
 
82
+ function resolveLegacyTsCliPath() {
83
+ return path.join(__dirname, '..', 'src', 'cli', 'index.ts')
84
+ }
85
+
72
86
  function normalizeLegacyTsCliArgv(argv) {
73
87
  const normalized = []
74
88
 
@@ -98,7 +112,7 @@ function normalizeLegacyTsCliArgv(argv) {
98
112
  }
99
113
 
100
114
  function runLegacyTsCli(argv) {
101
- const cliPath = path.join(__dirname, '..', 'src', 'cli', 'index.ts')
115
+ const cliPath = resolveLegacyTsCliPath()
102
116
  const args = buildLegacyTsCliArgs(cliPath, normalizeLegacyTsCliArgv(argv))
103
117
  const env = normalizeLegacyCliEnv(process.env)
104
118
  if (!args) {
@@ -358,6 +372,8 @@ module.exports = {
358
372
  buildLegacyTsCliArgs,
359
373
  hasTsxRuntime,
360
374
  normalizeLegacyTsCliArgv,
375
+ pathIsInsideNodeModules,
376
+ resolveLegacyTsCliPath,
361
377
  TS_CLI_ACTIONS,
362
378
  normalizeLegacyCliEnv,
363
379
  printPackageVersion,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@swarmclawai/swarmclaw",
3
- "version": "1.9.26",
3
+ "version": "1.9.28",
4
4
  "description": "Build and run autonomous AI agents with OpenClaw, Hermes, multiple model providers, orchestration, delegation, memory, skills, schedules, and chat connectors.",
5
5
  "main": "electron-dist/main.js",
6
6
  "license": "MIT",
@@ -58,3 +58,39 @@ test('provider models route updates custom provider configs without creating mod
58
58
  hasOverride: false,
59
59
  })
60
60
  })
61
+
62
+ test('provider model overrides preserve built-in provider array rows', () => {
63
+ const output = runWithTempDataDir<{
64
+ overrides: Record<string, string[]>
65
+ providerModels: string[]
66
+ getPayload: { models: string[]; hasOverride: boolean }
67
+ }>(`
68
+ const storageMod = await import('./src/lib/server/storage')
69
+ const providerMod = await import('./src/lib/providers')
70
+ const routeMod = await import('./src/app/api/providers/[id]/models/route')
71
+ const storage = storageMod.default || storageMod
72
+ const providers = providerMod.default || providerMod
73
+ const route = routeMod.default || routeMod
74
+
75
+ storage.saveModelOverrides({ lmstudio: ['qwen3.5-27b'] })
76
+
77
+ const getResponse = await route.GET(
78
+ new Request('http://local/api/providers/lmstudio/models'),
79
+ { params: Promise.resolve({ id: 'lmstudio' }) },
80
+ )
81
+ const provider = providers.getProviderList().find((entry) => entry.id === 'lmstudio')
82
+
83
+ console.log(JSON.stringify({
84
+ overrides: storage.loadModelOverrides(),
85
+ providerModels: provider?.models || [],
86
+ getPayload: await getResponse.json(),
87
+ }))
88
+ `, { prefix: 'swarmclaw-provider-model-override-test-' })
89
+
90
+ assert.deepEqual(output.overrides, { lmstudio: ['qwen3.5-27b'] })
91
+ assert.deepEqual(output.providerModels, ['qwen3.5-27b'])
92
+ assert.deepEqual(output.getPayload, {
93
+ models: ['qwen3.5-27b'],
94
+ hasOverride: true,
95
+ })
96
+ })
@@ -48,7 +48,52 @@ test('provider route upserts builtin override records for enablement changes', (
48
48
  assert.equal(output.responsePayload.isEnabled, false)
49
49
  })
50
50
 
51
- test('provider route rejects unknown fields per ProviderUpdateSchema.strict()', () => {
51
+ test('provider route ignores frontend metadata fields without persisting them', () => {
52
+ const output = runWithTempDataDir<{
53
+ status: number
54
+ providerConfig: {
55
+ id: string
56
+ type: string
57
+ name: string
58
+ isEnabled: boolean
59
+ updatedAt: number
60
+ }
61
+ }>(`
62
+ const storageMod = await import('./src/lib/server/storage')
63
+ const routeMod = await import('./src/app/api/providers/[id]/route')
64
+ const storage = storageMod.default || storageMod
65
+ const route = routeMod.default || routeMod
66
+
67
+ const response = await route.PUT(
68
+ new Request('http://local/api/providers/openai', {
69
+ method: 'PUT',
70
+ headers: { 'content-type': 'application/json' },
71
+ body: JSON.stringify({
72
+ id: 'wrong-id',
73
+ type: 'custom',
74
+ createdAt: '123',
75
+ updatedAt: '456',
76
+ isEnabled: false,
77
+ }),
78
+ }),
79
+ { params: Promise.resolve({ id: 'openai' }) },
80
+ )
81
+
82
+ console.log(JSON.stringify({
83
+ status: response.status,
84
+ providerConfig: storage.loadProviderConfigs().openai,
85
+ }))
86
+ `, { prefix: 'swarmclaw-provider-route-strict-test-' })
87
+
88
+ assert.equal(output.status, 200)
89
+ assert.equal(output.providerConfig.id, 'openai')
90
+ assert.equal(output.providerConfig.type, 'builtin')
91
+ assert.equal(output.providerConfig.name, 'OpenAI')
92
+ assert.equal(output.providerConfig.isEnabled, false)
93
+ assert.equal(typeof output.providerConfig.updatedAt, 'number')
94
+ })
95
+
96
+ test('provider route still rejects unknown non-metadata fields', () => {
52
97
  const output = runWithTempDataDir<{ status: number }>(`
53
98
  const routeMod = await import('./src/app/api/providers/[id]/route')
54
99
  const route = routeMod.default || routeMod
@@ -57,13 +102,13 @@ test('provider route rejects unknown fields per ProviderUpdateSchema.strict()',
57
102
  new Request('http://local/api/providers/openai', {
58
103
  method: 'PUT',
59
104
  headers: { 'content-type': 'application/json' },
60
- body: JSON.stringify({ type: 'builtin', isEnabled: true }),
105
+ body: JSON.stringify({ unexpectedField: true, isEnabled: true }),
61
106
  }),
62
107
  { params: Promise.resolve({ id: 'openai' }) },
63
108
  )
64
109
 
65
110
  console.log(JSON.stringify({ status: response.status }))
66
- `, { prefix: 'swarmclaw-provider-route-strict-test-' })
111
+ `, { prefix: 'swarmclaw-provider-route-unknown-field-test-' })
67
112
 
68
113
  assert.equal(output.status, 400)
69
114
  })
@@ -8,6 +8,7 @@ import { ProviderUpdateSchema, formatZodError } from '@/lib/validation/schemas'
8
8
 
9
9
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
10
10
  const ops: CollectionOps<any> = { load: loadProviderConfigs, save: saveProviderConfigs, topic: 'providers' }
11
+ const PROVIDER_UPDATE_WRITABLE_KEYS = new Set(['name', 'baseUrl', 'models', 'credentialId', 'isEnabled', 'requiresApiKey', 'notes'])
11
12
 
12
13
  export async function GET(_req: Request, { params }: { params: Promise<{ id: string }> }) {
13
14
  const { id } = await params
@@ -27,7 +28,7 @@ export async function PUT(req: Request, { params }: { params: Promise<{ id: stri
27
28
  const rawKeys = new Set(Object.keys(raw ?? {}))
28
29
  const body: Record<string, unknown> = {}
29
30
  for (const [key, value] of Object.entries(parsed.data)) {
30
- if (rawKeys.has(key)) body[key] = value
31
+ if (rawKeys.has(key) && PROVIDER_UPDATE_WRITABLE_KEYS.has(key)) body[key] = value
31
32
  }
32
33
 
33
34
  if (!ops.load()[id]) {
@@ -7,7 +7,7 @@ const fs = require('node:fs')
7
7
  const os = require('node:os')
8
8
  const path = require('node:path')
9
9
  const { spawnSync } = require('node:child_process')
10
- const { buildLegacyTsCliArgs } = require('../../bin/swarmclaw.js')
10
+ const { buildLegacyTsCliArgs, resolveLegacyTsCliPath } = require('../../bin/swarmclaw.js')
11
11
 
12
12
  const CLI_BIN = path.join(__dirname, '..', '..', 'bin', 'swarmclaw.js')
13
13
  const PACKAGE_JSON = require('../../package.json')
@@ -208,3 +208,14 @@ test('legacy TS launcher falls back to tsx import when strip-types is unavailabl
208
208
 
209
209
  assert.deepEqual(args, ['--no-warnings', '--import', 'tsx', cliPath, 'runs', 'list'])
210
210
  })
211
+
212
+ test('legacy TS launcher uses tsx instead of strip-types inside node_modules', () => {
213
+ const cliPath = path.join(os.tmpdir(), 'node_modules', '@swarmclawai', 'swarmclaw', 'src', 'cli', 'index.ts')
214
+ const args = buildLegacyTsCliArgs(cliPath, ['agents', 'list'], {
215
+ supportsStripTypes: true,
216
+ hasTsxRuntime: true,
217
+ })
218
+
219
+ assert.deepEqual(args, ['--no-warnings', '--import', 'tsx', cliPath, 'agents', 'list'])
220
+ assert.equal(resolveLegacyTsCliPath(), path.join(APP_ROOT, 'src', 'cli', 'index.ts'))
221
+ })
@@ -1,9 +1,15 @@
1
1
  import assert from 'node:assert/strict'
2
+ import { EventEmitter } from 'node:events'
2
3
  import fs from 'node:fs'
3
4
  import os from 'node:os'
4
5
  import path from 'node:path'
5
6
  import { describe, it } from 'node:test'
6
- import { buildAttachments } from './email'
7
+ import {
8
+ attachImapErrorHandler,
9
+ buildAttachments,
10
+ buildEmailTlsOptions,
11
+ parseTlsRejectUnauthorized,
12
+ } from './email'
7
13
  import { connectorSupportsBinaryMedia } from './response-media'
8
14
 
9
15
  describe('connectorSupportsBinaryMedia — email', () => {
@@ -63,3 +69,30 @@ describe('email buildAttachments', () => {
63
69
  }
64
70
  })
65
71
  })
72
+
73
+ describe('email TLS configuration', () => {
74
+ it('defaults to certificate verification', () => {
75
+ assert.equal(parseTlsRejectUnauthorized(undefined), true)
76
+ assert.equal(parseTlsRejectUnauthorized(''), true)
77
+ assert.deepEqual(buildEmailTlsOptions({ tlsRejectUnauthorized: true }), { rejectUnauthorized: true })
78
+ })
79
+
80
+ it('allows explicit self-signed certificate opt-out', () => {
81
+ assert.equal(parseTlsRejectUnauthorized(false), false)
82
+ assert.equal(parseTlsRejectUnauthorized('false'), false)
83
+ assert.equal(parseTlsRejectUnauthorized('0'), false)
84
+ assert.deepEqual(buildEmailTlsOptions({ tlsRejectUnauthorized: false }), { rejectUnauthorized: false })
85
+ })
86
+
87
+ it('handles IMAP socket errors without leaving the emitter unhandled', () => {
88
+ const imap = new EventEmitter()
89
+ let disconnected = false
90
+
91
+ attachImapErrorHandler(imap, () => {
92
+ disconnected = true
93
+ })
94
+
95
+ assert.doesNotThrow(() => imap.emit('error', new Error('DEPTH_ZERO_SELF_SIGNED_CERT')))
96
+ assert.equal(disconnected, true)
97
+ })
98
+ })
@@ -21,6 +21,7 @@ interface EmailConfig {
21
21
  folder?: string
22
22
  pollIntervalSec?: number
23
23
  subjectPrefix?: string
24
+ tlsRejectUnauthorized: boolean
24
25
  }
25
26
 
26
27
  interface MailAttachment {
@@ -29,6 +30,10 @@ interface MailAttachment {
29
30
  contentType?: string
30
31
  }
31
32
 
33
+ interface ImapErrorEmitter {
34
+ on(event: 'error', listener: (err: unknown) => void): unknown
35
+ }
36
+
32
37
  export function buildAttachments(options?: OutboundSendOptions): MailAttachment[] {
33
38
  const source = options?.mediaPath
34
39
  if (!source) return []
@@ -43,6 +48,28 @@ export function buildAttachments(options?: OutboundSendOptions): MailAttachment[
43
48
  }]
44
49
  }
45
50
 
51
+ export function parseTlsRejectUnauthorized(value: unknown): boolean {
52
+ if (typeof value === 'boolean') return value
53
+ if (typeof value !== 'string') return true
54
+
55
+ const normalized = value.trim().toLowerCase()
56
+ if (!normalized) return true
57
+ if (['false', '0', 'no', 'off', 'disabled'].includes(normalized)) return false
58
+ if (['true', '1', 'yes', 'on', 'enabled'].includes(normalized)) return true
59
+ return true
60
+ }
61
+
62
+ export function buildEmailTlsOptions(config: Pick<EmailConfig, 'tlsRejectUnauthorized'>): { rejectUnauthorized: boolean } {
63
+ return { rejectUnauthorized: config.tlsRejectUnauthorized !== false }
64
+ }
65
+
66
+ export function attachImapErrorHandler(imap: ImapErrorEmitter, onDisconnected: () => void): void {
67
+ imap.on('error', (err: unknown) => {
68
+ onDisconnected()
69
+ log.error(TAG, `IMAP socket error: ${errorMessage(err)}`)
70
+ })
71
+ }
72
+
46
73
  function getConfig(connector: Connector): EmailConfig {
47
74
  const c = connector.config as Record<string, unknown>
48
75
  return {
@@ -55,6 +82,7 @@ function getConfig(connector: Connector): EmailConfig {
55
82
  folder: String(c.folder ?? 'INBOX'),
56
83
  pollIntervalSec: Number(c.pollIntervalSec ?? 60),
57
84
  subjectPrefix: c.subjectPrefix ? String(c.subjectPrefix) : undefined,
85
+ tlsRejectUnauthorized: parseTlsRejectUnauthorized(c.tlsRejectUnauthorized),
58
86
  }
59
87
  }
60
88
 
@@ -68,24 +96,31 @@ const email: PlatformConnector = {
68
96
 
69
97
  const folder = config.folder || 'INBOX'
70
98
  const pollMs = (config.pollIntervalSec || 60) * 1000
99
+ const tls = buildEmailTlsOptions(config)
100
+ let connected = false
71
101
 
72
102
  // IMAP client for inbound
73
103
  const imap = new ImapFlow({
74
104
  host: config.imapHost,
75
105
  port: config.imapPort || 993,
76
106
  secure: (config.imapPort || 993) === 993,
107
+ tls,
77
108
  auth: {
78
109
  user: config.user,
79
110
  pass: config.password,
80
111
  },
81
112
  logger: false,
82
113
  })
114
+ attachImapErrorHandler(imap, () => {
115
+ connected = false
116
+ })
83
117
 
84
118
  // SMTP transport for outbound
85
119
  const smtp: Transporter = createTransport({
86
120
  host: config.smtpHost,
87
121
  port: config.smtpPort || 587,
88
122
  secure: (config.smtpPort || 587) === 465,
123
+ tls,
89
124
  auth: {
90
125
  user: config.user,
91
126
  pass: config.password,
@@ -94,7 +129,6 @@ const email: PlatformConnector = {
94
129
 
95
130
  // Track last seen UID to only process new messages
96
131
  let highwaterUid = 0
97
- let connected = false
98
132
  let pollTimer: ReturnType<typeof setInterval> | null = null
99
133
 
100
134
  // Map to track original sender per channelId (email address) for replies
@@ -187,6 +187,10 @@ const COLLECTIONS = [
187
187
 
188
188
  export type StorageCollection = (typeof COLLECTIONS)[number]
189
189
 
190
+ const ARRAY_VALUE_COLLECTIONS = new Set<StorageCollection>([
191
+ 'model_overrides',
192
+ ])
193
+
190
194
  for (const table of COLLECTIONS) {
191
195
  db.exec(`CREATE TABLE IF NOT EXISTS ${table} (id TEXT PRIMARY KEY, data TEXT NOT NULL)`)
192
196
  }
@@ -246,18 +250,20 @@ function getCollectionRawCache(table: string): LRUMap<string, string> {
246
250
  }
247
251
 
248
252
  function loadCollectionWithNormalizationState(table: string): {
249
- result: Record<string, StoredObject>
253
+ result: Record<string, StoredObject | unknown[]>
250
254
  normalizedCount: number
251
255
  } {
252
256
  const endPerf = perf.start('storage', 'loadCollection', { table })
253
257
  const raw = getCollectionRawCache(table)
254
- const result: Record<string, StoredObject> = {}
258
+ const result: Record<string, StoredObject | unknown[]> = {}
259
+ const allowsArrayValues = ARRAY_VALUE_COLLECTIONS.has(table as StorageCollection)
255
260
  let normalizedCount = 0
256
261
  for (const [id, data] of raw.entries()) {
257
262
  try {
258
263
  const { value: normalized, changed } = normalize(table, JSON.parse(data))
259
- if (!normalized || typeof normalized !== 'object' || Array.isArray(normalized)) continue
260
- result[id] = normalized as StoredObject
264
+ if (!normalized || typeof normalized !== 'object') continue
265
+ if (Array.isArray(normalized) && !allowsArrayValues) continue
266
+ result[id] = normalized as StoredObject | unknown[]
261
267
  if (changed) normalizedCount += 1
262
268
  } catch (err) {
263
269
  const fingerprint = `${table}:${id}`
@@ -277,8 +283,8 @@ function loadCollectionWithNormalizationState(table: string): {
277
283
 
278
284
  export function loadCollection(table: string): Record<string, StoredObject> {
279
285
  const { result, normalizedCount } = loadCollectionWithNormalizationState(table)
280
- if (normalizedCount > 0) saveCollection(table, result)
281
- return result
286
+ if (normalizedCount > 0) saveCollection(table, result as Record<string, unknown>)
287
+ return result as Record<string, StoredObject>
282
288
  }
283
289
 
284
290
  function saveCollection(table: string, data: Record<string, unknown>) {
@@ -1001,7 +1007,7 @@ export function patchAgent(
1001
1007
  const schedulesStore = createCollectionStore('schedules', { ttlMs: 10_000 })
1002
1008
  export function loadSchedules(): Record<string, Schedule> {
1003
1009
  const { result, normalizedCount } = loadCollectionWithNormalizationState('schedules')
1004
- if (normalizedCount > 0) saveCollection('schedules', result)
1010
+ if (normalizedCount > 0) saveCollection('schedules', result as Record<string, unknown>)
1005
1011
  return result as unknown as Record<string, Schedule>
1006
1012
  }
1007
1013
  export const saveSchedules = schedulesStore.save
@@ -320,6 +320,10 @@ export const ProviderUpdateSchema = z.object({
320
320
  isEnabled: z.boolean().optional(),
321
321
  requiresApiKey: z.boolean().optional(),
322
322
  notes: z.string().max(4000).nullable().optional(),
323
+ id: z.unknown().optional(),
324
+ type: z.unknown().optional(),
325
+ createdAt: z.unknown().optional(),
326
+ updatedAt: z.unknown().optional(),
323
327
  }).strict()
324
328
 
325
329
  /** PUT /documents/:id — note: creating a new revision is a side-effect of
@@ -1,218 +0,0 @@
1
- "use strict";
2
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
- if (k2 === undefined) k2 = k;
4
- var desc = Object.getOwnPropertyDescriptor(m, k);
5
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
- desc = { enumerable: true, get: function() { return m[k]; } };
7
- }
8
- Object.defineProperty(o, k2, desc);
9
- }) : (function(o, m, k, k2) {
10
- if (k2 === undefined) k2 = k;
11
- o[k2] = m[k];
12
- }));
13
- var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
- Object.defineProperty(o, "default", { enumerable: true, value: v });
15
- }) : function(o, v) {
16
- o["default"] = v;
17
- });
18
- var __importStar = (this && this.__importStar) || (function () {
19
- var ownKeys = function(o) {
20
- ownKeys = Object.getOwnPropertyNames || function (o) {
21
- var ar = [];
22
- for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
- return ar;
24
- };
25
- return ownKeys(o);
26
- };
27
- return function (mod) {
28
- if (mod && mod.__esModule) return mod;
29
- var result = {};
30
- if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
- __setModuleDefault(result, mod);
32
- return result;
33
- };
34
- })();
35
- var __importDefault = (this && this.__importDefault) || function (mod) {
36
- return (mod && mod.__esModule) ? mod : { "default": mod };
37
- };
38
- Object.defineProperty(exports, "__esModule", { value: true });
39
- const electron_1 = require("electron");
40
- const node_fs_1 = __importDefault(require("node:fs"));
41
- const node_path_1 = __importDefault(require("node:path"));
42
- const paths_1 = require("./paths");
43
- const server_lifecycle_1 = require("./server-lifecycle");
44
- const menu_1 = require("./menu");
45
- const DEV_URL_DEFAULT = 'http://127.0.0.1:3456';
46
- const LOG_TAIL_BYTES = 1500;
47
- let mainWindow = null;
48
- let serverHandle = null;
49
- let serverLogFile = null;
50
- let isQuitting = false;
51
- const gotLock = electron_1.app.requestSingleInstanceLock();
52
- if (!gotLock) {
53
- electron_1.app.quit();
54
- }
55
- else {
56
- electron_1.app.on('second-instance', () => {
57
- if (mainWindow) {
58
- if (mainWindow.isMinimized())
59
- mainWindow.restore();
60
- mainWindow.focus();
61
- }
62
- });
63
- electron_1.app.on('ready', () => void onReady());
64
- electron_1.app.on('window-all-closed', () => {
65
- if (process.platform !== 'darwin')
66
- electron_1.app.quit();
67
- });
68
- electron_1.app.on('activate', () => {
69
- if (mainWindow !== null)
70
- return;
71
- if (serverHandle) {
72
- createMainWindow(serverHandle.url);
73
- }
74
- else if (!electron_1.app.isPackaged) {
75
- createMainWindow(process.env.SWARMCLAW_DEV_URL || DEV_URL_DEFAULT);
76
- }
77
- });
78
- electron_1.app.on('before-quit', () => {
79
- isQuitting = true;
80
- });
81
- electron_1.app.on('will-quit', async (event) => {
82
- if (!serverHandle)
83
- return;
84
- event.preventDefault();
85
- try {
86
- await serverHandle.stop();
87
- }
88
- finally {
89
- serverHandle = null;
90
- electron_1.app.exit(0);
91
- }
92
- });
93
- }
94
- async function onReady() {
95
- const paths = (0, paths_1.resolveRuntimePaths)();
96
- (0, menu_1.buildAppMenu)(paths, () => mainWindow);
97
- const iconPath = resolveIconPath();
98
- if (process.platform === 'darwin' && iconPath && electron_1.app.dock) {
99
- const img = electron_1.nativeImage.createFromPath(iconPath);
100
- if (!img.isEmpty())
101
- electron_1.app.dock.setIcon(img);
102
- }
103
- if (!electron_1.app.isPackaged) {
104
- const devUrl = process.env.SWARMCLAW_DEV_URL || DEV_URL_DEFAULT;
105
- console.log(`[swarmclaw] dev mode, loading ${devUrl}`);
106
- createMainWindow(devUrl);
107
- return;
108
- }
109
- serverLogFile = node_path_1.default.join(electron_1.app.getPath('userData'), 'logs', 'server.log');
110
- node_fs_1.default.mkdirSync(node_path_1.default.dirname(serverLogFile), { recursive: true });
111
- try {
112
- serverHandle = await (0, server_lifecycle_1.startEmbeddedServer)({
113
- paths,
114
- logFile: serverLogFile,
115
- onStdout: (c) => process.stdout.write(`[swarmclaw] ${c}`),
116
- onStderr: (c) => process.stderr.write(`[swarmclaw] ${c}`),
117
- onExit: (code, signal) => {
118
- if (!isQuitting) {
119
- console.error(`[swarmclaw] server exited unexpectedly (code=${code}, signal=${signal ?? 'none'})`);
120
- void showServerCrashDialog(code, signal);
121
- }
122
- },
123
- });
124
- }
125
- catch (err) {
126
- await showStartupFailureDialog(err, paths);
127
- electron_1.app.exit(1);
128
- return;
129
- }
130
- createMainWindow(serverHandle.url);
131
- void Promise.resolve().then(() => __importStar(require('./updater'))).then((m) => m.initAutoUpdater());
132
- }
133
- function resolveIconPath() {
134
- const candidate = electron_1.app.isPackaged
135
- ? node_path_1.default.join(process.resourcesPath, 'icon.png')
136
- : node_path_1.default.join(__dirname, '..', 'resources', 'icon.png');
137
- return node_fs_1.default.existsSync(candidate) ? candidate : undefined;
138
- }
139
- function createMainWindow(startUrl) {
140
- const iconPath = resolveIconPath();
141
- mainWindow = new electron_1.BrowserWindow({
142
- width: 1440,
143
- height: 900,
144
- minWidth: 1024,
145
- minHeight: 640,
146
- backgroundColor: '#0b0b0f',
147
- show: true,
148
- ...(iconPath ? { icon: iconPath } : {}),
149
- webPreferences: {
150
- contextIsolation: true,
151
- nodeIntegration: false,
152
- sandbox: false,
153
- },
154
- });
155
- const wc = mainWindow.webContents;
156
- if (!electron_1.app.isPackaged)
157
- wc.openDevTools({ mode: 'detach' });
158
- wc.on('did-start-loading', () => console.log('[swarmclaw] did-start-loading'));
159
- wc.on('did-finish-load', () => console.log('[swarmclaw] did-finish-load'));
160
- wc.on('did-fail-load', (_e, code, desc, url) => console.error(`[swarmclaw] did-fail-load code=${code} desc=${desc} url=${url}`));
161
- wc.on('render-process-gone', (_e, details) => console.error(`[swarmclaw] render-process-gone reason=${details.reason}`));
162
- wc.on('unresponsive', () => console.error('[swarmclaw] webContents unresponsive'));
163
- mainWindow.on('closed', () => {
164
- mainWindow = null;
165
- });
166
- mainWindow.webContents.setWindowOpenHandler(({ url }) => {
167
- if (url.startsWith(startUrl))
168
- return { action: 'allow' };
169
- void electron_1.shell.openExternal(url);
170
- return { action: 'deny' };
171
- });
172
- void mainWindow.loadURL(startUrl).catch((err) => {
173
- console.error('[swarmclaw] loadURL rejected:', err);
174
- });
175
- }
176
- async function showServerCrashDialog(code, signal) {
177
- const buttons = serverLogFile ? ['Open Logs Folder', 'Quit'] : ['Quit'];
178
- const quitButtonId = buttons.length - 1;
179
- const detail = buildLogDetail(`code=${code ?? 'null'} signal=${signal ?? 'none'}`);
180
- const res = await electron_1.dialog.showMessageBox({
181
- type: 'error',
182
- buttons,
183
- defaultId: quitButtonId,
184
- cancelId: quitButtonId,
185
- title: 'SwarmClaw stopped',
186
- message: 'The SwarmClaw server exited unexpectedly.',
187
- detail,
188
- });
189
- if (serverLogFile && res.response === 0)
190
- electron_1.shell.showItemInFolder(serverLogFile);
191
- electron_1.app.exit(1);
192
- }
193
- async function showStartupFailureDialog(err, paths) {
194
- const message = err instanceof Error ? err.message : String(err);
195
- const base = `${message}\n\nStandalone entry: ${paths.standaloneEntry}\nData dir: ${paths.dataDir}`;
196
- const detail = buildLogDetail(base);
197
- const buttons = serverLogFile ? ['Open Logs Folder', 'Quit'] : ['Quit'];
198
- const quitButtonId = buttons.length - 1;
199
- const res = await electron_1.dialog.showMessageBox({
200
- type: 'error',
201
- buttons,
202
- defaultId: quitButtonId,
203
- cancelId: quitButtonId,
204
- title: 'SwarmClaw failed to start',
205
- message: 'The embedded server did not start.',
206
- detail,
207
- });
208
- if (serverLogFile && res.response === 0)
209
- electron_1.shell.showItemInFolder(serverLogFile);
210
- }
211
- function buildLogDetail(base) {
212
- if (!serverLogFile)
213
- return base;
214
- const tail = (0, server_lifecycle_1.tailLogFile)(serverLogFile, LOG_TAIL_BYTES).trim();
215
- if (!tail)
216
- return `${base}\n\nLog file: ${serverLogFile}\n(no output captured yet)`;
217
- return `${base}\n\nLog tail (${serverLogFile}):\n${tail}`;
218
- }