switchroom 0.13.51 → 0.13.53

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.
@@ -13708,7 +13708,11 @@ var ScheduleEntrySchema = exports_external.object({
13708
13708
  cron: exports_external.string().describe("Cron expression (e.g., '0 8 * * *')"),
13709
13709
  prompt: exports_external.string().describe("Prompt to send at the scheduled time"),
13710
13710
  model: exports_external.string().optional().describe("DEPRECATED / IGNORED. Pre-v0.8 the singleton scheduler ran each " + "task as an isolated headless invocation and could set --model per " + "task. Post cron-fold-in (v0.8) the fire is injected into the agent's " + "running session, so it always uses the agent's configured model " + "— this field has no effect. Accepted (optional) only so existing " + "configs keep validating; set the model at the agent level instead. " + "See docs/scheduling.md."),
13711
- secrets: exports_external.array(exports_external.string().regex(/^[a-zA-Z0-9_\-/]+$/, "Secret key names must contain only alphanumeric characters, underscores, hyphens, and forward slashes")).default([]).describe("Vault key names this cron task may read via the vault-broker daemon. " + "Empty by default — broker requests for unlisted keys are denied. " + "Note: this is misconfiguration protection (a typo in cron-A doesn't " + "accidentally read cron-B's keys) rather than a security boundary — " + "anyone who can edit cron scripts can also edit switchroom.yaml, and " + "anyone with the vault passphrase can read the vault file directly. " + "See docs/configuration.md for the full framing.")
13711
+ secrets: exports_external.array(exports_external.string().regex(/^[a-zA-Z0-9_\-/]+$/, "Secret key names must contain only alphanumeric characters, underscores, hyphens, and forward slashes")).default([]).describe("Vault key names this cron task may read via the vault-broker daemon. " + "Empty by default — broker requests for unlisted keys are denied. " + "Note: this is misconfiguration protection (a typo in cron-A doesn't " + "accidentally read cron-B's keys) rather than a security boundary — " + "anyone who can edit cron scripts can also edit switchroom.yaml, and " + "anyone with the vault passphrase can read the vault file directly. " + "See docs/configuration.md for the full framing."),
13712
+ topic: exports_external.union([
13713
+ exports_external.string().min(1, "topic alias must be non-empty"),
13714
+ exports_external.number().int().positive("topic ID must be a positive integer")
13715
+ ]).optional().describe("Forum topic this cron fires into when the owning agent is in " + "supergroup-owned mode (channels.telegram.chat_id set). Either a " + 'string alias resolved against `topic_aliases` (e.g. "planning") ' + "or a numeric topic ID. Falls back to the agent's `default_topic_id` " + "when unset. Ignored for agents in fleet-shared or dm_only mode. " + "Alias-resolution happens at config-load — typos surface immediately. " + "See docs/rfcs/supergroup-mode.md.")
13712
13716
  });
13713
13717
  var AgentSoulSchema = exports_external.object({
13714
13718
  name: exports_external.string().describe("Agent persona name (e.g., 'Coach', 'Sage')"),
@@ -13820,8 +13824,35 @@ var TelegramChannelSchema = exports_external.object({
13820
13824
  }).optional().describe("Auto-dispatch rules: when a verified webhook event matches a rule, " + "inject the rendered prompt into the agent's live session (#1625). " + "Supports cooldowns, quiet hours, and label/action matchers. " + "Off by default — opt in per agent. See src/web/webhook-dispatch.ts."),
13821
13825
  webhook_rate_limit: exports_external.object({
13822
13826
  rpm: exports_external.number().int().positive()
13823
- }).optional().describe("Per-source rate limit for the webhook ingest path (#714). " + "Off by default — when this key is absent the handler skips " + "rate-limit checks entirely. Opt in by setting `rpm` to an " + "integer requests-per-minute (token bucket per (agent, source); " + "burst equal to rpm). When enabled, exceeding the limit returns " + "429 with Retry-After header; first throttle event per " + "(agent, source) per 60s window is written to " + "<agent>/telegram/issues.jsonl. " + "Cascades from defaults.channels.telegram.webhook_rate_limit.")
13824
- }).optional();
13827
+ }).optional().describe("Per-source rate limit for the webhook ingest path (#714). " + "Off by default — when this key is absent the handler skips " + "rate-limit checks entirely. Opt in by setting `rpm` to an " + "integer requests-per-minute (token bucket per (agent, source); " + "burst equal to rpm). When enabled, exceeding the limit returns " + "429 with Retry-After header; first throttle event per " + "(agent, source) per 60s window is written to " + "<agent>/telegram/issues.jsonl. " + "Cascades from defaults.channels.telegram.webhook_rate_limit."),
13828
+ chat_id: exports_external.string().regex(/^-\d+$/, 'supergroup chat_id must be a negative integer as a string (e.g. "-1001234567890")').optional().describe("Per-agent supergroup ID — overrides fleet `telegram.forum_chat_id`. " + "When set, requires `default_topic_id`. Negative integer as string. " + "Forbidden when `dm_only: true`. See docs/rfcs/supergroup-mode.md."),
13829
+ default_topic_id: exports_external.number().int().positive().optional().describe("Forum topic ID this agent's automated outbounds default to when " + "no more-specific alias resolves. Required when `chat_id` is set. " + "Telegram's General topic is `id=1` at MTProto but sends omit the " + "field — the outbound wrapper strips `message_thread_id === 1` " + "on send. Forbidden when `dm_only: true`."),
13830
+ topic_aliases: exports_external.record(exports_external.string(), exports_external.number().int().positive()).optional().describe("Operator-friendly names for forum topic IDs (e.g. " + "`{ general: 1, planning: 17, cron: 23, admin: 31, alerts: 41 }`). " + "Referenced from per-cron `topic:` fields and the outbound router " + "for autonomous events (boot → alerts, hostd → admin, etc.). " + "Cascades per-key through defaults → profile → agent.")
13831
+ }).optional().superRefine((tg, ctx) => {
13832
+ if (!tg)
13833
+ return;
13834
+ if (tg.chat_id != null && tg.default_topic_id == null) {
13835
+ ctx.addIssue({
13836
+ code: exports_external.ZodIssueCode.custom,
13837
+ message: "`channels.telegram.chat_id` requires `default_topic_id` — supergroup-mode agents need a fallback topic for unclassified outbounds.",
13838
+ path: ["default_topic_id"]
13839
+ });
13840
+ }
13841
+ if (tg.default_topic_id != null && tg.chat_id == null) {
13842
+ ctx.addIssue({
13843
+ code: exports_external.ZodIssueCode.custom,
13844
+ message: "`channels.telegram.default_topic_id` requires `chat_id` — default_topic_id is only meaningful when the agent owns its own supergroup.",
13845
+ path: ["chat_id"]
13846
+ });
13847
+ }
13848
+ if (tg.topic_aliases != null && tg.chat_id == null) {
13849
+ ctx.addIssue({
13850
+ code: exports_external.ZodIssueCode.custom,
13851
+ message: "`channels.telegram.topic_aliases` requires `chat_id` — aliases only resolve in supergroup-owned mode.",
13852
+ path: ["topic_aliases"]
13853
+ });
13854
+ }
13855
+ });
13825
13856
  var ChannelsSchema = exports_external.object({
13826
13857
  telegram: TelegramChannelSchema
13827
13858
  }).optional();
@@ -13838,6 +13869,12 @@ var GoogleWorkspaceConfigSchema = exports_external.object({
13838
13869
  approvers: exports_external.array(ApproverIdSchema).min(1).describe("Array of numeric Telegram user IDs authorized to approve drive onboarding. " + "At least one must be specified."),
13839
13870
  tier: GoogleWorkspaceTierSchema.optional().describe("RFC G Phase 1: which upstream MCP tier to expose. " + "core (default) = ~16 tools (Drive+Docs+Sheets+Calendar). " + "extended = ~40 tools (+Slides, Forms, Tasks, Chat). " + "complete = ~60+ tools (+Gmail; not recommended yet — see RFC G §5).")
13840
13871
  }).optional();
13872
+ var MicrosoftWorkspaceConfigSchema = exports_external.object({
13873
+ microsoft_client_id: exports_external.string().min(1).describe("Microsoft OAuth application (client) ID from Entra portal " + "(literal string or vault reference e.g. " + "'vault:microsoft-oauth-client-id')."),
13874
+ microsoft_client_secret: exports_external.string().min(1).optional().describe("Microsoft OAuth client secret. Optional — public-client apps " + "(Mobile + Desktop platform with 'Allow public client flows' " + "enabled) work without a secret; confidential clients pass " + "one. Either literal or vault reference e.g. " + "'vault:microsoft-oauth-client-secret'."),
13875
+ authority: exports_external.string().url().optional().describe("Microsoft authority endpoint. Defaults to " + "'https://login.microsoftonline.com/common' which accepts both " + "personal MSA and work/school tenants. Override only for " + "single-tenant deployments."),
13876
+ org_mode: exports_external.boolean().optional().describe("Opt-in to Teams + SharePoint surfaces (RFC §6.4). When true, " + "the v1 scope set adds Sites.ReadWrite.All AND the launcher " + "spawns softeria with --org-mode. Defaults to false — personal " + "MSA + standard work surfaces only. Flipping for an existing " + "consented account requires re-running 'auth microsoft account " + "add --replace' to consent the additional scope.")
13877
+ }).optional();
13841
13878
  var AgentGoogleWorkspaceConfigSchema = exports_external.object({
13842
13879
  account: exports_external.string().regex(/^[^@\s:]+@[^@\s:]+\.[^@\s:]+$/, {
13843
13880
  message: "google_workspace.account must be a Google account email like " + "'alice@example.com' (colons not allowed)"
@@ -13845,6 +13882,12 @@ var AgentGoogleWorkspaceConfigSchema = exports_external.object({
13845
13882
  approvers: exports_external.array(ApproverIdSchema).min(1).optional().describe("Per-agent approver override. When set, replaces (does not extend) " + "the top-level drive.approvers list for this agent's onboarding card."),
13846
13883
  tier: GoogleWorkspaceTierSchema.optional().describe("Per-agent tier override (RFC G Phase 1). When set, replaces the " + "top-level google_workspace.tier for this agent. Common case: most " + "agents on `core`, one specialist on `extended` for Slides access.")
13847
13884
  }).optional();
13885
+ var AgentMicrosoftWorkspaceConfigSchema = exports_external.object({
13886
+ account: exports_external.string().regex(/^[^@\s:]+@[^@\s:]+\.[^@\s:]+$/, {
13887
+ message: "microsoft_workspace.account must be a Microsoft account email like " + "'alice@outlook.com' or 'alice@contoso.com' (colons not allowed)"
13888
+ }).transform((v) => v.trim().toLowerCase()).optional().describe("RFC #1873: the Microsoft account this agent uses for the M365 MCP. " + "Must be a key in top-level `microsoft_accounts:` with this agent " + "listed in its `enabled_for[]`. Read by the auth-broker " + "(get-credentials, provider=microsoft) and by the scaffold to " + "decide whether to emit the `ms-365` MCP entry. Normalized to " + "lowercase so it matches the microsoft_accounts key (which is " + "also normalized)."),
13889
+ org_mode: exports_external.boolean().optional().describe("Per-agent org_mode override (RFC #1873 §6.4). When set, replaces " + "the top-level microsoft_workspace.org_mode for this agent. " + "Defaults to top-level value (which defaults to false).")
13890
+ }).optional();
13848
13891
  var ReactionsSchema = exports_external.object({
13849
13892
  enabled: exports_external.boolean().optional().describe("Master switch for the reaction-trigger path. When false, " + "reactions are still persisted via recordReaction but never " + "dispatched to the agent as synthetic inbound turns. Default true."),
13850
13893
  trigger_emojis: exports_external.array(exports_external.string()).optional().describe("Emoji allowlist that triggers a synthetic inbound when reacted " + "to a bot message. Default ['\uD83D\uDC4E', '❌', '\uD83D\uDC4D', '✅']. Cascade " + "mode: REPLACE (not union) — setting this at a layer replaces " + "lower layers entirely, so an operator can narrow to [] to " + "disable triggering without flipping `enabled`."),
@@ -13980,6 +14023,7 @@ var AgentSchema = exports_external.object({
13980
14023
  code_repos: exports_external.array(CodeRepoEntrySchema).optional().describe("Git repositories this agent is allowed to claim worktrees from. " + "Each entry provides a short name alias, a source path, and an " + "optional concurrency cap (default 5). When code_repos is set, " + "claim_worktree accepts the alias as the repo argument. " + "Absolute paths may always be passed regardless of this list."),
13981
14024
  drive: AgentGoogleWorkspaceConfigSchema.describe("RFC D legacy key — use `google_workspace:` instead. Per-agent " + "google_workspace overrides (currently approvers + tier). When set, " + "replaces the top-level approvers list for this agent. " + "google_client_id/secret are not per-agent — they live at the top level."),
13982
14025
  google_workspace: AgentGoogleWorkspaceConfigSchema.describe("RFC G canonical key. Per-agent Google Workspace overrides — currently " + "approvers (replaces, does not extend the top-level list) and tier " + "(`core` | `extended` | `complete`, replaces top-level default). " + "google_client_id/secret are not per-agent — they live at the top level. " + "Mutually exclusive with `drive:` on the same agent (loader fails fast " + "if both are set)."),
14026
+ microsoft_workspace: AgentMicrosoftWorkspaceConfigSchema.describe("RFC #1873 (Microsoft 365 integration). Per-agent Microsoft Workspace " + "override — pins the Microsoft account this agent reads via the " + "auth-broker (must be a key in top-level `microsoft_accounts:` with " + "this agent in its `enabled_for[]`) and optionally overrides org_mode. " + "microsoft_client_id/secret are not per-agent."),
13983
14027
  repos: exports_external.record(exports_external.string().regex(/^[a-z0-9][a-z0-9-]*$/, "Repo slug must be kebab-case ASCII: start with a lowercase letter or digit, contain only lowercase letters, digits, and hyphens"), exports_external.object({
13984
14028
  url: exports_external.string().min(1).describe("Git remote URL for the repo (e.g. 'git@github.com:org/repo.git' or " + "'https://github.com/org/repo.git'). Used verbatim for git clone."),
13985
14029
  branch_default: exports_external.string().optional().describe("Default branch to track (defaults to the remote's HEAD, typically 'main'). " + "The per-agent branch 'agent/<agentName>/main' fast-forwards to this branch " + "when the worktree is clean on session start.")
@@ -13994,6 +14038,33 @@ var AgentSchema = exports_external.object({
13994
14038
  pids_limit: exports_external.number().int().positive().optional(),
13995
14039
  cpus: exports_external.number().positive().optional()
13996
14040
  }).optional()
14041
+ }).superRefine((agent, ctx) => {
14042
+ if (agent.dm_only !== true)
14043
+ return;
14044
+ const tg = agent.channels?.telegram;
14045
+ if (tg == null)
14046
+ return;
14047
+ if (tg.chat_id != null) {
14048
+ ctx.addIssue({
14049
+ code: exports_external.ZodIssueCode.custom,
14050
+ message: "`dm_only: true` forbids `channels.telegram.chat_id` — DM-only agents have their own private chat, not a supergroup.",
14051
+ path: ["channels", "telegram", "chat_id"]
14052
+ });
14053
+ }
14054
+ if (tg.default_topic_id != null) {
14055
+ ctx.addIssue({
14056
+ code: exports_external.ZodIssueCode.custom,
14057
+ message: "`dm_only: true` forbids `channels.telegram.default_topic_id` — DMs don't have forum topics.",
14058
+ path: ["channels", "telegram", "default_topic_id"]
14059
+ });
14060
+ }
14061
+ if (tg.topic_aliases != null) {
14062
+ ctx.addIssue({
14063
+ code: exports_external.ZodIssueCode.custom,
14064
+ message: "`dm_only: true` forbids `channels.telegram.topic_aliases` — DMs don't have forum topics.",
14065
+ path: ["channels", "telegram", "topic_aliases"]
14066
+ });
14067
+ }
13997
14068
  });
13998
14069
  var TelegramConfigSchema = exports_external.object({
13999
14070
  bot_token: exports_external.string().describe("Telegram bot token or vault reference (e.g., 'vault:telegram-bot-token')"),
@@ -14075,6 +14146,7 @@ var SwitchroomConfigSchema = exports_external.object({
14075
14146
  }).optional().describe("Switchroom-auth-broker configuration (RFC H). Fleet-wide active account, " + "fallback order, admin-agent ACL, and ephemeral-consumer surface. " + "Required from the v0.8+ schema onwards; pre-v0.8 fleets are migrated " + "in-place by `switchroom apply` (see src/auth/migrate-schema.ts)."),
14076
14147
  drive: GoogleWorkspaceConfigSchema.describe("RFC D legacy key — use `google_workspace:` instead. Optional Google " + "Workspace onboarding configuration. When set, supplies Google OAuth " + "client credentials, the approver allowlist for `switchroom drive " + "connect`, and the optional tier knob. Env vars " + "(SWITCHROOM_GOOGLE_CLIENT_ID, SWITCHROOM_GOOGLE_CLIENT_SECRET, " + "SWITCHROOM_APPROVER_USER_ID) take precedence over this block when " + "set, preserving back-compat with the env-only flow shipped in #766."),
14077
14148
  google_workspace: GoogleWorkspaceConfigSchema.describe("RFC G canonical key. Top-level Google Workspace configuration — " + "OAuth client credentials, approver allowlist, and tier knob (`core` " + "| `extended` | `complete`, default `core`). Mutually exclusive with " + "`drive:` at the top level (loader fails fast if both are set)."),
14149
+ microsoft_workspace: MicrosoftWorkspaceConfigSchema.describe("RFC #1873 (Microsoft 365 integration). Top-level Microsoft Workspace " + "configuration — OAuth client credentials (Entra app), authority " + "endpoint (defaults to /common for personal MSA + work), and the " + "org_mode opt-in for Teams/SharePoint surfaces. Block is optional; " + "when omitted the broker does not register the Microsoft provider."),
14078
14150
  quota: QuotaConfigSchema.optional().describe("Optional weekly/monthly USD spend budgets rendered in the session " + "greeting. Usage is read from ccusage at runtime; no network calls."),
14079
14151
  host_control: HostControlConfigSchema.default({}).describe("Host-control daemon configuration. Defaults to enabled=true since " + "RFC C Phase 2 (docs/rfcs/host-control-daemon.md). Omit the block " + "to accept defaults; set `enabled: false` only on legacy systemd-" + "mode installs (removal tracked as RFC C Phase 3)."),
14080
14152
  hostd: HostdConfigSchema.default({}).describe("hostd verb-level knobs (RFC admin-agent-config-edit). Distinct " + "from `host_control:` which governs whether the daemon runs at " + "all. Currently scopes the opt-in flag and rate cap for the new " + "`config_propose_edit` verb (PR 1a — disabled by default)."),
@@ -14085,6 +14157,13 @@ var SwitchroomConfigSchema = exports_external.object({
14085
14157
  message: "Agent name must match the standard agent-name pattern"
14086
14158
  })).describe("Agent slugs that may read this account's vault slots " + "(`google:<account>:refresh_token` etc). Per-agent ACL is " + "enforced at the broker, not at the agent identity layer — " + "the agent still authenticates via socket-path-as-identity " + "per RFC D §4.1, broker just gates the cross-agent token share.")
14087
14159
  })).optional().describe("RFC G Phase 2: per-Google-account ACL for vault slots holding " + "OAuth refresh tokens. Maps account email → list of agents " + "permitted to read that account's slots. Written by `switchroom " + "auth google enable|disable` (Phase 3); read by the broker on " + "every Google slot access. Replaces RFC D's per-agent vault slot " + "scope (which can't express 'two agents share one Google account')."),
14160
+ microsoft_accounts: exports_external.record(exports_external.string().regex(/^[^@\s:]+@[^@\s:]+\.[^@\s:]+$/, {
14161
+ message: "Account key must be a Microsoft account email like 'alice@outlook.com' or 'alice@contoso.com' (colons not allowed)"
14162
+ }).transform((v) => v.trim().toLowerCase()), exports_external.object({
14163
+ enabled_for: exports_external.array(exports_external.string().regex(/^[a-z0-9][a-z0-9_-]{0,50}$/, {
14164
+ message: "Agent name must match the standard agent-name pattern"
14165
+ })).describe("Agent slugs that may read this Microsoft account's broker " + "credentials. Per-agent ACL enforced at the broker; agents " + "still authenticate via socket-path-as-identity, broker just " + "gates the cross-agent token share. Mirrors google_accounts.")
14166
+ })).optional().describe("RFC #1873: per-Microsoft-account ACL. Maps account email → list of " + "agents permitted to use that account's broker credentials. Written " + "by `switchroom auth microsoft enable|disable`; read by the broker " + "on get-credentials with provider=microsoft."),
14088
14167
  defaults: AgentDefaultsSchema.describe("Implicit bottom-of-cascade profile applied to every agent before " + "per-agent config and `extends:` resolution. Tools, mcp_servers, and " + "schedule are unioned/concatenated; scalars and nested objects are " + "shallow-merged with per-agent values winning."),
14089
14168
  profiles: exports_external.record(exports_external.string(), ProfileSchema).optional().describe("Named profile definitions. Agents reference via `extends: <name>`. " + "Inline profiles declared here take priority over filesystem " + "profiles/<name>/ directories when both exist."),
14090
14169
  agents: exports_external.record(exports_external.string().regex(/^[a-z0-9][a-z0-9_-]{0,50}$/, {
@@ -14264,130 +14343,6 @@ function applyAgentOverlays(config) {
14264
14343
  return { config, warnings };
14265
14344
  }
14266
14345
 
14267
- // src/config/loader.ts
14268
- class ConfigError extends Error {
14269
- details;
14270
- constructor(message, details) {
14271
- super(message);
14272
- this.details = details;
14273
- this.name = "ConfigError";
14274
- }
14275
- }
14276
- function formatZodErrors(error) {
14277
- return error.errors.map((e) => {
14278
- const path = e.path.join(".");
14279
- return ` ${path}: ${e.message}`;
14280
- });
14281
- }
14282
- function coerceLegacyGoogleWorkspaceKeys(parsed, filePath) {
14283
- const stableStringify = (v) => {
14284
- if (v === null || typeof v !== "object")
14285
- return JSON.stringify(v);
14286
- if (Array.isArray(v))
14287
- return `[${v.map(stableStringify).join(",")}]`;
14288
- const obj = v;
14289
- const keys = Object.keys(obj).sort();
14290
- return `{${keys.map((k) => `${JSON.stringify(k)}:${stableStringify(obj[k])}`).join(",")}}`;
14291
- };
14292
- const aliasInPlace = (obj, where) => {
14293
- const a = obj.drive;
14294
- const b = obj.google_workspace;
14295
- if (a !== undefined && b !== undefined) {
14296
- if (stableStringify(a) !== stableStringify(b)) {
14297
- throw new ConfigError(`Both \`drive:\` and \`google_workspace:\` are set on ${where} in ${filePath} with different values.`, [
14298
- " These are aliases — pick one and remove the other.",
14299
- " `google_workspace:` is the RFC G canonical key; `drive:` is the legacy alias.",
14300
- " Allowed during transition: setting both with identical values."
14301
- ]);
14302
- }
14303
- return;
14304
- }
14305
- if (a !== undefined && b === undefined)
14306
- obj.google_workspace = a;
14307
- if (b !== undefined && a === undefined)
14308
- obj.drive = b;
14309
- };
14310
- aliasInPlace(parsed, "the top level");
14311
- const agents = parsed.agents;
14312
- if (agents && typeof agents === "object" && !Array.isArray(agents)) {
14313
- for (const [name, agent] of Object.entries(agents)) {
14314
- if (agent && typeof agent === "object" && !Array.isArray(agent)) {
14315
- aliasInPlace(agent, `agent \`${name}\``);
14316
- }
14317
- }
14318
- }
14319
- }
14320
- function findConfigFile(startDir) {
14321
- const envPath = process.env.SWITCHROOM_CONFIG;
14322
- const home2 = homedir();
14323
- const userDir = resolve3(home2, ".switchroom");
14324
- const searchPaths = [
14325
- envPath ? resolve3(envPath) : null,
14326
- startDir ? resolve3(startDir, "switchroom.yaml") : null,
14327
- startDir ? resolve3(startDir, "switchroom.yml") : null,
14328
- startDir ? resolve3(startDir, "clerk.yaml") : null,
14329
- startDir ? resolve3(startDir, "clerk.yml") : null,
14330
- resolve3(process.cwd(), "switchroom.yaml"),
14331
- resolve3(process.cwd(), "switchroom.yml"),
14332
- resolve3(process.cwd(), "clerk.yaml"),
14333
- resolve3(process.cwd(), "clerk.yml"),
14334
- resolve3(userDir, "switchroom.yaml"),
14335
- resolve3(userDir, "switchroom.yml"),
14336
- resolve3(userDir, "clerk.yaml"),
14337
- resolve3(userDir, "clerk.yml")
14338
- ].filter(Boolean);
14339
- for (const path of searchPaths) {
14340
- if (existsSync3(path)) {
14341
- return path;
14342
- }
14343
- }
14344
- throw new ConfigError("No switchroom.yaml found", searchPaths.map((p) => ` Searched: ${p}`));
14345
- }
14346
- function loadConfig(configPath) {
14347
- const filePath = configPath ?? findConfigFile();
14348
- if (!existsSync3(filePath)) {
14349
- throw new ConfigError(`Config file not found: ${filePath}`);
14350
- }
14351
- let raw;
14352
- try {
14353
- raw = readFileSync2(filePath, "utf-8");
14354
- } catch (err) {
14355
- throw new ConfigError(`Failed to read config file: ${filePath}`, [
14356
- ` ${err.message}`
14357
- ]);
14358
- }
14359
- let parsed;
14360
- try {
14361
- parsed = $parse(raw);
14362
- } catch (err) {
14363
- throw new ConfigError(`Invalid YAML in ${filePath}`, [
14364
- ` ${err.message}`
14365
- ]);
14366
- }
14367
- if (parsed && typeof parsed === "object" && !Array.isArray(parsed) && parsed.clerk !== undefined && parsed.switchroom === undefined) {
14368
- const obj = parsed;
14369
- obj.switchroom = obj.clerk;
14370
- delete obj.clerk;
14371
- }
14372
- if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
14373
- coerceLegacyGoogleWorkspaceKeys(parsed, filePath);
14374
- }
14375
- let config;
14376
- try {
14377
- config = SwitchroomConfigSchema.parse(parsed);
14378
- } catch (err) {
14379
- if (err instanceof ZodError) {
14380
- throw new ConfigError("Invalid switchroom.yaml configuration", formatZodErrors(err));
14381
- }
14382
- throw err;
14383
- }
14384
- applyAgentOverlays(config);
14385
- return config;
14386
- }
14387
-
14388
- // src/agents/compose.ts
14389
- import { createHash } from "node:crypto";
14390
-
14391
14346
  // src/config/merge.ts
14392
14347
  function dedupe(items) {
14393
14348
  const seen = new Set;
@@ -14416,6 +14371,20 @@ function deepMergeJson(base, override) {
14416
14371
  }
14417
14372
  return out;
14418
14373
  }
14374
+ function resolveAgentConfig(defaults, profiles, agent) {
14375
+ if (!mergeAgentConfig.suppressDeprecationLogs && !mergeAgentConfig.notifiedWorkerIsolationMove && defaults?.subagents?.worker?.isolation === "worktree") {
14376
+ mergeAgentConfig.notifiedWorkerIsolationMove = true;
14377
+ console.warn("[switchroom] NOTICE: defaults.subagents.worker.isolation moved to the " + "`coding` profile in switchroom 0.6.6 (#682). Agents extending coding " + "still get worktree-isolated workers; other agents would have hard-failed " + "the first time they delegated. See CHANGELOG.");
14378
+ }
14379
+ const name = agent.extends;
14380
+ const profile = name && profiles ? profiles[name] : undefined;
14381
+ if (!profile) {
14382
+ return mergeAgentConfig(defaults, agent);
14383
+ }
14384
+ const { extends: _unused, ...profileWithoutExtends } = profile;
14385
+ const layered = mergeAgentConfig(defaults, profileWithoutExtends);
14386
+ return mergeAgentConfig(layered, agent);
14387
+ }
14419
14388
  function foldDeprecatedTelegramFields(config) {
14420
14389
  const c = config;
14421
14390
  const root = c;
@@ -14683,6 +14652,156 @@ function mergeAgentConfig(defaultsIn, agentIn) {
14683
14652
  mergeAgentConfig.notifiedWorkerIsolationMove = false;
14684
14653
  })(mergeAgentConfig ||= {});
14685
14654
 
14655
+ // src/config/loader.ts
14656
+ class ConfigError extends Error {
14657
+ details;
14658
+ constructor(message, details) {
14659
+ super(message);
14660
+ this.details = details;
14661
+ this.name = "ConfigError";
14662
+ }
14663
+ }
14664
+ function formatZodErrors(error) {
14665
+ return error.errors.map((e) => {
14666
+ const path = e.path.join(".");
14667
+ return ` ${path}: ${e.message}`;
14668
+ });
14669
+ }
14670
+ function coerceLegacyGoogleWorkspaceKeys(parsed, filePath) {
14671
+ const stableStringify = (v) => {
14672
+ if (v === null || typeof v !== "object")
14673
+ return JSON.stringify(v);
14674
+ if (Array.isArray(v))
14675
+ return `[${v.map(stableStringify).join(",")}]`;
14676
+ const obj = v;
14677
+ const keys = Object.keys(obj).sort();
14678
+ return `{${keys.map((k) => `${JSON.stringify(k)}:${stableStringify(obj[k])}`).join(",")}}`;
14679
+ };
14680
+ const aliasInPlace = (obj, where) => {
14681
+ const a = obj.drive;
14682
+ const b = obj.google_workspace;
14683
+ if (a !== undefined && b !== undefined) {
14684
+ if (stableStringify(a) !== stableStringify(b)) {
14685
+ throw new ConfigError(`Both \`drive:\` and \`google_workspace:\` are set on ${where} in ${filePath} with different values.`, [
14686
+ " These are aliases — pick one and remove the other.",
14687
+ " `google_workspace:` is the RFC G canonical key; `drive:` is the legacy alias.",
14688
+ " Allowed during transition: setting both with identical values."
14689
+ ]);
14690
+ }
14691
+ return;
14692
+ }
14693
+ if (a !== undefined && b === undefined)
14694
+ obj.google_workspace = a;
14695
+ if (b !== undefined && a === undefined)
14696
+ obj.drive = b;
14697
+ };
14698
+ aliasInPlace(parsed, "the top level");
14699
+ const agents = parsed.agents;
14700
+ if (agents && typeof agents === "object" && !Array.isArray(agents)) {
14701
+ for (const [name, agent] of Object.entries(agents)) {
14702
+ if (agent && typeof agent === "object" && !Array.isArray(agent)) {
14703
+ aliasInPlace(agent, `agent \`${name}\``);
14704
+ }
14705
+ }
14706
+ }
14707
+ }
14708
+ function findConfigFile(startDir) {
14709
+ const envPath = process.env.SWITCHROOM_CONFIG;
14710
+ const home2 = homedir();
14711
+ const userDir = resolve3(home2, ".switchroom");
14712
+ const searchPaths = [
14713
+ envPath ? resolve3(envPath) : null,
14714
+ startDir ? resolve3(startDir, "switchroom.yaml") : null,
14715
+ startDir ? resolve3(startDir, "switchroom.yml") : null,
14716
+ startDir ? resolve3(startDir, "clerk.yaml") : null,
14717
+ startDir ? resolve3(startDir, "clerk.yml") : null,
14718
+ resolve3(process.cwd(), "switchroom.yaml"),
14719
+ resolve3(process.cwd(), "switchroom.yml"),
14720
+ resolve3(process.cwd(), "clerk.yaml"),
14721
+ resolve3(process.cwd(), "clerk.yml"),
14722
+ resolve3(userDir, "switchroom.yaml"),
14723
+ resolve3(userDir, "switchroom.yml"),
14724
+ resolve3(userDir, "clerk.yaml"),
14725
+ resolve3(userDir, "clerk.yml")
14726
+ ].filter(Boolean);
14727
+ for (const path of searchPaths) {
14728
+ if (existsSync3(path)) {
14729
+ return path;
14730
+ }
14731
+ }
14732
+ throw new ConfigError("No switchroom.yaml found", searchPaths.map((p) => ` Searched: ${p}`));
14733
+ }
14734
+ function loadConfig(configPath) {
14735
+ const filePath = configPath ?? findConfigFile();
14736
+ if (!existsSync3(filePath)) {
14737
+ throw new ConfigError(`Config file not found: ${filePath}`);
14738
+ }
14739
+ let raw;
14740
+ try {
14741
+ raw = readFileSync2(filePath, "utf-8");
14742
+ } catch (err) {
14743
+ throw new ConfigError(`Failed to read config file: ${filePath}`, [
14744
+ ` ${err.message}`
14745
+ ]);
14746
+ }
14747
+ let parsed;
14748
+ try {
14749
+ parsed = $parse(raw);
14750
+ } catch (err) {
14751
+ throw new ConfigError(`Invalid YAML in ${filePath}`, [
14752
+ ` ${err.message}`
14753
+ ]);
14754
+ }
14755
+ if (parsed && typeof parsed === "object" && !Array.isArray(parsed) && parsed.clerk !== undefined && parsed.switchroom === undefined) {
14756
+ const obj = parsed;
14757
+ obj.switchroom = obj.clerk;
14758
+ delete obj.clerk;
14759
+ }
14760
+ if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
14761
+ coerceLegacyGoogleWorkspaceKeys(parsed, filePath);
14762
+ }
14763
+ let config;
14764
+ try {
14765
+ config = SwitchroomConfigSchema.parse(parsed);
14766
+ } catch (err) {
14767
+ if (err instanceof ZodError) {
14768
+ throw new ConfigError("Invalid switchroom.yaml configuration", formatZodErrors(err));
14769
+ }
14770
+ throw err;
14771
+ }
14772
+ applyAgentOverlays(config);
14773
+ validateAllCronTopicAliases(config, filePath);
14774
+ return config;
14775
+ }
14776
+ function validateAllCronTopicAliases(config, filePath) {
14777
+ const issues = [];
14778
+ for (const [agentName, agentRaw] of Object.entries(config.agents)) {
14779
+ if (!agentRaw)
14780
+ continue;
14781
+ const resolved = resolveAgentConfig(config.defaults, config.profiles, agentRaw);
14782
+ const schedule = resolved.schedule ?? [];
14783
+ if (schedule.length === 0)
14784
+ continue;
14785
+ const tg = resolved.channels?.telegram;
14786
+ const aliases = new Set(Object.keys(tg?.topic_aliases ?? {}));
14787
+ for (const entry of schedule) {
14788
+ if (entry.topic == null)
14789
+ continue;
14790
+ if (typeof entry.topic === "number")
14791
+ continue;
14792
+ if (!aliases.has(entry.topic)) {
14793
+ issues.push(` agents.${agentName}.schedule cron \`${entry.cron}\`: ` + `topic alias "${entry.topic}" is not defined in ` + `channels.telegram.topic_aliases.`);
14794
+ }
14795
+ }
14796
+ }
14797
+ if (issues.length > 0) {
14798
+ throw new ConfigError(`Cron \`topic:\` alias references unknown topic_aliases in ${filePath}`, issues);
14799
+ }
14800
+ }
14801
+
14802
+ // src/agents/compose.ts
14803
+ import { createHash } from "node:crypto";
14804
+
14686
14805
  // src/vault/broker/peercred.ts
14687
14806
  var RESERVED_AGENT_NAMES = new Set(["operator", "hostd"]);
14688
14807
  function isReservedAgentName(name) {