@skaile/workspaces 0.53.0 → 1.0.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 (137) hide show
  1. package/CHANGELOG.md +14 -0
  2. package/dist/{asset-feeds-OEGJ6NOF.js → asset-feeds-677S5NX7.js} +7 -7
  3. package/dist/{asset-feeds-OEGJ6NOF.js.map → asset-feeds-677S5NX7.js.map} +1 -1
  4. package/dist/asset-manager/index.js +5 -5
  5. package/dist/asset-manager/installer.js +4 -4
  6. package/dist/{chunk-VGT2R662.js → chunk-43JDPQJ4.js} +3 -3
  7. package/dist/{chunk-VGT2R662.js.map → chunk-43JDPQJ4.js.map} +1 -1
  8. package/dist/{chunk-EOINYN5T.js → chunk-DW5MIJK3.js} +3 -3
  9. package/dist/{chunk-EOINYN5T.js.map → chunk-DW5MIJK3.js.map} +1 -1
  10. package/dist/{chunk-VE2UIJ7Y.js → chunk-EXNTTJGP.js} +3 -43
  11. package/dist/chunk-EXNTTJGP.js.map +1 -0
  12. package/dist/{chunk-7ZWLZ5H3.js → chunk-FLRHP3UC.js} +3 -3
  13. package/dist/{chunk-7ZWLZ5H3.js.map → chunk-FLRHP3UC.js.map} +1 -1
  14. package/dist/{chunk-V4BGVOJC.js → chunk-K5JIAHDV.js} +6 -6
  15. package/dist/{chunk-V4BGVOJC.js.map → chunk-K5JIAHDV.js.map} +1 -1
  16. package/dist/{chunk-3IHBGDCG.js → chunk-KSISPZV3.js} +2 -2
  17. package/dist/{chunk-3IHBGDCG.js.map → chunk-KSISPZV3.js.map} +1 -1
  18. package/dist/{chunk-WD2NRI3T.js → chunk-PLQVAEM2.js} +2 -2
  19. package/dist/{chunk-WD2NRI3T.js.map → chunk-PLQVAEM2.js.map} +1 -1
  20. package/dist/{chunk-TCNYSHPM.js → chunk-SFVEHSCI.js} +4 -4
  21. package/dist/{chunk-TCNYSHPM.js.map → chunk-SFVEHSCI.js.map} +1 -1
  22. package/dist/{chunk-QLLFCQU5.js → chunk-WSQ5J7CE.js} +403 -1469
  23. package/dist/chunk-WSQ5J7CE.js.map +1 -0
  24. package/dist/{chunk-BXC5547R.js → chunk-XD7GYMAU.js} +3 -3
  25. package/dist/{chunk-BXC5547R.js.map → chunk-XD7GYMAU.js.map} +1 -1
  26. package/dist/cli/index.js +30 -32
  27. package/dist/cli/index.js.map +1 -1
  28. package/dist/connectors/config.js +4 -4
  29. package/dist/connectors/index.js +5 -7
  30. package/dist/connectors/src/config.d.ts +1 -74
  31. package/dist/connectors/src/config.d.ts.map +1 -1
  32. package/dist/connectors/src/connector-manager.d.ts +13 -137
  33. package/dist/connectors/src/connector-manager.d.ts.map +1 -1
  34. package/dist/connectors/src/connector-types.d.ts +3 -25
  35. package/dist/connectors/src/connector-types.d.ts.map +1 -1
  36. package/dist/connectors/src/fleet-utils.d.ts +2 -30
  37. package/dist/connectors/src/fleet-utils.d.ts.map +1 -1
  38. package/dist/connectors/src/fs-utils.d.ts +1 -2
  39. package/dist/connectors/src/fs-utils.d.ts.map +1 -1
  40. package/dist/connectors/src/index.d.ts +2 -12
  41. package/dist/connectors/src/index.d.ts.map +1 -1
  42. package/dist/connectors/src/watcher.d.ts +1 -5
  43. package/dist/connectors/src/watcher.d.ts.map +1 -1
  44. package/dist/core/index.js +3 -3
  45. package/dist/deploy/index.js +3 -3
  46. package/dist/{ensure-sources-GJOXWVWO.js → ensure-sources-OCMHK7LT.js} +5 -5
  47. package/dist/{ensure-sources-GJOXWVWO.js.map → ensure-sources-OCMHK7LT.js.map} +1 -1
  48. package/dist/factory-assets/connectors/deploy.js +5 -7
  49. package/dist/factory-assets/connectors/devserver.js +5 -7
  50. package/dist/factory-assets/connectors/flow/adapter.js +5 -7
  51. package/dist/factory-assets/connectors/flow/engine.js +3 -3
  52. package/dist/factory-assets/connectors/flow/run-flow.js +6 -8
  53. package/dist/factory-assets/connectors/flow.js +5 -7
  54. package/dist/factory-assets/connectors/git.js +5 -7
  55. package/dist/factory-assets/connectors/gmail.js +5 -7
  56. package/dist/factory-assets/connectors/googledrive/CONNECTOR.md +14 -128
  57. package/dist/factory-assets/connectors/googledrive/driver.d.ts +6 -13
  58. package/dist/factory-assets/connectors/googledrive/driver.d.ts.map +1 -1
  59. package/dist/factory-assets/connectors/googledrive.js +5 -7
  60. package/dist/factory-assets/connectors/local.js +5 -7
  61. package/dist/factory-assets/connectors/mattermost.js +5 -7
  62. package/dist/factory-assets/connectors/memory.js +5 -7
  63. package/dist/factory-assets/connectors/minio.js +5 -7
  64. package/dist/factory-assets/connectors/postgres.js +5 -7
  65. package/dist/factory-assets/connectors/s3.js +5 -7
  66. package/dist/factory-assets/connectors/sharepoint/CONNECTOR.md +13 -159
  67. package/dist/factory-assets/connectors/sharepoint/driver.d.ts +6 -12
  68. package/dist/factory-assets/connectors/sharepoint/driver.d.ts.map +1 -1
  69. package/dist/factory-assets/connectors/sharepoint.js +5 -7
  70. package/dist/factory-assets/connectors/sqlite.js +5 -7
  71. package/dist/factory-assets/connectors/static-server.js +5 -7
  72. package/dist/factory-assets/connectors/tunnel.js +5 -7
  73. package/dist/factory-assets/connectors/webdav/CONNECTOR.md +13 -118
  74. package/dist/factory-assets/connectors/webdav/driver.d.ts +6 -15
  75. package/dist/factory-assets/connectors/webdav/driver.d.ts.map +1 -1
  76. package/dist/factory-assets/connectors/webdav.js +5 -7
  77. package/dist/factory-assets/connectors/xstate-store.js +5 -7
  78. package/dist/factory-assets/connectors/xstate.js +5 -7
  79. package/dist/{flows-AGPIE6JM.js → flows-36PZESON.js} +4 -4
  80. package/dist/{flows-AGPIE6JM.js.map → flows-36PZESON.js.map} +1 -1
  81. package/dist/library/index.js +4 -4
  82. package/dist/library/install.js +3 -3
  83. package/dist/{open-library-ERKRGH4B.js → open-library-WRFYABFP.js} +7 -7
  84. package/dist/{open-library-ERKRGH4B.js.map → open-library-WRFYABFP.js.map} +1 -1
  85. package/dist/{paths-D6RUQ522.js → paths-EUNVMONC.js} +5 -5
  86. package/dist/{paths-D6RUQ522.js.map → paths-EUNVMONC.js.map} +1 -1
  87. package/dist/{plugin-store-SGNJTBYS.js → plugin-store-35KIMX6W.js} +5 -5
  88. package/dist/{plugin-store-SGNJTBYS.js.map → plugin-store-35KIMX6W.js.map} +1 -1
  89. package/dist/runner/index.js +7 -9
  90. package/dist/sdk/asset-manager.js +5 -5
  91. package/dist/sdk/core.js +3 -3
  92. package/dist/sdk/flow.js +3 -3
  93. package/dist/sdk/index.js +7 -9
  94. package/dist/sdk/index.js.map +1 -1
  95. package/dist/sdk/runner.js +7 -9
  96. package/dist/{setup-IV2JFW3T.js → setup-HM6HATAC.js} +5 -5
  97. package/dist/{setup-IV2JFW3T.js.map → setup-HM6HATAC.js.map} +1 -1
  98. package/dist/{source-FGOMQMZT.js → source-EZ5Y3CKP.js} +8 -8
  99. package/dist/{source-FGOMQMZT.js.map → source-EZ5Y3CKP.js.map} +1 -1
  100. package/dist/{store-client-GJT2XQ5Z.js → store-client-BUUF7BPK.js} +5 -5
  101. package/dist/{store-client-GJT2XQ5Z.js.map → store-client-BUUF7BPK.js.map} +1 -1
  102. package/dist/tui/index.js +7 -9
  103. package/dist/tui/index.js.map +1 -1
  104. package/dist/workspace-plugin/adapters/mcp.js +3 -3
  105. package/dist/workspace-plugin/adapters/omp.js +3 -3
  106. package/dist/workspace-plugin/index.js +1 -1
  107. package/package.json +1 -13
  108. package/dist/chunk-OVRSNIKJ.js +0 -72
  109. package/dist/chunk-OVRSNIKJ.js.map +0 -1
  110. package/dist/chunk-QLLFCQU5.js.map +0 -1
  111. package/dist/chunk-RAIRWFAN.js +0 -843
  112. package/dist/chunk-RAIRWFAN.js.map +0 -1
  113. package/dist/chunk-VE2UIJ7Y.js.map +0 -1
  114. package/dist/connectors/rclone-config.d.ts +0 -2
  115. package/dist/connectors/rclone-config.js +0 -4
  116. package/dist/connectors/rclone-config.js.map +0 -1
  117. package/dist/connectors/rclone.d.ts +0 -2
  118. package/dist/connectors/rclone.js +0 -5
  119. package/dist/connectors/rclone.js.map +0 -1
  120. package/dist/connectors/src/fleet-health-gate.d.ts +0 -105
  121. package/dist/connectors/src/fleet-health-gate.d.ts.map +0 -1
  122. package/dist/connectors/src/mount-placeholder.d.ts +0 -131
  123. package/dist/connectors/src/mount-placeholder.d.ts.map +0 -1
  124. package/dist/connectors/src/rclone-config/googledrive.d.ts +0 -59
  125. package/dist/connectors/src/rclone-config/googledrive.d.ts.map +0 -1
  126. package/dist/connectors/src/rclone-config/index.d.ts +0 -9
  127. package/dist/connectors/src/rclone-config/index.d.ts.map +0 -1
  128. package/dist/connectors/src/rclone-config/onedrive.d.ts +0 -48
  129. package/dist/connectors/src/rclone-config/onedrive.d.ts.map +0 -1
  130. package/dist/connectors/src/rclone-config/sanitize.d.ts +0 -9
  131. package/dist/connectors/src/rclone-config/sanitize.d.ts.map +0 -1
  132. package/dist/connectors/src/rclone-config/webdav.d.ts +0 -50
  133. package/dist/connectors/src/rclone-config/webdav.d.ts.map +0 -1
  134. package/dist/connectors/src/rclone-process-manager.d.ts +0 -316
  135. package/dist/connectors/src/rclone-process-manager.d.ts.map +0 -1
  136. package/dist/connectors/src/rclone-token-refresh.d.ts +0 -84
  137. package/dist/connectors/src/rclone-token-refresh.d.ts.map +0 -1
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../connectors/src/connector-base.ts","../factory-assets/connectors/deploy/adapter.ts","../factory-assets/connectors/devserver/adapter.ts","../factory-assets/connectors/git/driver.ts","../factory-assets/connectors/gmail/adapter.ts","../factory-assets/connectors/googledrive/driver.ts","../factory-assets/connectors/local/driver.ts","../factory-assets/connectors/mattermost/adapter.ts","../factory-assets/connectors/memory/adapter.ts","../factory-assets/connectors/minio/adapter.ts","../factory-assets/connectors/postgres/adapter.ts","../factory-assets/connectors/s3/driver.ts","../factory-assets/connectors/sharepoint/driver.ts","../factory-assets/connectors/sqlite/adapter.ts","../factory-assets/connectors/static-server/adapter.ts","../factory-assets/connectors/tunnel/adapter.ts","../factory-assets/connectors/webdav/driver.ts","../factory-assets/connectors/xstate/adapter.ts","../factory-assets/connectors/xstate-store/adapter.ts","../connectors/src/connector-registry.ts","../connectors/src/connector-types.ts","../connectors/src/fleet-health-gate.ts","../connectors/src/fleet-utils.ts","../connectors/src/mount-placeholder.ts","../connectors/src/connector-manager.ts","../connectors/src/connector-prompt.ts","../connectors/src/credential-helper-script.ts","../connectors/src/log-buffer.ts","../connectors/src/managed-gitconfig.ts","../connectors/src/npm-installer.ts","../connectors/src/rclone-token-refresh.ts","../connectors/src/worktree.ts","../factory-assets/connectors/flow/adapter.ts"],"names":["createConnector","execSync","credentialTag","stat","existsSync","mkdirSync","path","resolve","table","result","join","dirname","writeFileSync","DEFAULT_CACHE_BASE","cacheBase","parseAuthBlob","quoteIdent","readFileSync","instanceToStatus","t","_ctx","z","z2","entry","renameSync","require","now","git"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAgBO,IAAe,oBAAf,MAAsD;AAAA,EAEjD,MAAc,YAAA,CAAa,EAAE,MAAM,WAAA,EAAa,OAAA,EAAS,WAAW,CAAA;AAAA,EAC9E,UAAU,MAAA,EAAsB;AAC9B,IAAA,IAAA,CAAK,GAAA,GAAM,MAAA;AAAA,EACb;AAAA;AAAA,EAGU,UAAA;AAAA,EAQV,KAAA,CACE,OAAA,EACA,QAAA,EACA,QAAA,EACa;AACb,IAAA,IAAA,CAAK,UAAA,GAAa,QAAA;AAClB,IAAA,OAAO;AAAA,MACL,OAAO,YAAY;AACjB,QAAA,IAAA,CAAK,UAAA,GAAa,MAAA;AAAA,MACpB;AAAA,KACF;AAAA,EACF;AAAA,EAEA,MAAM,YAAY,OAAA,EAAuD;AACvE,IAAA,OAAO,MAAA;AAAA,EACT;AAAA,EACA,MAAM,eAAe,OAAA,EAAuD;AAC1E,IAAA,OAAO,MAAA;AAAA,EACT;AAAA;AAAA,EAGU,UAAA,CACR,WAAA,EACA,KAAA,EACA,SAAA,EACiB;AACjB,IAAA,OAAO;AAAA,MACL,IAAI,WAAA,CAAY,EAAA;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AA,CAAO,CAAA,CAAE,WAAA,IAAe,WAAW,CAAA;AAAA,IAChD,IAAA,EAAO,EAAE,IAAA,IAAgC,OAAA;AAAA,IACzC,QAAA,EAAW,EAAE,QAAA,IAAwC,SAAA;AAAA,IACrD,UAAA,EAAY,MAAA,CAAO,CAAA,CAAE,UAAA,IAAc,EAAE;AAAA,GACvC,CAAE,CAAA;AACN;AAEA,SAAS,cAAc,KAAA,EAA0B;AAC/C,EAAA,IAAI;AACF,IAAA,MAAM,MAAA,GAAS,IAAA,CAAK,KAAA,CAAM,KAAK,CAAA;AAC/B,IAAA,OAAO,KAAA,CAAM,OAAA,CAAQ,MAAM,CAAA,GAAI,SAAS,EAAC;AAAA,EAC3C,CAAA,CAAA,MAAQ;AACN,IAAA,OAAO,EAAC;AAAA,EACV;AACF;AAEA,SAAS,qBAAqB,KAAA,EAA6B;AACzD,EAAA,IAAI,KAAA,IAAS,OAAO,KAAA,KAAU,QAAA,EAAU,OAAO,KAAA;AAC/C,EAAA,IAAI,OAAO,UAAU,QAAA,EAAU;AAC7B,IAAA,IAAI;AACF,MAAA,OAAO,IAAA,CAAK,MAAM,KAAK,CAAA;AAAA,IACzB,CAAA,CAAA,MAAQ;AACN,MAAA,OAAO,EAAE,MAAM,MAAA,EAAO;AAAA,IACxB;AAAA,EACF;AACA,EAAA,OAAO,EAAE,MAAM,MAAA,EAAO;AACxB;AAWO,SAAS,eAAA,GAA+B;AAC7C,EAAA,OAAO,IAAI,WAAA,EAAY;AACzB","file":"chunk-QLLFCQU5.js","sourcesContent":["import { createLogger } from \"@skaile/workspaces/core/logging\";\nimport type { Logger } from \"@skaile/workspaces/types\";\nimport type {\n ConnectContext,\n Connector,\n ConnectorChangeEvent,\n ConnectorDeclaration,\n ConnectorHandle,\n} from \"./connector-types.js\";\nimport type { WatchHandle, WatchOptions } from \"./shared-types.js\";\n\n/**\n * Base class for unified connectors. Subclasses set `filesystem` and/or `tools`\n * face objects and implement `connect`/`disconnect`. The manager replaces\n * `this.log` via `setLogger()` after construction — do not initialise your own.\n */\nexport abstract class AbstractConnector implements Connector {\n abstract readonly name: string;\n protected log: Logger = createLogger({ kind: \"connector\", subkind: \"unknown\" });\n setLogger(logger: Logger): void {\n this.log = logger;\n }\n\n /** Set by the default `watch()`; call after mutations to emit change events. */\n protected emitChange?: (event: ConnectorChangeEvent) => void;\n\n abstract connect(\n declaration: ConnectorDeclaration,\n ctx: ConnectContext,\n ): Promise<ConnectorHandle>;\n abstract disconnect(handle: ConnectorHandle): Promise<void>;\n\n watch(\n _handle: ConnectorHandle,\n callback: (e: ConnectorChangeEvent) => void,\n _options?: WatchOptions,\n ): WatchHandle {\n this.emitChange = callback;\n return {\n close: async () => {\n this.emitChange = undefined;\n },\n };\n }\n\n async onHibernate(_handle: ConnectorHandle): Promise<string | undefined> {\n return undefined;\n }\n async onSessionClose(_handle: ConnectorHandle): Promise<string | undefined> {\n return undefined;\n }\n\n /** Build a handle. Pass `mountPath` only for mountable connectors. */\n protected makeHandle(\n declaration: ConnectorDeclaration,\n state: unknown,\n mountPath?: string,\n ): ConnectorHandle {\n return {\n id: declaration.id,\n driver: this.name,\n access: declaration.access,\n status: \"connected\",\n mountPath,\n state,\n };\n }\n}\n","/**\n * DeployConnector — build at a git ref and push to remote deployment targets.\n *\n * Supported providers: mock, fly, vercel, docker-push, rsync.\n * Only `mock` is fully implemented.\n */\n\nimport { execSync } from \"node:child_process\";\nimport type {\n ConnectContext,\n ConnectorDeclaration,\n ConnectorHandle,\n OperationDescriptor,\n RuntimeSkillDescriptor,\n ToolFace,\n} from \"@skaile/workspaces/connectors\";\nimport { AbstractConnector } from \"@skaile/workspaces/connectors\";\n\ninterface DeployState {\n provider: string;\n defaults: Record<string, string>;\n deployments: Map<string, DeploymentRecord>;\n repoRoot: string | null;\n worktreeDir: string;\n}\n\ninterface DeploymentRecord {\n id: string;\n url: string;\n ref?: string;\n buildCommand: string;\n buildDir: string;\n deployedAt: string;\n status: \"deploying\" | \"live\" | \"failed\" | \"removed\";\n}\n\n/**\n * Connector for building and deploying to remote targets.\n * Supports push, status, list, teardown, and logs operations. Currently implements the `mock` provider; fly, vercel, docker-push, and rsync are planned.\n * @docLink packages/factory-assets/concepts#deploy-connector\n */\nexport class DeployConnector extends AbstractConnector {\n readonly name = \"deploy\";\n\n tools: ToolFace;\n\n constructor() {\n super();\n this.tools = {\n describeOperations: (handle) => this._describeOperations(handle),\n executeOp: (handle, operation, args) => this._executeOp(handle, operation, args),\n describeSkill: (handle, declaration) => this._describeSkill(handle, declaration),\n };\n }\n\n async connect(declaration: ConnectorDeclaration, _ctx: ConnectContext): Promise<ConnectorHandle> {\n const provider = String(declaration.options?.provider ?? \"mock\");\n this.log.info(\"connect\", { id: declaration.id, provider });\n const defaults: Record<string, string> = {};\n for (const [k, v] of Object.entries(declaration.options ?? {})) {\n if (k !== \"provider\" && typeof v === \"string\") defaults[k] = v;\n }\n let repoRoot: string | null = null;\n try {\n repoRoot = execSync(\"git rev-parse --show-toplevel\", {\n encoding: \"utf-8\",\n stdio: [\"pipe\", \"pipe\", \"pipe\"],\n }).trim();\n } catch {}\n return this.makeHandle(declaration, {\n provider,\n defaults,\n deployments: new Map(),\n repoRoot,\n worktreeDir: process.cwd(),\n } as DeployState);\n }\n\n async disconnect(handle: ConnectorHandle): Promise<void> {\n this.log.info(\"disconnect\");\n handle.status = \"disconnected\";\n }\n\n override async onSessionClose(_handle: ConnectorHandle): Promise<string | undefined> {\n return undefined;\n }\n\n override async onHibernate(_handle: ConnectorHandle): Promise<string | undefined> {\n return undefined;\n }\n\n // ── Tool face methods (private, wired in constructor) ─────────────────────\n\n private _describeOperations(_handle: ConnectorHandle): OperationDescriptor[] {\n return [\n {\n name: \"push\",\n description: \"Build and deploy.\",\n accessLevel: \"write\",\n args: [\n { name: \"build_command\", type: \"string\", required: true, description: \"Build command\" },\n {\n name: \"build_dir\",\n type: \"string\",\n required: true,\n description: \"Build output directory\",\n },\n { name: \"ref\", type: \"string\", required: false, description: \"Git ref\" },\n { name: \"label\", type: \"string\", required: false, description: \"Deployment label\" },\n {\n name: \"target_overrides\",\n type: \"json\",\n required: false,\n description: \"Provider overrides\",\n },\n ],\n },\n {\n name: \"status\",\n description: \"Get deployment status.\",\n accessLevel: \"read\",\n args: [\n {\n name: \"deployment\",\n type: \"string\",\n required: false,\n description: \"Deployment ID (omit for all)\",\n },\n ],\n },\n { name: \"list\", description: \"List all deployments.\", accessLevel: \"read\", args: [] },\n {\n name: \"teardown\",\n description: \"Remove a deployment.\",\n accessLevel: \"write\",\n args: [\n { name: \"deployment\", type: \"string\", required: true, description: \"Deployment ID\" },\n ],\n },\n {\n name: \"logs\",\n description: \"Fetch remote logs.\",\n accessLevel: \"read\",\n args: [\n { name: \"deployment\", type: \"string\", required: true, description: \"Deployment ID\" },\n {\n name: \"lines\",\n type: \"number\",\n required: false,\n description: \"Number of lines (default: 100)\",\n },\n ],\n },\n ];\n }\n\n private _describeSkill(\n handle: ConnectorHandle,\n declaration: ConnectorDeclaration,\n ): RuntimeSkillDescriptor {\n const state = handle.state as DeployState;\n return {\n id: declaration.id,\n name: `Deploy — ${state.provider}`,\n description: `Build and deploy to ${state.provider}.`,\n category: \"service\",\n access: handle.access,\n toolNames: [\"push\", \"status\", \"list\", \"teardown\", \"logs\"],\n };\n }\n\n private async _executeOp(\n handle: ConnectorHandle,\n operation: string,\n args: Record<string, unknown>,\n ): Promise<string> {\n const state = handle.state as DeployState;\n switch (operation) {\n case \"push\":\n return this._opPush(handle, state, args);\n case \"status\":\n return this._opStatus(state, args);\n case \"list\":\n return this._opList(state);\n case \"teardown\":\n return this._opTeardown(handle, state, args);\n case \"logs\":\n return this._opLogs(state, args);\n default:\n throw new Error(`DeployConnector has no operation: ${operation}`);\n }\n }\n\n private async _opPush(\n handle: ConnectorHandle,\n state: DeployState,\n args: Record<string, unknown>,\n ): Promise<string> {\n if (handle.access === \"read-only\") throw new Error(\"push requires read-write access\");\n const buildCommand = String(args.build_command ?? \"\");\n const buildDir = String(args.build_dir ?? \"\");\n if (!buildCommand) throw new Error(\"push: build_command required\");\n if (!buildDir) throw new Error(\"push: build_dir required\");\n const deploymentId = args.label ? String(args.label) : `deploy-${Date.now()}`;\n this.log.info(\"build start\", {\n deploymentId,\n buildCommand,\n buildDir,\n provider: state.provider,\n });\n try {\n let result: string;\n switch (state.provider) {\n case \"mock\":\n result = this._mockPush(state, {\n deploymentId,\n buildCommand,\n buildDir,\n ref: args.ref ? String(args.ref) : undefined,\n });\n break;\n default:\n throw new Error(`Provider \"${state.provider}\" is not yet implemented`);\n }\n this.log.info(\"build success\", { deploymentId });\n return result;\n } catch (err) {\n this.log.error(\"build failed\", err, { deploymentId });\n throw err;\n }\n }\n\n private _mockPush(\n state: DeployState,\n opts: { deploymentId: string; buildCommand: string; buildDir: string; ref?: string },\n ): string {\n const record: DeploymentRecord = {\n id: opts.deploymentId,\n url: `https://mock.deploy.example.com/${opts.deploymentId}`,\n ref: opts.ref,\n buildCommand: opts.buildCommand,\n buildDir: opts.buildDir,\n deployedAt: new Date().toISOString(),\n status: \"live\",\n };\n state.deployments.set(opts.deploymentId, record);\n return JSON.stringify({ deployment_id: record.id, url: record.url, ref: record.ref ?? null });\n }\n\n private _opStatus(state: DeployState, args: Record<string, unknown>): string {\n const id = args.deployment ? String(args.deployment) : undefined;\n if (id) {\n const r = state.deployments.get(id);\n if (!r) throw new Error(`Deployment not found: ${id}`);\n return JSON.stringify(this._ser(r));\n }\n return JSON.stringify([...state.deployments.values()].map((r) => this._ser(r)));\n }\n\n private _opList(state: DeployState): string {\n return JSON.stringify([...state.deployments.values()].map((r) => this._ser(r)));\n }\n\n private _opTeardown(\n handle: ConnectorHandle,\n state: DeployState,\n args: Record<string, unknown>,\n ): string {\n if (handle.access === \"read-only\") throw new Error(\"teardown requires read-write access\");\n const id = args.deployment ? String(args.deployment) : undefined;\n if (!id) throw new Error(\"teardown: deployment required\");\n if (state.provider === \"mock\") {\n if (!state.deployments.delete(id)) throw new Error(`Not found: ${id}`);\n return JSON.stringify({ removed: true });\n }\n throw new Error(`Provider \"${state.provider}\" does not support teardown yet`);\n }\n\n private _opLogs(state: DeployState, args: Record<string, unknown>): string {\n const id = args.deployment ? String(args.deployment) : undefined;\n if (!id) throw new Error(\"logs: deployment required\");\n if (state.provider === \"mock\")\n return JSON.stringify({ deployment: id, logs: \"No logs available for mock provider.\" });\n throw new Error(`Provider \"${state.provider}\" does not support logs yet`);\n }\n\n private _ser(r: DeploymentRecord): Record<string, unknown> {\n return {\n id: r.id,\n url: r.url,\n ref: r.ref ?? null,\n status: r.status,\n deployedAt: r.deployedAt,\n buildCommand: r.buildCommand,\n buildDir: r.buildDir,\n };\n }\n}\n\n/**\n * Creates a new DeployConnector instance.\n * @returns Configured DeployConnector ready to be registered in the connector registry.\n * @docLink packages/factory-assets/api-reference#deploy-connector-factory\n */\nexport function createConnector(): DeployConnector {\n return new DeployConnector();\n}\n","/**\n * DevServerConnector — process management service connector.\n *\n * Manages dev server processes (Vite, Nuxt, Next, etc.) with port allocation,\n * health checks, log capture, and optional git worktree isolation.\n *\n * Category: service\n */\n\nimport type {\n ConnectContext,\n ConnectorDeclaration,\n ConnectorHandle,\n OperationDescriptor,\n RuntimeSkillDescriptor,\n ToolFace,\n} from \"@skaile/workspaces/connectors\";\nimport {\n AbstractConnector,\n createWorktree,\n findGitRoot,\n LogBuffer,\n PortPool,\n} from \"@skaile/workspaces/connectors\";\nimport { portableSpawn } from \"@skaile/workspaces/core\";\n\n// ── Internal types ───────────────────────────────────────────────────────────\n\ninterface ServiceInstance {\n id: string;\n pid: number;\n port: number;\n cwd: string;\n status: \"starting\" | \"healthy\" | \"unhealthy\" | \"stopped\" | \"crashed\";\n startedAt: string;\n command?: string;\n env?: Record<string, string>;\n ref?: string;\n worktreePath?: string;\n worktreeCleanup?: () => Promise<void>;\n healthEndpoint?: string;\n managed: boolean;\n restartable: boolean;\n process?: { pid: number; kill(signal?: number): void; exited: Promise<number> };\n logBuffer?: LogBuffer;\n}\n\ninterface DevServerState {\n instances: Map<string, ServiceInstance>;\n pool: PortPool;\n repoRoot: string | null;\n worktreeDir: string;\n logBufferSize: number;\n}\n\n// ── Helpers ──────────────────────────────────────────────────────────────────\n\nfunction isPidAlive(pid: number): boolean {\n try {\n process.kill(pid, 0);\n return true;\n } catch {\n return false;\n }\n}\n\nasync function pipeToBuffer(stream: ReadableStream<Uint8Array>, buf: LogBuffer): Promise<void> {\n const reader = stream.getReader();\n const decoder = new TextDecoder();\n try {\n while (true) {\n const { done, value } = await reader.read();\n if (done) break;\n buf.pushLines(decoder.decode(value));\n }\n } catch {\n /* stream closed */\n }\n}\n\nlet idCounter = 0;\n\n// ── Connector ────────────────────────────────────────────────────────────────\n\n/**\n * Connector for managing dev server processes — spawns, tracks, and stops processes with port allocation, health checks, and log capture.\n * Supports optional git worktree isolation for per-instance code snapshots.\n * @docLink packages/factory-assets/concepts#devserver-connector\n */\nexport class DevServerConnector extends AbstractConnector {\n readonly name = \"devserver\";\n\n tools: ToolFace;\n\n constructor() {\n super();\n this.tools = {\n describeOperations: (handle) => this._describeOperations(handle),\n executeOp: (handle, operation, args) => this._executeOp(handle, operation, args),\n describeSkill: (handle, declaration) => this._describeSkill(handle, declaration),\n };\n }\n\n async connect(declaration: ConnectorDeclaration, _ctx: ConnectContext): Promise<ConnectorHandle> {\n this.log.info(\"connect\", { id: declaration.id });\n const opts = declaration.options ?? {};\n const portRange = (opts.port_range as [number, number]) ?? [3000, 3099];\n let repoRoot: string | null = null;\n try {\n repoRoot = findGitRoot(process.cwd());\n } catch {}\n\n const state: DevServerState = {\n instances: new Map(),\n pool: new PortPool(portRange),\n repoRoot,\n worktreeDir: String(opts.worktree_dir ?? \".skaile/worktrees\"),\n logBufferSize: Number(opts.log_buffer_size ?? 500),\n };\n\n return this.makeHandle(declaration, state);\n }\n\n async disconnect(handle: ConnectorHandle): Promise<void> {\n this.log.info(\"disconnect\");\n try {\n await this._stopAll(handle);\n } finally {\n handle.status = \"disconnected\";\n }\n }\n\n override async onSessionClose(handle: ConnectorHandle): Promise<string | undefined> {\n await this._stopAll(handle);\n return undefined;\n }\n\n override async onHibernate(handle: ConnectorHandle): Promise<string | undefined> {\n const state = handle.state as DevServerState;\n await this._stopAll(handle);\n return `Stopped ${state.instances.size} dev server instances for hibernation`;\n }\n\n // ── Tool face methods (private, wired in constructor) ─────────────────────\n\n private async _stopAll(handle: ConnectorHandle): Promise<void> {\n const state = handle.state as DevServerState;\n for (const [id, inst] of [...state.instances.entries()]) {\n if (inst.managed && inst.process) await this._killProcess(inst, state);\n state.instances.delete(id);\n }\n }\n\n private async _killProcess(inst: ServiceInstance, state: DevServerState): Promise<void> {\n if (!inst.process) return;\n try {\n inst.process.kill(15);\n } catch {}\n const exited = await Promise.race([\n inst.process.exited.then(() => true),\n new Promise<false>((r) => setTimeout(() => r(false), 5000)),\n ]);\n if (!exited) {\n try {\n inst.process.kill(9);\n } catch {}\n }\n inst.status = \"stopped\";\n state.pool.release(inst.port);\n if (inst.worktreeCleanup) {\n try {\n await inst.worktreeCleanup();\n } catch {}\n }\n }\n\n private _describeOperations(_handle: ConnectorHandle): OperationDescriptor[] {\n return [\n {\n name: \"start\",\n description: \"Spawn a dev server process.\",\n accessLevel: \"write\",\n args: [\n { name: \"command\", type: \"string\", required: true, description: \"Shell command to run\" },\n { name: \"cwd\", type: \"string\", required: false, description: \"Working directory\" },\n {\n name: \"ref\",\n type: \"string\",\n required: false,\n description: \"Git ref for worktree isolation\",\n },\n { name: \"port\", type: \"number\", required: false, description: \"Explicit port\" },\n { name: \"label\", type: \"string\", required: false, description: \"Instance label\" },\n {\n name: \"env\",\n type: \"json\",\n required: false,\n description: \"Additional environment variables\",\n },\n {\n name: \"health_endpoint\",\n type: \"string\",\n required: false,\n description: \"Health check URL\",\n },\n ],\n examples: ['start --command \"bun run dev\" --label \"frontend\"'],\n },\n {\n name: \"register\",\n description: \"Track an externally started process.\",\n accessLevel: \"write\",\n args: [\n { name: \"pid\", type: \"number\", required: true, description: \"Process ID\" },\n { name: \"port\", type: \"number\", required: true, description: \"Port\" },\n { name: \"label\", type: \"string\", required: false, description: \"Instance label\" },\n { name: \"cwd\", type: \"string\", required: false, description: \"Working directory\" },\n {\n name: \"health_endpoint\",\n type: \"string\",\n required: false,\n description: \"Health check URL\",\n },\n ],\n },\n {\n name: \"stop\",\n description: \"Stop a dev server instance.\",\n accessLevel: \"write\",\n args: [{ name: \"instance\", type: \"string\", required: true, description: \"Instance ID\" }],\n },\n {\n name: \"restart\",\n description: \"Restart a managed instance.\",\n accessLevel: \"write\",\n args: [{ name: \"instance\", type: \"string\", required: true, description: \"Instance ID\" }],\n },\n {\n name: \"status\",\n description: \"Check instance health.\",\n accessLevel: \"read\",\n args: [\n {\n name: \"instance\",\n type: \"string\",\n required: false,\n description: \"Instance ID (omit for all)\",\n },\n ],\n },\n {\n name: \"logs\",\n description: \"Get recent stdout/stderr.\",\n accessLevel: \"read\",\n args: [\n { name: \"instance\", type: \"string\", required: true, description: \"Instance ID\" },\n {\n name: \"lines\",\n type: \"number\",\n required: false,\n description: \"Number of lines (default: 50)\",\n },\n ],\n },\n {\n name: \"list_instances\",\n description: \"List all tracked instances.\",\n accessLevel: \"read\",\n args: [],\n },\n {\n name: \"free_port\",\n description: \"Allocate a port from the pool.\",\n accessLevel: \"read\",\n args: [],\n },\n ];\n }\n\n private async _executeOp(\n handle: ConnectorHandle,\n operation: string,\n args: Record<string, unknown>,\n ): Promise<string> {\n const state = handle.state as DevServerState;\n if (\n [\"start\", \"register\", \"stop\", \"restart\"].includes(operation) &&\n handle.access === \"read-only\"\n ) {\n throw new Error(`DevServerConnector: \"${operation}\" requires read-write access`);\n }\n\n switch (operation) {\n case \"start\":\n return this._opStart(handle, state, args);\n case \"register\":\n return this._opRegister(state, args);\n case \"stop\":\n return this._opStop(state, args);\n case \"restart\":\n return this._opRestart(handle, state, args);\n case \"status\":\n return this._opStatus(state, args);\n case \"logs\":\n return this._opLogs(state, args);\n case \"list_instances\":\n return this._opListInstances(state);\n case \"free_port\":\n return this._opFreePort(state);\n default:\n throw new Error(`DevServerConnector: unknown operation \"${operation}\"`);\n }\n }\n\n private async _opStart(\n handle: ConnectorHandle,\n state: DevServerState,\n args: Record<string, unknown>,\n ): Promise<string> {\n const command = args.command ? String(args.command) : undefined;\n if (!command) throw new Error(\"start requires a command argument\");\n let cwd = args.cwd ? String(args.cwd) : process.cwd();\n const ref = args.ref ? String(args.ref) : undefined;\n const label = args.label ? String(args.label) : `srv-${++idCounter}`;\n const userEnv = (args.env as Record<string, string>) ?? {};\n const healthEndpoint = args.health_endpoint ? String(args.health_endpoint) : undefined;\n\n let worktreePath: string | undefined;\n let worktreeCleanup: (() => Promise<void>) | undefined;\n if (ref) {\n if (!state.repoRoot) throw new Error(\"start with ref requires a git repository\");\n const wt = await createWorktree({\n repoRoot: state.repoRoot,\n ref,\n baseDir: state.worktreeDir,\n label,\n owner: handle.id,\n });\n cwd = wt.path;\n worktreePath = wt.path;\n worktreeCleanup = wt.cleanup;\n }\n\n let port: number;\n if (args.port !== undefined && args.port !== null) {\n port = Number(args.port);\n if (!(await PortPool.isPortFree(port))) throw new Error(`Port ${port} is already in use`);\n state.pool.reserve(port);\n } else {\n port = await state.pool.allocate();\n }\n\n const resolvedHealth = healthEndpoint\n ? healthEndpoint.replace(/\\bPORT\\b/g, String(port))\n : `http://localhost:${port}/`;\n this.log.info(\"spawn dev server\", { label, command, cwd, port });\n const proc = portableSpawn([\"sh\", \"-c\", command], {\n cwd,\n env: { ...process.env, ...userEnv, PORT: String(port) },\n detached: true,\n });\n const logBuffer = new LogBuffer(state.logBufferSize);\n pipeToBuffer(proc.stdout, logBuffer);\n pipeToBuffer(proc.stderr, logBuffer);\n\n const instance: ServiceInstance = {\n id: label,\n pid: proc.pid,\n port,\n cwd,\n status: \"starting\",\n startedAt: new Date().toISOString(),\n command,\n env: userEnv,\n ref,\n worktreePath,\n worktreeCleanup,\n healthEndpoint: resolvedHealth,\n managed: true,\n restartable: true,\n process: proc,\n logBuffer,\n };\n state.instances.set(label, instance);\n proc.exited.then((code: number | null) => {\n this.log.info(\"dev server exited\", { label, exitCode: code });\n if (instance.status !== \"stopped\") {\n instance.status = code === 0 ? \"stopped\" : \"crashed\";\n if (code !== 0 && code !== null) {\n this.log.warn(\"dev server crashed\", { label, exitCode: code });\n }\n this.emitChange?.({\n path: `instance/${instance.id}`,\n action: \"delete\",\n source: \"operation\",\n });\n }\n });\n\n return JSON.stringify({ instance_id: label, pid: proc.pid, port, cwd });\n }\n\n private async _opRegister(state: DevServerState, args: Record<string, unknown>): Promise<string> {\n const pid = Number(args.pid);\n const port = Number(args.port);\n if (!pid || Number.isNaN(pid)) throw new Error(\"register requires a valid pid\");\n if (!port || Number.isNaN(port)) throw new Error(\"register requires a valid port\");\n if (!isPidAlive(pid)) throw new Error(`PID ${pid} is not alive`);\n if (await PortPool.isPortFree(port)) throw new Error(`Port ${port} is not bound`);\n\n const label = args.label ? String(args.label) : `ext-${pid}`;\n state.pool.reserve(port);\n state.instances.set(label, {\n id: label,\n pid,\n port,\n cwd: args.cwd ? String(args.cwd) : process.cwd(),\n status: \"healthy\",\n startedAt: new Date().toISOString(),\n healthEndpoint: args.health_endpoint\n ? String(args.health_endpoint)\n : `http://localhost:${port}/`,\n managed: false,\n restartable: false,\n });\n return JSON.stringify({ instance_id: label });\n }\n\n private async _opStop(state: DevServerState, args: Record<string, unknown>): Promise<string> {\n const id = String(args.instance ?? \"\");\n const inst = state.instances.get(id);\n if (!inst) throw new Error(`Instance \"${id}\" not found`);\n if (inst.managed && inst.process) await this._killProcess(inst, state);\n else state.pool.release(inst.port);\n state.instances.delete(id);\n this.emitChange?.({ path: `instance/${id}`, action: \"delete\", source: \"operation\" });\n return JSON.stringify({ stopped: true });\n }\n\n private async _opRestart(\n handle: ConnectorHandle,\n state: DevServerState,\n args: Record<string, unknown>,\n ): Promise<string> {\n const id = String(args.instance ?? \"\");\n const inst = state.instances.get(id);\n if (!inst) throw new Error(`Instance \"${id}\" not found`);\n if (!inst.managed || !inst.restartable) throw new Error(`Instance \"${id}\" is not restartable`);\n const { command, cwd, env, port, healthEndpoint } = inst;\n if (inst.process) await this._killProcess(inst, state);\n state.instances.delete(id);\n state.pool.reserve(port);\n return this._opStart(handle, state, {\n command,\n cwd,\n env,\n port,\n label: id,\n health_endpoint: healthEndpoint,\n });\n }\n\n private async _opStatus(state: DevServerState, args: Record<string, unknown>): Promise<string> {\n if (args.instance) {\n const inst = state.instances.get(String(args.instance));\n if (!inst) throw new Error(`Instance \"${args.instance}\" not found`);\n await this._refreshStatus(inst);\n return JSON.stringify(instanceToStatus(inst));\n }\n for (const inst of state.instances.values()) await this._refreshStatus(inst);\n return JSON.stringify([...state.instances.values()].map(instanceToStatus));\n }\n\n private async _refreshStatus(inst: ServiceInstance): Promise<void> {\n if (inst.status === \"stopped\") return;\n if (!isPidAlive(inst.pid)) {\n inst.status = \"crashed\";\n return;\n }\n if (inst.healthEndpoint) {\n try {\n const res = await fetch(inst.healthEndpoint, { signal: AbortSignal.timeout(3000) });\n inst.status = res.ok ? \"healthy\" : \"unhealthy\";\n } catch {\n inst.status = \"unhealthy\";\n }\n } else {\n inst.status = \"healthy\";\n }\n }\n\n private _opLogs(state: DevServerState, args: Record<string, unknown>): string {\n const inst = state.instances.get(String(args.instance ?? \"\"));\n if (!inst) throw new Error(`Instance \"${args.instance}\" not found`);\n if (!inst.managed) throw new Error(`Cannot retrieve logs for non-managed instance`);\n return inst.logBuffer!.tail(args.lines ? Number(args.lines) : 50).join(\"\\n\");\n }\n\n private _opListInstances(state: DevServerState): string {\n return JSON.stringify(\n [...state.instances.values()].map((i) => ({\n id: i.id,\n pid: i.pid,\n port: i.port,\n status: i.status,\n ref: i.ref,\n managed: i.managed,\n started_at: i.startedAt,\n cwd: i.cwd,\n })),\n );\n }\n\n private async _opFreePort(state: DevServerState): Promise<string> {\n return JSON.stringify({ port: await state.pool.allocate() });\n }\n\n private _describeSkill(\n handle: ConnectorHandle,\n declaration: ConnectorDeclaration,\n ): RuntimeSkillDescriptor {\n return {\n id: declaration.id,\n name: `Dev Server — ${declaration.id}`,\n description:\n \"Manage dev server processes with port allocation, health checks, and log capture.\",\n category: \"service\",\n access: declaration.access,\n toolNames: this._describeOperations(handle).map((o) => o.name),\n };\n }\n}\n\nfunction instanceToStatus(inst: ServiceInstance) {\n return {\n id: inst.id,\n pid: inst.pid,\n port: inst.port,\n status: inst.status,\n managed: inst.managed,\n restartable: inst.restartable,\n ref: inst.ref,\n cwd: inst.cwd,\n started_at: inst.startedAt,\n health_endpoint: inst.healthEndpoint,\n uptime_ms: Date.now() - new Date(inst.startedAt).getTime(),\n };\n}\n\n/**\n * Creates a new DevServerConnector instance.\n * @returns Configured DevServerConnector ready to be registered in the connector registry.\n * @docLink packages/factory-assets/api-reference#devserver-connector-factory\n */\nexport function createConnector(): DevServerConnector {\n return new DevServerConnector();\n}\n","/**\n * GitConnector — git repository filesystem-face connector.\n * Mounts a git repo by cloning/pulling to a local directory.\n * Session-aware: auto-branching, lifecycle hooks (hibernate/close), periodic fetch/rebase.\n */\n\nimport { execSync } from \"node:child_process\";\nimport {\n existsSync,\n mkdirSync,\n readdirSync,\n readFileSync,\n renameSync,\n writeFileSync,\n} from \"node:fs\";\nimport { dirname, join } from \"node:path\";\nimport type {\n ConnectContext,\n ConnectorChangeEvent,\n ConnectorDeclaration,\n ConnectorHandle,\n FilesystemFace,\n MountAuthRef,\n OperationDescriptor,\n SecretProvider,\n SyncOptions,\n SyncResult,\n ToolFace,\n TokenMediatorResult,\n WatchHandle,\n WatchOptions,\n} from \"@skaile/workspaces/connectors\";\nimport { createLogger } from \"@skaile/workspaces/core/logging\";\nimport {\n AbstractConnector,\n atomicReplaceCredential,\n createFsWatcher,\n ensureFleetMounted,\n isFleetManaged,\n removeMountBlock,\n renderCredentialHelperScript,\n resolveAuthRef,\n writeHelperScript,\n writeMountBlock,\n} from \"@skaile/workspaces/connectors\";\n\n/** New unified TokenMediator shape — uses `connectorId` (renamed from `mountId` in Task 1). */\ntype ConnectorTokenMediator = NonNullable<ConnectContext[\"tokenMediator\"]>;\n\n// ── Session/sync/lifecycle config parsed from declaration.options ────────────\n\ninterface GitSessionConfig {\n enabled: boolean;\n slug?: string;\n isMain: boolean;\n branchPrefix: string;\n /**\n * Starting point for a freshly-created session branch. When set and the\n * session branch does not already exist on origin, the driver fetches this\n * ref and branches from it instead of from the base branch tip. Used by\n * the platform's fork flow so a forked session branches off the source\n * session's tip rather than off `main`. May be a branch name (e.g.\n * `skaile/session-source-slug`) or a commit SHA. Ignored when the session\n * branch already exists on origin (existing branch wins). No-op when\n * `enabled = false` or `isMain = true` (only branch sessions cut new\n * branches). The value is validated against `isValidGitRefOrSha` before\n * use; refs with shell metacharacters are rejected and the driver falls\n * back to branching off base.\n */\n fromRef?: string;\n}\n\ninterface GitSyncConfig {\n fetchIntervalSec: number;\n autoRebase: boolean;\n autoPull: boolean;\n}\n\ninterface GitLifecycleConfig {\n commitOnHibernate: boolean;\n pushOnHibernate: boolean;\n mergeOnClose: boolean;\n pushOnClose: boolean;\n /** Auto-commit after N ms of no file changes. 0 = disabled. Default: 30000 (30s). */\n autoCommitIdleMs: number;\n /** Push to remote after each auto-commit. */\n pushAfterCommit: boolean;\n /** Push freshly-created session branch to origin on connect. Best-effort — push\n * failures are swallowed; lifecycle push hooks remain the backstop. */\n publishOnCreate: boolean;\n}\n\ninterface GitState {\n /** URL of the remote repository. */\n url: string;\n /** Base branch to track (e.g. \"main\"). */\n branch: string;\n /** Active branch (may differ from base when session branching is active). */\n activeBranch: string;\n /** Auth token for HTTPS URLs. */\n token?: string;\n /** Session branching config. */\n session: GitSessionConfig;\n /** Periodic fetch/rebase config. */\n sync: GitSyncConfig;\n /** Lifecycle hook config. */\n lifecycle: GitLifecycleConfig;\n /** Periodic fetch timer ID. */\n fetchTimer?: ReturnType<typeof setInterval>;\n /** Auto-commit idle timer ID. */\n autoCommitTimer?: ReturnType<typeof setTimeout>;\n /** Callback for emitting change events (set by watch()). */\n emitChange?: (event: ConnectorChangeEvent) => void;\n /**\n * Tier-2 managed-gitconfig paths populated when `exposeAccessToken` is on.\n * Cleared on `disconnect`/`onSessionClose` so the credential is removed\n * promptly. Absent for Tier-1 mounts.\n */\n managedGitconfig?: {\n gitconfigPath: string;\n credentialsPath: string;\n urlPrefix: string;\n };\n /**\n * Token mediator captured at connect time for use by refresh ticks. Only\n * populated for `auth: backend` connectors; absent for `pat:` and anonymous.\n */\n tokenMediator?: ConnectorTokenMediator;\n /**\n * Active refresh timer. Set only when the resolved token came from the\n * backend mediator and carried a finite expiry. Cleared on every\n * reschedule and on teardown.\n */\n refreshTimer?: ReturnType<typeof setTimeout>;\n /** Checkout path, retained so the Tier-1 refresh tick can re-bake origin. */\n targetDir?: string;\n /** True when the host fleet owns clone/pull/commit/push for this mount. */\n fleetManaged?: boolean;\n /** Auto-started watcher in fleet mode (no auto-commit timer); disposed in `disconnect`. */\n fleetWatcher?: WatchHandle;\n}\n\n/** Per-block defaults the `parse*Config` helpers fall back to when an option is absent. */\ninterface GitConfigDefaults {\n session: { enabled: boolean };\n sync: { fetchIntervalSec: number; autoRebase: boolean; autoPull: boolean };\n lifecycle: {\n commitOnHibernate: boolean;\n pushOnHibernate: boolean;\n mergeOnClose: boolean;\n pushOnClose: boolean;\n autoCommitIdleMs: number;\n pushAfterCommit: boolean;\n publishOnCreate: boolean;\n };\n}\n\n/**\n * Legacy / no-mode defaults — the exact literals this driver used before `mode`\n * existed, so behavior is unchanged when a declaration carries no `mode`.\n */\nconst LEGACY_DEFAULTS: GitConfigDefaults = {\n session: { enabled: false },\n sync: { fetchIntervalSec: 0, autoRebase: false, autoPull: false },\n lifecycle: {\n commitOnHibernate: true,\n pushOnHibernate: true,\n mergeOnClose: true,\n pushOnClose: true,\n autoCommitIdleMs: 30_000,\n pushAfterCommit: false,\n publishOnCreate: true,\n },\n};\n\n/** Per-mode default tables. `agent` lets the agent drive git; `sync` makes the connector own the working copy. */\nconst MODE_DEFAULTS: Record<\"agent\" | \"sync\", GitConfigDefaults> = {\n agent: {\n session: { enabled: true },\n sync: { fetchIntervalSec: 0, autoRebase: false, autoPull: false },\n lifecycle: {\n ...LEGACY_DEFAULTS.lifecycle,\n // Agent owns its own merge — connector must not auto-merge the session branch.\n mergeOnClose: false,\n autoCommitIdleMs: 0,\n pushAfterCommit: false,\n },\n },\n sync: {\n session: { enabled: false },\n sync: { fetchIntervalSec: 30, autoRebase: true, autoPull: true },\n lifecycle: {\n ...LEGACY_DEFAULTS.lifecycle,\n autoCommitIdleMs: 30_000,\n pushAfterCommit: true,\n },\n },\n};\n\nfunction parseSessionConfig(\n opts: Record<string, unknown> | undefined,\n defaults: GitConfigDefaults[\"session\"],\n): GitSessionConfig {\n const raw = (opts?.session as Record<string, unknown>) ?? {};\n return {\n enabled: Boolean(raw.enabled ?? defaults.enabled),\n slug: raw.slug != null ? String(raw.slug) : undefined,\n isMain: Boolean(raw.isMain ?? true),\n branchPrefix: String(raw.branchPrefix ?? \"session/\"),\n fromRef: raw.fromRef != null ? String(raw.fromRef) : undefined,\n };\n}\n\nfunction parseSyncConfig(\n opts: Record<string, unknown> | undefined,\n defaults: GitConfigDefaults[\"sync\"],\n): GitSyncConfig {\n const raw = (opts?.sync as Record<string, unknown>) ?? {};\n return {\n fetchIntervalSec: Number(raw.fetchIntervalSec ?? defaults.fetchIntervalSec),\n autoRebase: Boolean(raw.autoRebase ?? defaults.autoRebase),\n autoPull: Boolean(raw.autoPull ?? defaults.autoPull),\n };\n}\n\nfunction parseLifecycleConfig(\n opts: Record<string, unknown> | undefined,\n defaults: GitConfigDefaults[\"lifecycle\"],\n): GitLifecycleConfig {\n const raw = (opts?.lifecycle as Record<string, unknown>) ?? {};\n return {\n commitOnHibernate: Boolean(raw.commitOnHibernate ?? defaults.commitOnHibernate),\n pushOnHibernate: Boolean(raw.pushOnHibernate ?? defaults.pushOnHibernate),\n mergeOnClose: Boolean(raw.mergeOnClose ?? defaults.mergeOnClose),\n pushOnClose: Boolean(raw.pushOnClose ?? defaults.pushOnClose),\n autoCommitIdleMs: Number(raw.autoCommitIdleMs ?? defaults.autoCommitIdleMs),\n pushAfterCommit: Boolean(raw.pushAfterCommit ?? defaults.pushAfterCommit),\n publishOnCreate: Boolean(raw.publishOnCreate ?? defaults.publishOnCreate),\n };\n}\n\n/**\n * Resolve the session/sync/lifecycle config blocks for a git connector. `mode`\n * seeds per-block defaults (`agent` / `sync`); explicit `options.{session,sync,\n * lifecycle}` keys still override those defaults. Absent `mode` reproduces the\n * legacy literals exactly, so behavior is unchanged for declarations that set none.\n */\nfunction resolveGitConfig(args: { mode?: \"agent\" | \"sync\"; options?: Record<string, unknown> }): {\n session: GitSessionConfig;\n sync: GitSyncConfig;\n lifecycle: GitLifecycleConfig;\n} {\n // `mode` arrives unvalidated from YAML (connectors are cast, not Zod-parsed);\n // an unknown value would index MODE_DEFAULTS as undefined and crash below.\n let mode = args.mode;\n if (mode && !(mode in MODE_DEFAULTS)) {\n modeLog.warn(\"unknown git mode — falling back to legacy defaults\", { mode });\n mode = undefined;\n }\n const defaults = mode ? MODE_DEFAULTS[mode] : LEGACY_DEFAULTS;\n return {\n session: parseSessionConfig(args.options, defaults.session),\n sync: parseSyncConfig(args.options, defaults.sync),\n lifecycle: parseLifecycleConfig(args.options, defaults.lifecycle),\n };\n}\n\n/** Free-function diagnostics for `resolveGitConfig` (no `this.log` in scope). */\nconst modeLog = createLogger({ kind: \"connector\", subkind: \"git\" });\n\n// ── Git helpers ──────────────────────────────────────────────────────────────\n\nfunction git(cmd: string, cwd: string, timeout = 30_000): string {\n return execSync(`git ${cmd}`, { cwd, encoding: \"utf-8\", timeout, stdio: \"pipe\" }).trim();\n}\n\n// Best-effort: align nested submodule checkouts with the parent's pinned SHAs\n// after any ref-changing operation (clone bootstrap, pull, branch switch).\n// `--recurse-submodules` on the initial clone handles the first checkout; this\n// covers every subsequent state change. No-op when `.gitmodules` is absent.\nfunction syncSubmodules(cwd: string): void {\n if (!existsSync(join(cwd, \".gitmodules\"))) return;\n try {\n git(\"submodule update --init --recursive\", cwd, 120_000);\n } catch {\n /* best-effort: a missing submodule shouldn't abort the parent operation */\n }\n}\n\n/**\n * Conservative refname / SHA validator. Used to gate any externally-supplied\n * ref before it interpolates into a shell-form `git` invocation. Accepts a\n * subset of git-check-ref-format(1): forbids whitespace, shell metacharacters,\n * control chars, leading `-` (so the value cannot be misread as a flag), `..`,\n * `@{`, and a trailing `.lock`. Hex SHAs (40 chars) pass through.\n */\nfunction isValidGitRefOrSha(ref: string): boolean {\n if (ref.length === 0 || ref.length > 255) return false;\n // Rejecting control chars is the whole point of this validator — Biome's\n // noControlCharactersInRegex rule does not apply here.\n // biome-ignore lint/suspicious/noControlCharactersInRegex: intentional control-char rejection\n if (/[\\s\\\\~^:?*[\\x00-\\x1f\\x7f`$;&|'\"<>()]/.test(ref)) return false;\n if (ref.startsWith(\"-\") || ref.endsWith(\".lock\") || ref.endsWith(\"/\") || ref.endsWith(\".\"))\n return false;\n if (ref.includes(\"..\") || ref.includes(\"@{\")) return false;\n return true;\n}\n\nfunction hasChanges(cwd: string): boolean {\n const status = git(\"status --porcelain\", cwd);\n return status.length > 0;\n}\n\n/** Run a git subcommand, returning trimmed stdout or `null` on any failure. */\nfunction gitOrNull(cmd: string, cwd: string): string | null {\n try {\n return git(cmd, cwd);\n } catch {\n return null;\n }\n}\n\n/**\n * Parse `git rev-list --left-right --count <ref>...HEAD` into ahead/behind.\n * Left count = commits only on `<ref>` (behind), right count = commits only on\n * HEAD (ahead). Returns `{0,0}` when the ref is missing (e.g. no upstream).\n */\nfunction countAheadBehind(cwd: string, remoteRef: string): { ahead: number; behind: number } {\n const out = gitOrNull(`rev-list --left-right --count ${remoteRef}...HEAD`, cwd);\n if (!out) {\n return { ahead: 0, behind: 0 };\n }\n const parts = out.split(/\\s+/);\n const behind = Number.parseInt(parts[0] ?? \"0\", 10);\n const ahead = Number.parseInt(parts[1] ?? \"0\", 10);\n return {\n ahead: Number.isFinite(ahead) ? ahead : 0,\n behind: Number.isFinite(behind) ? behind : 0,\n };\n}\n\n/**\n * Snapshot returned by the `sync_status` tool op. JSON-serialised over the\n * transport; the platform overlays `available`/`containerAwake`/`reason`\n * before handing it to the UI badge.\n */\nexport interface GitSyncStatusResult {\n /** Current branch name, or `null` (detached HEAD / unavailable). */\n branch: string | null;\n /** Working tree has uncommitted changes (`git status --porcelain` non-empty). */\n dirty: boolean;\n /** Commits on HEAD not on its upstream — i.e. unpushed. */\n ahead: number;\n /** Commits on the upstream not on HEAD — i.e. unpulled (since last fetch). */\n behind: number;\n /**\n * Whether the current branch has a configured upstream. `false` ⇒ the branch\n * has never been pushed; `ahead`/`behind` read as 0 (no remote-tracking ref\n * to diff against), so this distinguishes \"never pushed\" from \"synced\".\n */\n hasUpstream: boolean;\n /** Commits on HEAD not on `origin/<baseBranch>` — diverged ahead of base. */\n mainAhead: number;\n /** Commits on `origin/<baseBranch>` not on HEAD — diverged behind base. */\n mainBehind: number;\n /** Current HEAD commit SHA, or `null` when unavailable. */\n commitSha: string | null;\n}\n\n/**\n * Read git sync status for an in-container checkout. Pure and never throws —\n * every git call degrades to a safe default. No network fetch:\n * ahead/behind reflect locally-known remote-tracking refs (\"since last sync\").\n * `baseBranch` is the mount's tracked base (e.g. \"main\"); base divergence is\n * measured against `origin/<baseBranch>`.\n */\nexport function readGitSyncStatus(cwd: string, baseBranch: string): GitSyncStatusResult {\n const branchRaw = gitOrNull(\"rev-parse --abbrev-ref HEAD\", cwd);\n const branch = branchRaw && branchRaw !== \"HEAD\" ? branchRaw : null;\n\n const dirty = (gitOrNull(\"status --porcelain\", cwd) ?? \"\") !== \"\";\n\n // A branch with no configured upstream has never been pushed. Detected\n // separately because countAheadBehind can't tell \"no upstream\" (rev-list\n // fails → 0/0) from \"in sync with upstream\" (also 0/0). rev-parse exits\n // non-zero when @{upstream} is unset; only success/failure matters here.\n const hasUpstream =\n branch !== null && gitOrNull(\"rev-parse --abbrev-ref @{upstream}\", cwd) !== null;\n\n const upstream = countAheadBehind(cwd, \"@{upstream}\");\n\n const baseRef = isValidGitRefOrSha(baseBranch) ? `origin/${baseBranch}` : \"origin/main\";\n const base = countAheadBehind(cwd, baseRef);\n\n const commitSha = gitOrNull(\"rev-parse HEAD\", cwd);\n\n return {\n branch,\n dirty,\n ahead: upstream.ahead,\n behind: upstream.behind,\n hasUpstream,\n mainAhead: base.ahead,\n mainBehind: base.behind,\n commitSha,\n };\n}\n\n/**\n * True when `branch` exists as a local head in the checkout. Used to reuse a\n * session branch a prior connect created but never pushed — `checkout -b` would\n * otherwise abort with \"already exists\" and fail the connector. `branch` must\n * already be refname-validated before it reaches this shell-form `git` call.\n */\nfunction localBranchExists(branch: string, cwd: string): boolean {\n try {\n git(`rev-parse --verify --quiet refs/heads/${branch}`, cwd);\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * True when `dir` is empty (no entries, including no dotfiles) or when\n * `readdirSync` fails (e.g. dir does not exist). The \"fails → empty\" mapping\n * is intentional: the caller is about to `mkdir` and proceed, so a missing\n * dir is functionally equivalent to an empty one.\n */\nfunction isDirEmpty(dir: string): boolean {\n try {\n return readdirSync(dir).length === 0;\n } catch {\n return true;\n }\n}\n\nfunction commitAll(cwd: string, message: string): string | null {\n if (!hasChanges(cwd)) return null;\n git(\"add -A\", cwd);\n return git(`commit -m ${JSON.stringify(message)}`, cwd);\n}\n\n/**\n * Structured error used when the backend credential mediator refuses or\n * cannot deliver a token. Carries the wire-format error code so callers\n * (connector manager, retry loop, audit log) can branch on it.\n *\n * @docLink packages/factory-assets/concepts#git-connector-mediation\n */\nclass TokenMediatorError extends Error {\n readonly code: TokenMediatorResult extends infer R\n ? R extends { ok: false; code: infer C }\n ? C\n : never\n : never;\n constructor(\n message: string,\n code: \"not-configured\" | \"revoked\" | \"provider-error\" | \"backend-error\" | \"timeout\",\n connectorId: string,\n ) {\n super(`Git connector '${connectorId}': backend mediator ${code} — ${message}`);\n this.name = \"TokenMediatorError\";\n this.code = code as never;\n }\n}\n\n// ── Connector ──────────────────────────────────────────────────────────────────\n\n/**\n * Filesystem-face connector for git repositories — clones or pulls on connect, supports\n * session branching, periodic fetch/rebase, and lifecycle hooks (hibernate commit/push,\n * session close merge). Also supports Tier-2 managed credential injection via\n * `GIT_CONFIG_GLOBAL` for agent-facing `git` CLI access.\n *\n * Token acquisition for `auth: backend` connectors is mediated by the runner: the\n * connector calls the injected `tokenMediator` callback (which sends a\n * `request_access_token` command over the transport and awaits the matching\n * `access_token_response` event). Local provider minting (OAuth, GitHub App)\n * has been removed — the platform owns dispatch.\n *\n * @docLink packages/factory-assets/concepts#git-connector\n */\nexport class GitConnector extends AbstractConnector {\n readonly name = \"git\";\n\n readonly filesystem: FilesystemFace = {\n sync: (handle: ConnectorHandle, options?: SyncOptions): Promise<SyncResult> => {\n return this._sync(handle, options);\n },\n };\n\n readonly tools: ToolFace = {\n describeOperations: (handle: ConnectorHandle): OperationDescriptor[] =>\n this._describeOperations(handle),\n executeOp: (\n handle: ConnectorHandle,\n operation: string,\n args: Record<string, unknown>,\n ): Promise<string> => this._executeOp(handle, operation, args),\n };\n\n private _describeOperations(_handle: ConnectorHandle): OperationDescriptor[] {\n return [\n {\n name: \"sync_status\",\n description:\n \"Report git sync status for this mount: current branch, dirty flag, ahead/behind \" +\n \"vs the upstream, whether the branch has a configured upstream (never-pushed when \" +\n \"false), and divergence vs the base branch. Read-only; performs no fetch.\",\n accessLevel: \"read\",\n args: [],\n examples: [\"sync_status\"],\n },\n ];\n }\n\n private async _executeOp(\n handle: ConnectorHandle,\n operation: string,\n _args: Record<string, unknown>,\n ): Promise<string> {\n switch (operation) {\n case \"sync_status\": {\n const cwd = handle.mountPath;\n if (!cwd) {\n throw new Error(\"git sync_status: mount path unavailable\");\n }\n const state = handle.state as GitState;\n return JSON.stringify(readGitSyncStatus(cwd, state.branch));\n }\n default:\n throw new Error(`GitConnector has no operation: ${operation}`);\n }\n }\n\n async connect(declaration: ConnectorDeclaration, ctx: ConnectContext): Promise<ConnectorHandle> {\n const targetDir = ctx.mountTarget;\n if (!targetDir) {\n throw new Error(\"GitConnector requires ctx.mountTarget to be set by the manager\");\n }\n\n // Host bind-mounts the worktree; in-container driver must not touch the git lifecycle.\n if (isFleetManaged(declaration.id)) {\n return this.connectFleetManaged(declaration, targetDir);\n }\n\n const secrets = ctx.secrets;\n const tokenMediator = ctx.tokenMediator;\n\n const started = Date.now();\n const opts = declaration.options;\n const url = String(declaration.mount?.source ?? \"\");\n const branch = String(opts?.branch ?? \"main\");\n\n if (!url) {\n this.log.error(\"connect failed: missing mount.source URL\", undefined);\n throw new Error(\"Git connector requires a mount.source URL\");\n }\n\n // `branch` interpolates into shell-form `git clone --branch ...` and later\n // pull/push commands. Reject anything carrying shell metacharacters.\n if (!isValidGitRefOrSha(branch)) {\n throw new Error(`Git connector: invalid branch name \"${branch}\"`);\n }\n\n this.log.info(\"mount start\", { url, branch, targetDir });\n\n // Resolve auth ref and (when present) the initial token. For `backend`\n // refs the token comes from the platform mediator; for `pat:env:NAME`\n // it falls back to the secrets chain. Anonymous (no `auth:`) connectors\n // remain supported for public repos.\n const initial = await this.acquireInitialToken(declaration, secrets, tokenMediator);\n\n const { session, sync, lifecycle } = resolveGitConfig({\n mode: declaration.mode,\n options: opts,\n });\n\n const state: GitState = {\n url,\n branch,\n activeBranch: branch,\n token: initial.token,\n session,\n sync,\n lifecycle,\n targetDir,\n tokenMediator: initial.authRef?.kind === \"backend\" ? tokenMediator : undefined,\n };\n\n // Clone or pull\n const authUrl = this.authUrl(state);\n this.prepareCheckout(targetDir, url, branch, authUrl, started);\n\n // Session branching: create and checkout a session branch for non-main sessions\n if (session.enabled && !session.isMain && session.slug) {\n this.checkoutSessionBranch(state, session, targetDir);\n }\n\n // Start periodic fetch if configured\n if (sync.fetchIntervalSec > 0) {\n this.startPeriodicFetch(state, targetDir);\n }\n\n // Tier-2: when `exposeAccessToken` is on (in declaration.mount),\n // wire the resolved credential into a managed-gitconfig file so the\n // agent's interactive `git` can authenticate against this host.\n // Path comes from `GIT_CONFIG_GLOBAL` set by the runner; absent in\n // CLI/standalone contexts (Tier-1 stays the default there).\n if (declaration.mount?.exposeAccessToken === true) {\n try {\n this.exposeManagedCredential(declaration, state, url, initial);\n } catch (err) {\n this.log.error(\"managed-gitconfig write failed\", err, { connectorId: declaration.id });\n throw err;\n }\n }\n\n // Reconcile origin auth on every connect — stale baked tokens persist across wakes.\n // Tier-2: strip inline creds so the managed credential helper is consulted instead.\n // Tier-1: re-bake the freshly minted token so a woken session doesn't push with a dead one.\n if (state.managedGitconfig) {\n this.stripRemoteInlineToken(targetDir);\n } else {\n this.rebakeRemoteAuth(targetDir, state);\n // Tier-1 has no managed helper: the baked URL token is the sole credential\n // and dies at its ~1h TTL on a session that never hibernates. Schedule the\n // same rotation tick as Tier-2, re-baking the fresh token each time.\n if (initial.authRef?.kind === \"backend\" && initial.expiresAt && state.tokenMediator) {\n this.scheduleRefresh(declaration.id, state, initial.expiresAt);\n }\n }\n\n this.log.info(\"mount ok\", {\n targetDir,\n activeBranch: state.activeBranch,\n durationMs: Date.now() - started,\n });\n return this.makeHandle(declaration, state, targetDir);\n }\n\n /**\n * Bring `targetDir` into a usable checkout state for `connect()`.\n *\n * Minimal-connect policy: `connect()` never auto-syncs with the remote.\n * The lifecycle hooks (`pushOnHibernate`, `pushAfterCommit`,\n * `sync.autoPull`) and the explicit `filesystem.sync()` method are the\n * only paths that touch the network with the existing checkout. Recreating\n * a container is therefore idempotent — the on-disk dir is preserved.\n *\n * Three cases:\n * - `.git` exists → use as-is. No pull, no reset.\n * - dir empty → fresh clone (only network fetch on connect).\n * - dir populated, no `.git` → `git init` + `remote add origin` so\n * lifecycle hooks (commit/push) can do their job. No fetch, no\n * reset, no clean. Existing files become uncommitted-on-init; the\n * agent or `pushAfterCommit` reconciles with remote later.\n */\n private prepareCheckout(\n targetDir: string,\n url: string,\n branch: string,\n authUrl: string,\n started: number,\n ): void {\n try {\n if (existsSync(join(targetDir, \".git\"))) {\n if (this.isInitialisedCheckout(targetDir)) {\n // Functional working checkout — leave it alone. Sync is the\n // lifecycle's job (push on hibernate, periodic fetch, etc.).\n this.log.info(\"found existing checkout — using as-is\", { branch, targetDir });\n } else {\n // `.git` is present but has no resolved HEAD — typically the\n // residue of a prior `initInPlace` call (origin configured, no\n // objects fetched) or an aborted clone. Bootstrap content from\n // the remote *once*, then future connects hit the as-is path above.\n this.log.info(\"found empty .git — bootstrapping from origin\", { branch });\n this.bootstrapFromOrigin(targetDir, branch, authUrl);\n this.log.info(\"bootstrap ok\", { branch, durationMs: Date.now() - started });\n }\n } else {\n mkdirSync(targetDir, { recursive: true });\n if (isDirEmpty(targetDir)) {\n this.log.info(\"clone start\", { url, branch });\n execSync(\n `git clone --branch ${branch} --single-branch --recurse-submodules ${authUrl} ${targetDir}`,\n {\n timeout: 120_000,\n stdio: \"pipe\",\n },\n );\n this.log.info(\"clone ok\", { branch, durationMs: Date.now() - started });\n } else {\n // Populated dir without `.git`. Typical causes: previous connect\n // aborted mid-clone; bind-mount of a worktree whose `.git` FILE\n // points outside the container. We DO NOT overwrite the files —\n // they are likely the user's last working state. We just bring\n // git tracking back online so lifecycle hooks work.\n this.log.warn(\"target non-empty without .git — initialising in place\", { targetDir });\n this.initInPlace(targetDir, authUrl);\n this.log.info(\"init in place ok\", { durationMs: Date.now() - started });\n }\n }\n } catch (err) {\n this.log.error(\"connect preparation failed\", err, { url, branch });\n throw err;\n }\n }\n\n /**\n * Create and check out the session branch for a non-main session, updating\n * `state.activeBranch`. Reuses an existing local branch (unpushed work);\n * else prefers `origin/<branch>`; otherwise branches off `fromRef` (platform\n * fork flow) when supplied and valid, else off the currently-checked-out\n * HEAD (== base branch).\n */\n private checkoutSessionBranch(\n state: GitState,\n session: GitSessionConfig,\n targetDir: string,\n ): void {\n const sessionBranch = `${session.branchPrefix}${session.slug}`;\n // The composed branch name interpolates into shell-form `git` commands.\n // Reject slug/prefix combinations that don't survive refname validation.\n if (!isValidGitRefOrSha(sessionBranch)) {\n throw new Error(`Git connector: invalid session branch name \"${sessionBranch}\"`);\n }\n // Track whether this connect cut a brand-new branch that does not yet exist\n // on origin — only then do we publish-on-create. Reusing a local branch or\n // checking out an existing origin branch must not trigger an extra push.\n let created = false;\n if (localBranchExists(sessionBranch, targetDir)) {\n // A prior connect created the branch locally but never pushed it — no\n // origin/<branch> tracking ref for the fast path, yet `checkout -b` would\n // abort with \"already exists\". Reuse it so unpushed work survives.\n git(`checkout ${sessionBranch}`, targetDir);\n this.log.info(\"reusing existing local session branch\", { sessionBranch });\n } else {\n // Separate the existence probe from the checkout so the new-branch path\n // is reached only when origin genuinely lacks the branch — a failing\n // `checkout -B` on an existing origin branch must not flip `created`.\n let originHasBranch = false;\n try {\n git(`rev-parse --verify origin/${sessionBranch}`, targetDir);\n originHasBranch = true;\n } catch {\n /* not on origin */\n }\n\n if (originHasBranch) {\n git(`checkout -B ${sessionBranch} origin/${sessionBranch}`, targetDir);\n } else if (!this.branchFromRef(session, sessionBranch, targetDir)) {\n // No fromRef anchor (or its fetch failed) — branch off the\n // currently-checked-out HEAD (== base branch).\n git(`checkout -b ${sessionBranch}`, targetDir);\n created = true;\n } else {\n // branchFromRef cut the branch off the supplied fork anchor.\n created = true;\n }\n }\n syncSubmodules(targetDir);\n state.activeBranch = sessionBranch;\n this.log.info(\"session branch checked out\", { sessionBranch });\n\n if (created && state.lifecycle.publishOnCreate) {\n try {\n git(`push -u origin ${sessionBranch}`, targetDir, 60_000);\n this.log.info(\"published new session branch\", { sessionBranch });\n } catch (err) {\n // Best-effort: offline / no-remote-write must not fail connect. The\n // lifecycle push hooks (hibernate/close) remain the backstop.\n this.log.warn(\"publish-on-create push failed; deferring to lifecycle push\", {\n sessionBranch,\n error: err instanceof Error ? err.message : String(err),\n });\n }\n }\n }\n\n /**\n * Attempt to create `sessionBranch` anchored on `session.fromRef`. Returns\n * true when the branch was created from the anchor; false when no valid\n * `fromRef` was supplied or the fetch failed (caller falls back to base).\n */\n private branchFromRef(\n session: GitSessionConfig,\n sessionBranch: string,\n targetDir: string,\n ): boolean {\n if (!session.fromRef) return false;\n if (!isValidGitRefOrSha(session.fromRef)) {\n // Defense in depth: fromRef interpolates into a shell-form `git`\n // command. Refuse anything that doesn't pass refname/SHA validation\n // rather than letting shell metacharacters through.\n this.log.warn(\"fromRef rejected by refname validation, falling back to base branch\", {\n sessionBranch,\n fromRef: session.fromRef,\n });\n return false;\n }\n try {\n git(`fetch origin ${session.fromRef}`, targetDir);\n git(`checkout -b ${sessionBranch} FETCH_HEAD`, targetDir);\n this.log.info(\"session branch created from fromRef\", {\n sessionBranch,\n fromRef: session.fromRef,\n });\n return true;\n } catch (err) {\n this.log.warn(\"fromRef fetch failed, falling back to base branch\", {\n sessionBranch,\n fromRef: session.fromRef,\n error: err instanceof Error ? err.message : String(err),\n });\n return false;\n }\n }\n\n /**\n * Fleet-managed connect: verify the host bind, register an explorer watcher,\n * no-op every git lifecycle hook. Spec: `_devlog/specs/2026-05-28-git-fleet-mode-design.md`.\n */\n private async connectFleetManaged(\n declaration: ConnectorDeclaration,\n targetDir: string,\n ): Promise<ConnectorHandle> {\n this.log.info(\"mount handled by host fleet — skipping in-container git\", {\n connectorId: declaration.id,\n targetDir,\n });\n if (declaration.mount?.exposeAccessToken) {\n // Host fleet owns credentials; managed-gitconfig is intentionally skipped.\n this.log.warn(\"fleet-managed: exposeAccessToken ignored — host fleet owns credentials\", {\n connectorId: declaration.id,\n });\n }\n await ensureFleetMounted(targetDir, this.log);\n\n let activeBranch = \"unknown\";\n try {\n activeBranch = git(\"rev-parse --abbrev-ref HEAD\", targetDir, 5_000);\n } catch {\n // worktree may be on a detached HEAD or pre-init; non-fatal.\n }\n\n const fleetConfig = resolveGitConfig({\n mode: declaration.mode,\n options: declaration.options,\n });\n const state: GitState = {\n url: String(declaration.mount?.source ?? \"\"),\n branch: activeBranch,\n activeBranch,\n session: fleetConfig.session,\n sync: fleetConfig.sync,\n lifecycle: fleetConfig.lifecycle,\n fleetManaged: true,\n };\n\n const dispatch = (event: ConnectorChangeEvent): void => {\n state.emitChange?.(event);\n };\n // Await the watcher so a rapid disconnect cannot race past an unresolved handle.\n state.fleetWatcher = await createFsWatcher(targetDir, dispatch, { ignored: [\"**/.git/**\"] });\n\n this.log.info(\"fleet mount ready\", { activeBranch, targetDir });\n return this.makeHandle(declaration, state, targetDir);\n }\n\n /**\n * Public refresh entry-point used by the runner's wake-mid-401 handler when\n * the credential-helper script touches the workspace refresh-flag. Calls\n * the same internal refresh path as the scheduled timer, but with\n * `reason: 'retry-401'` so the platform can distinguish proactive refreshes\n * from emergency ones in audit logs.\n *\n * No-op when:\n * - the handle was not minted with `exposeAccessToken: true`\n * (no `managedGitconfig` on state), or\n * - the connector was not provisioned with a `tokenMediator` (PAT path —\n * the script will keep serving the static token and the user must\n * rotate the PAT manually).\n *\n * Spec: `_devlog/specs/2026-05-07-unified-credential-mediation.md` Step 9a.\n */\n async refreshExposedCredential(connectorId: string, handle: ConnectorHandle): Promise<void> {\n const s = handle.state as GitState;\n if (!s.managedGitconfig || !s.tokenMediator) return;\n const { credentialsPath, urlPrefix } = s.managedGitconfig;\n const result = await s.tokenMediator({ connectorId, reason: \"retry-401\" });\n if (!result.ok) {\n this.log.warn(\"refresh-flag-driven mediation failed\", {\n connectorId,\n code: result.code,\n message: result.message,\n });\n return;\n }\n atomicReplaceCredential({\n mountId: connectorId,\n urlPrefix,\n token: result.token,\n credentialsPath,\n });\n s.token = result.token;\n this.log.info(\"refresh\", {\n event: \"refresh\",\n tier: 2,\n provider: \"backend\",\n scope: urlPrefix,\n reason: \"retry-401\",\n expiresAt: result.expiresAt,\n ...(result.scope ? { permissions: result.scope } : {}),\n });\n // Reschedule the proactive timer so the next pre-expiry tick still fires.\n if (result.expiresAt) {\n this.scheduleRefresh(connectorId, s, new Date(result.expiresAt));\n }\n }\n\n async disconnect(handle: ConnectorHandle): Promise<void> {\n this.log.info(\"unmount\");\n const s = handle.state as GitState;\n if (s.fleetManaged) {\n // Host owns the worktree; we only own the watcher.\n await s.fleetWatcher?.close();\n s.fleetWatcher = undefined;\n s.emitChange = undefined;\n return;\n }\n if (s.fetchTimer) {\n clearInterval(s.fetchTimer);\n s.fetchTimer = undefined;\n }\n if (s.autoCommitTimer) {\n clearTimeout(s.autoCommitTimer);\n s.autoCommitTimer = undefined;\n }\n this.teardownManagedCredential(handle.id, s);\n }\n\n private async _sync(handle: ConnectorHandle, _options?: SyncOptions): Promise<SyncResult> {\n const s = handle.state as GitState;\n if (s.fleetManaged) {\n // Host's GitFleetService owns periodic fetch/pull. Returning a no-op\n // SyncResult matches the sharepoint/webdav fleet pattern.\n this.log.debug(\"sync skipped — fleet-managed\");\n return { filesWritten: 0, filesDeleted: 0, bytesTransferred: 0 };\n }\n this.log.debug(\"sync (pull) start\", { branch: s.activeBranch });\n try {\n git(`pull origin ${s.activeBranch}`, handle.mountPath!, 60_000);\n syncSubmodules(handle.mountPath!);\n this.log.debug(\"sync ok\");\n } catch (err) {\n this.log.error(\"sync failed\", err, { branch: s.activeBranch });\n throw err;\n }\n return { filesWritten: 0, filesDeleted: 0, bytesTransferred: 0 };\n }\n\n // ── Watch ──────────────────────────────────────────────────────────────────\n\n override watch(\n handle: ConnectorHandle,\n callback: (event: ConnectorChangeEvent) => void,\n options?: WatchOptions,\n ): WatchHandle {\n const s = handle.state as GitState;\n\n if (s.fleetManaged) {\n // The fleet watcher was created in connectFleetManaged and already\n // dispatches through `s.emitChange`. Hook the caller's callback in and\n // detach on close — no auto-commit timer, no second chokidar instance.\n s.emitChange = callback;\n return {\n close: async () => {\n s.emitChange = undefined;\n },\n };\n }\n\n // Wrap callback to reset auto-commit timer on every file change\n s.emitChange = (event: ConnectorChangeEvent) => {\n callback(event);\n this.resetAutoCommitTimer(s, handle.mountPath!);\n };\n\n let fsWatcher: WatchHandle | null = null;\n let closed = false;\n\n const ignored = [...(options?.ignored ?? []), \"**/.git/**\"];\n createFsWatcher(handle.mountPath!, s.emitChange, { ...options, ignored })\n .then((w) => {\n // close() may have already run before creation resolved — dispose\n // immediately so the late watcher does not leak.\n if (closed) void w.close();\n else fsWatcher = w;\n })\n .catch((err) => {\n this.log.warn(\"watcher creation failed\", {\n error: err instanceof Error ? err.message : String(err),\n });\n });\n\n return {\n close: async () => {\n closed = true;\n s.emitChange = undefined;\n await fsWatcher?.close();\n },\n };\n }\n\n // ── Session lifecycle ──────────────────────────────────────────────────────\n\n override async onHibernate(handle: ConnectorHandle): Promise<string | undefined> {\n this.log.info(\"hibernate\");\n const s = handle.state as GitState;\n if (s.fleetManaged) {\n // Host GitFleetService schedules pushes via its idle-debounce timer.\n return \"fleet-managed\";\n }\n const lc = s.lifecycle;\n if (!lc.commitOnHibernate) return;\n\n const result = commitAll(handle.mountPath!, `skaile: hibernate snapshot`);\n if (!result) return \"Nothing to commit.\";\n\n const sha = git(\"rev-parse --short HEAD\", handle.mountPath!);\n\n if (lc.pushOnHibernate) {\n try {\n git(`push origin ${s.activeBranch}`, handle.mountPath!, 60_000);\n this.log.info(\"push ok\", { branch: s.activeBranch });\n } catch (err) {\n this.log.error(\"push failed\", err, { branch: s.activeBranch });\n throw err;\n }\n }\n\n return `Committed ${sha} on ${s.activeBranch}${lc.pushOnHibernate ? \" (pushed)\" : \"\"}`;\n }\n\n override async onSessionClose(handle: ConnectorHandle): Promise<string | undefined> {\n this.log.info(\"session closed\");\n const s = handle.state as GitState;\n if (s.fleetManaged) {\n // Host's GitFleetService detaches the worktree when its session refcount\n // reaches zero; merge/push are its job, not ours.\n return \"fleet-managed\";\n }\n const lc = s.lifecycle;\n const details: string[] = [];\n\n // Commit any remaining work on the session branch\n const commitResult = commitAll(handle.mountPath!, `skaile: session close`);\n if (commitResult) {\n const sha = git(\"rev-parse --short HEAD\", handle.mountPath!);\n details.push(`Committed ${sha}`);\n }\n\n // Push session branch\n if (lc.pushOnClose || lc.mergeOnClose) {\n git(`push origin ${s.activeBranch}`, handle.mountPath!, 60_000);\n details.push(`Pushed ${s.activeBranch}`);\n }\n\n // Merge session branch into base branch\n if (lc.mergeOnClose && s.activeBranch !== s.branch) {\n git(`checkout ${s.branch}`, handle.mountPath!);\n git(`pull origin ${s.branch}`, handle.mountPath!, 60_000);\n syncSubmodules(handle.mountPath!);\n try {\n git(`merge ${s.activeBranch}`, handle.mountPath!);\n } catch {\n const resolved = this.resolveConflictsOrAbort(s, handle.mountPath!, \"merge\");\n if (resolved) {\n details.push(\"Resolved merge conflicts (created .conflict files)\");\n }\n }\n\n if (lc.pushOnClose) {\n git(`push origin ${s.branch}`, handle.mountPath!, 60_000);\n }\n\n details.push(`Merged ${s.activeBranch} into ${s.branch}`);\n }\n\n // Tier-2: best-effort teardown of the agent-facing credential when the\n // session closes. The runner also tears connectors down on container\n // shutdown, but the host may invoke `onSessionClose` first.\n this.teardownManagedCredential(handle.id, s);\n\n return details.join(\"; \") || undefined;\n }\n\n // ── Private: managed gitconfig (Tier-2 credential exposure) ──────────────\n\n /**\n * Compute the URL prefix used to scope the credential helper. We key on\n * host plus the first path segment when one is present (e.g. for\n * `https://github.com/orgA/repo.git` we register\n * `https://github.com/orgA/`). This lets two connectors on the same host\n * with disjoint org prefixes coexist; same-host repos under one org just\n * share the same scope.\n */\n private deriveUrlPrefix(url: string): string {\n const u = new URL(url);\n const segments = u.pathname.split(\"/\").filter(Boolean);\n if (segments.length > 0) {\n return `${u.protocol}//${u.host}/${segments[0]}/`;\n }\n return `${u.protocol}//${u.host}`;\n }\n\n /**\n * Acquire the initial credential for a connector.\n *\n * `auth:` accepts the post-2026-05-06 grammar:\n * - `backend` → request a token from the platform mediator\n * (preferred for any platform-backed session).\n * - `pat:env:NAME` → static token from the secrets chain\n * (standalone CLI / non-platform contexts).\n *\n * Anonymous connectors (`auth` unset) succeed without a token — the\n * `git clone`/`git pull` calls still work for public repos.\n *\n * @returns The parsed auth ref, the resolved token (when any), and the\n * `expiresAt` timestamp surfaced by the mediator (used to schedule a\n * refresh tick when the credential is exposed to the agent CLI).\n */\n private async acquireInitialToken(\n declaration: ConnectorDeclaration,\n secrets: SecretProvider | undefined,\n tokenMediator: ConnectorTokenMediator | undefined,\n ): Promise<{\n authRef: MountAuthRef | undefined;\n token: string | undefined;\n expiresAt: Date | null;\n scope?: string[];\n }> {\n if (!declaration.auth) {\n return { authRef: undefined, token: undefined, expiresAt: null };\n }\n const authRef = resolveAuthRef(declaration.auth, declaration.id);\n if (!authRef) {\n return { authRef: undefined, token: undefined, expiresAt: null };\n }\n\n if (authRef.kind === \"backend\") {\n if (!tokenMediator) {\n throw new Error(\n `Connector '${declaration.id}' uses 'auth: backend' but no token mediator is wired ` +\n `(standalone CLI does not have one — use 'pat:env:NAME' instead).`,\n );\n }\n const result = await tokenMediator({ connectorId: declaration.id, reason: \"initial\" });\n if (!result.ok) {\n this.log.error(\"backend mediator refused initial token\", undefined, {\n connectorId: declaration.id,\n code: result.code,\n message: result.message,\n });\n throw new TokenMediatorError(result.message, result.code, declaration.id);\n }\n return {\n authRef,\n token: result.token,\n expiresAt: result.expiresAt ? new Date(result.expiresAt) : null,\n ...(result.scope ? { scope: result.scope } : {}),\n };\n }\n\n // PAT path — resolve via secrets chain when available, fall back to\n // process.env for standalone CLI contexts.\n const inner = authRef.value;\n let token: string | undefined;\n if (secrets) {\n token = secrets.resolve(inner);\n } else if (inner.startsWith(\"env:\")) {\n token = process.env[inner.slice(4)];\n } else {\n token = inner;\n }\n if (!token) {\n throw new Error(\n `PAT auth ref '${authRef.raw}' did not resolve to a token. ` +\n `Provision '${authRef.value}' in the SecretProviderChain.`,\n );\n }\n return { authRef, token, expiresAt: null };\n }\n\n private exposeManagedCredential(\n declaration: ConnectorDeclaration,\n state: GitState,\n url: string,\n initial: {\n authRef: MountAuthRef | undefined;\n token: string | undefined;\n expiresAt: Date | null;\n scope?: string[];\n },\n ): void {\n const token = initial.token;\n if (!token) {\n this.log.warn(\"managed-gitconfig: skipped — no token resolved\", {\n connectorId: declaration.id,\n });\n return;\n }\n if (!url.startsWith(\"https://\") && !url.startsWith(\"http://\")) {\n this.log.warn(\"managed-gitconfig: skipped — non-http remote\", {\n connectorId: declaration.id,\n url,\n });\n return;\n }\n\n const gitconfigPath = process.env.GIT_CONFIG_GLOBAL;\n if (!gitconfigPath) {\n this.log.warn(\"managed-gitconfig: GIT_CONFIG_GLOBAL not set — agent CLI auth will not work\", {\n connectorId: declaration.id,\n });\n return;\n }\n const skaileDir = dirname(gitconfigPath);\n const credentialsPath = join(skaileDir, \"git-credentials\");\n const urlPrefix = this.deriveUrlPrefix(url);\n\n // Step 9a: write a per-connector credential-helper script so the agent's\n // interactive `git` can refresh stale tokens mid-401 by signalling the\n // runner via a refresh-flag file. The runner watches that flag and\n // re-mints tokens on `change`. The script is per-connector (not per-\n // workspace) because each one carries its own credentialsPath + tag.\n const refreshFlagPath = join(skaileDir, \"refresh-request\");\n const helperScriptPath = join(skaileDir, `credential-helper-${declaration.id}.sh`);\n const credentialTag = `# skaile-mount: ${declaration.id}`;\n const scriptBody = renderCredentialHelperScript({\n credentialsPath,\n refreshFlagPath,\n credentialTag,\n });\n try {\n writeHelperScript(helperScriptPath, scriptBody);\n } catch (err) {\n this.log.warn(\n \"managed-gitconfig: failed to write credential-helper script -- falling back to static helper\",\n {\n connectorId: declaration.id,\n error: err instanceof Error ? err.message : String(err),\n },\n );\n }\n\n writeMountBlock({\n mountId: declaration.id,\n urlPrefix,\n token,\n gitconfigPath,\n credentialsPath,\n helperScriptPath,\n });\n\n state.managedGitconfig = { gitconfigPath, credentialsPath, urlPrefix };\n\n const providerKind = initial.authRef?.kind ?? \"pat\";\n const isRefreshable = providerKind === \"backend\" && initial.expiresAt !== null;\n\n // Spec'd schema: kind=mount, subkind=git, instance=<id>, data.event=mint,\n // data.tier=2, data.provider, data.scope. PAT path is static — flag the\n // warning so operators see \"no refresh\" in the logs.\n this.log.info(\"mint\", {\n event: \"mint\",\n origin: \"tier-2\",\n tier: 2,\n provider: providerKind,\n scope: urlPrefix,\n expiresAt: initial.expiresAt ? initial.expiresAt.toISOString() : null,\n ...(initial.scope ? { permissions: initial.scope } : {}),\n ...(isRefreshable ? {} : { warning: \"static-credential\" }),\n });\n\n // Backend-mediated tokens with finite expiry → schedule the rotation\n // tick. The 5-minute lead lets the long-push 401 retry path re-read the\n // new token via `credential.helper store` before the in-flight token\n // expires.\n if (isRefreshable && state.tokenMediator && initial.expiresAt) {\n this.scheduleRefresh(declaration.id, state, initial.expiresAt);\n }\n }\n\n /**\n * Schedule the next refresh of the credential file.\n *\n * Cancels any existing timer first so re-connects (and the test harness)\n * do not double-fire. Uses a 5-minute lead per spec; if the lead is\n * negative (very short-lived test tokens) we fall back to a tiny delay\n * so the timer still fires in deterministic order.\n */\n private scheduleRefresh(connectorId: string, state: GitState, expiresAt: Date): void {\n if (state.refreshTimer) {\n clearTimeout(state.refreshTimer);\n state.refreshTimer = undefined;\n }\n const FIVE_MINUTES_MS = 5 * 60 * 1000;\n const delay = Math.max(1_000, expiresAt.getTime() - Date.now() - FIVE_MINUTES_MS);\n state.refreshTimer = setTimeout(() => {\n this.refreshManagedCredential(connectorId, state).catch((err) => {\n this.log.error(\"managed-gitconfig refresh failed\", err, { connectorId });\n });\n }, delay);\n }\n\n private async refreshManagedCredential(connectorId: string, state: GitState): Promise<void> {\n if (!state.tokenMediator) return;\n\n const result = await state.tokenMediator({ connectorId, reason: \"refresh\" });\n if (!result.ok) {\n this.log.error(\"backend mediator refused refresh\", undefined, {\n connectorId,\n code: result.code,\n message: result.message,\n });\n // Best-effort retry once after 30s on transient errors. On a second\n // failure we surface via the existing log channel and stop scheduling\n // — the next git operation will hit a 401 and the manager will\n // restart the connector via its existing failure path.\n if (result.code === \"backend-error\" || result.code === \"provider-error\") {\n if (state.refreshTimer) {\n clearTimeout(state.refreshTimer);\n state.refreshTimer = undefined;\n }\n state.refreshTimer = setTimeout(() => {\n this.refreshManagedCredential(connectorId, state).catch((err) => {\n this.log.error(\"managed-gitconfig refresh retry failed\", err, { connectorId });\n });\n }, 30_000);\n }\n return;\n }\n\n state.token = result.token;\n if (state.managedGitconfig) {\n atomicReplaceCredential({\n mountId: connectorId,\n urlPrefix: state.managedGitconfig.urlPrefix,\n token: result.token,\n credentialsPath: state.managedGitconfig.credentialsPath,\n });\n } else if (state.targetDir) {\n // Tier-1: the URL token is the sole credential — re-bake it.\n this.rebakeRemoteAuth(state.targetDir, state);\n }\n\n this.log.info(\"refresh\", {\n event: \"refresh\",\n tier: state.managedGitconfig ? 2 : 1,\n provider: \"backend\",\n scope: state.managedGitconfig?.urlPrefix ?? state.url,\n expiresAt: result.expiresAt,\n ...(result.scope ? { permissions: result.scope } : {}),\n });\n\n if (result.expiresAt) {\n this.scheduleRefresh(connectorId, state, new Date(result.expiresAt));\n }\n }\n\n private teardownManagedCredential(connectorId: string, state: GitState): void {\n if (state.refreshTimer) {\n clearTimeout(state.refreshTimer);\n state.refreshTimer = undefined;\n }\n // Tier-1 has no gitconfig block to remove, but the mediator ref must still\n // be dropped from the disconnected handle's state.\n state.tokenMediator = undefined;\n if (!state.managedGitconfig) return;\n try {\n removeMountBlock({\n mountId: connectorId,\n gitconfigPath: state.managedGitconfig.gitconfigPath,\n credentialsPath: state.managedGitconfig.credentialsPath,\n });\n this.log.info(\"teardown\", {\n event: \"teardown\",\n tier: 2,\n scope: state.managedGitconfig.urlPrefix,\n });\n } catch (err) {\n this.log.warn(\"managed-gitconfig: teardown best-effort failed\", {\n connectorId,\n error: err instanceof Error ? err.message : String(err),\n });\n } finally {\n state.managedGitconfig = undefined;\n state.tokenMediator = undefined;\n }\n }\n\n // ── Private: in-place git init ───────────────────────────────────────────\n\n /**\n * Bring a populated, non-git directory under git tracking without\n * touching the working tree. Runs only on the \"dir populated, no `.git`\"\n * branch of `connect()` — exactly when a previous connect aborted before\n * `.git` was written, or when the bind-mounted host dir's `.git` FILE\n * pointed outside the container.\n *\n * The intent is to preserve whatever the agent last had on disk. We\n * therefore:\n * - `git init` — creates `.git/`; does not modify any existing file.\n * - `git remote add origin <authUrl>` — wires up the remote so the\n * normal lifecycle hooks (`pushOnHibernate`, `pushAfterCommit`)\n * have a target.\n *\n * Deliberately omitted:\n * - `fetch` — would touch the network on every recreate. The lifecycle\n * handles sync explicitly (periodic `fetch`/`pull` via\n * `sync.autoPull`, push on hibernate, etc.).\n * - `checkout -f` / `reset --hard` / `clean -fd` — would discard the\n * user's last on-disk state. The agent or autocommit reconciles\n * with the remote later.\n *\n * Token persistence: the auth URL gets written into `.git/config`\n * exactly like the `git clone <authUrl>` path does — token-rotation\n * handling is external to this method (managed-gitconfig credential\n * helper refresh in Tier-2 connectors).\n */\n private initInPlace(targetDir: string, authUrl: string): void {\n git(\"init\", targetDir, 10_000);\n // Replace any existing origin (idempotent across re-connects).\n try {\n git(\"remote remove origin\", targetDir, 5_000);\n } catch {\n /* no existing origin — fine */\n }\n execSync(`git remote add origin ${authUrl}`, {\n cwd: targetDir,\n encoding: \"utf-8\",\n timeout: 5_000,\n stdio: \"pipe\",\n });\n }\n\n /**\n * True when `<targetDir>/.git` contains at least one resolvable commit\n * (i.e. `HEAD` points at a real object). False when `.git` is an empty\n * shell — e.g. just-initialised but never fetched, or all refs deleted.\n *\n * Used by `connect()` to tell the difference between a working agent\n * checkout (preserve, don't touch) and a half-initialised one\n * (bootstrap by fetching from origin).\n */\n private isInitialisedCheckout(targetDir: string): boolean {\n try {\n git(\"rev-parse HEAD\", targetDir, 5_000);\n return true;\n } catch {\n return false;\n }\n }\n\n /**\n * One-shot bootstrap path for the \"`.git` exists but is empty\" state.\n *\n * Runs `fetch --depth=1 origin <branch>` followed by `checkout -B\n * <branch> origin/<branch>` so the working tree gets the remote\n * content. Before the checkout, any untracked file whose path also\n * exists in the remote tree is renamed to `<path>.local` so the user\n * (or previous agent run) does not lose data. Other untracked files\n * are left in place.\n *\n * Deliberately not destructive: we never `clean -fd` and never\n * `reset --hard`. Files that do not conflict with the remote stay\n * exactly where they are.\n *\n * Auth-URL handling matches `initInPlace`: a pre-existing `origin`\n * remote is replaced with the authed URL so the fetch works even\n * after token rotation. This persists the token in `.git/config`\n * the same way `git clone <authUrl>` does — token-rotation handling\n * is external to this connector method.\n */\n private bootstrapFromOrigin(targetDir: string, branch: string, authUrl: string): void {\n // Ensure origin points at the current authed URL — handles the case\n // where the previous `initInPlace` wrote a stale token, or the\n // remote was never configured at all.\n try {\n git(\"remote remove origin\", targetDir, 5_000);\n } catch {\n /* no existing origin — fine */\n }\n execSync(`git remote add origin ${authUrl}`, {\n cwd: targetDir,\n encoding: \"utf-8\",\n timeout: 5_000,\n stdio: \"pipe\",\n });\n git(`fetch --depth=1 origin ${branch}`, targetDir, 120_000);\n this.preserveConflictingUntracked(targetDir, branch);\n git(`checkout -B ${branch} origin/${branch}`, targetDir, 30_000);\n syncSubmodules(targetDir);\n try {\n git(`branch --set-upstream-to=origin/${branch} ${branch}`, targetDir, 5_000);\n } catch {\n /* best-effort */\n }\n }\n\n /**\n * Walk the remote tree at `origin/<branch>` and rename any untracked\n * working-tree file whose path also exists there. Renames go to\n * `<path>.local`; on `.local` collision a millisecond suffix is\n * appended so nothing is overwritten.\n *\n * This makes the subsequent `git checkout -B <branch> origin/<branch>`\n * safe: without it, `checkout` aborts with \"untracked working tree\n * files would be overwritten\" the moment any local file collides with\n * a tracked path on the remote.\n *\n * Files in the local tree whose paths are NOT in the remote tree are\n * left untouched — they are pure local additions and survive the\n * bootstrap.\n */\n private preserveConflictingUntracked(targetDir: string, branch: string): void {\n let remoteFiles: string[] = [];\n try {\n remoteFiles = git(`ls-tree -r origin/${branch} --name-only`, targetDir, 30_000)\n .split(\"\\n\")\n .filter(Boolean);\n } catch (err) {\n this.log.warn(\"ls-tree failed — skipping untracked preservation\", {\n branch,\n error: err instanceof Error ? err.message : String(err),\n });\n return;\n }\n for (const relPath of remoteFiles) {\n const fullPath = join(targetDir, relPath);\n if (!existsSync(fullPath)) continue;\n let dest = `${fullPath}.local`;\n if (existsSync(dest)) {\n dest = `${fullPath}.local.${Date.now()}`;\n }\n try {\n renameSync(fullPath, dest);\n this.log.info(\"preserved local file as .local\", { path: relPath, dest });\n } catch (err) {\n this.log.warn(\"failed to preserve local file — checkout may fail\", {\n path: relPath,\n error: err instanceof Error ? err.message : String(err),\n });\n }\n }\n }\n\n // ── Private: auth URL ─────────────────────────────────────────────────────\n\n private authUrl(s: GitState): string {\n if (s.token && s.url.startsWith(\"https://\")) {\n const urlObj = new URL(s.url);\n urlObj.username = \"x-access-token\";\n urlObj.password = s.token;\n return urlObj.toString();\n }\n return s.url;\n }\n\n /**\n * Rewrite `origin` to drop any inline `user:password@` credentials, leaving\n * a bare https(s) URL. Tier-2 only: the managed credential helper supplies\n * (and refreshes) the token, but git ignores helpers when the URL already\n * carries creds — so the baked-in token must go. Best-effort: a missing\n * origin or a non-http(s) remote (e.g. file:// in tests) is left untouched.\n */\n private stripRemoteInlineToken(targetDir: string): void {\n try {\n const current = git(\"remote get-url origin\", targetDir, 5_000);\n if (!current.startsWith(\"https://\") && !current.startsWith(\"http://\")) return;\n const u = new URL(current);\n if (!u.username && !u.password) return;\n u.username = \"\";\n u.password = \"\";\n git(`remote set-url origin ${u.toString()}`, targetDir, 5_000);\n } catch (err) {\n this.log.warn(\"managed-gitconfig: failed to strip inline token from origin\", {\n error: err instanceof Error ? err.message : String(err),\n });\n }\n }\n\n /**\n * Tier-1 only: rewrite `origin` so it carries the token freshly minted on\n * this connect. The \"use as-is\" wake path leaves whatever token the first\n * connect baked in — long-dead for short-lived (GitHub App) tokens. Without\n * a Tier-2 helper this URL token is the sole credential, so it must be\n * refreshed here. No-op for anonymous (no token) or non-https remotes.\n */\n private rebakeRemoteAuth(targetDir: string, state: GitState): void {\n if (!state.token || !state.url.startsWith(\"https://\")) return;\n try {\n git(`remote set-url origin ${this.authUrl(state)}`, targetDir, 5_000);\n } catch (err) {\n this.log.warn(\"failed to refresh inline token on origin\", {\n error: err instanceof Error ? err.message : String(err),\n });\n }\n }\n\n // ── Periodic fetch ─────────────────────────────────────────────────────────\n\n private startPeriodicFetch(s: GitState, mountPath: string): void {\n if (s.fetchTimer) clearInterval(s.fetchTimer);\n\n const intervalMs = s.sync.fetchIntervalSec * 1000;\n s.fetchTimer = setInterval(() => {\n try {\n git(\"fetch origin\", mountPath, 60_000);\n if (s.sync.autoRebase && s.activeBranch !== s.branch) {\n try {\n git(`rebase origin/${s.branch}`, mountPath, 60_000);\n } catch {\n this.resolveConflictsOrAbort(s, mountPath, \"rebase\");\n }\n syncSubmodules(mountPath);\n } else if (s.sync.autoPull) {\n git(`pull origin ${s.activeBranch}`, mountPath, 60_000);\n syncSubmodules(mountPath);\n }\n } catch {\n // Periodic fetch is best-effort\n }\n }, intervalMs);\n }\n\n // ── Conflict resolution ──────────────────────────────────────────────────\n\n /**\n * Attempt to resolve merge/rebase conflicts by keeping \"ours\" and copying\n * \"theirs\" to a .conflict file. If resolution fails entirely, abort.\n * Returns true if conflicts were resolved, false if aborted.\n */\n private resolveConflictsOrAbort(\n s: GitState,\n mountPath: string,\n mode: \"rebase\" | \"merge\",\n ): boolean {\n try {\n const conflicted = git(\"diff --name-only --diff-filter=U\", mountPath)\n .split(\"\\n\")\n .filter(Boolean);\n\n if (conflicted.length === 0) return false;\n\n for (const file of conflicted) {\n this.resolveFileConflict(mountPath, file);\n }\n\n // Continue the rebase/merge\n if (mode === \"rebase\") {\n git(\"-c core.editor=true rebase --continue\", mountPath, 30_000);\n } else {\n git(`commit --no-edit`, mountPath);\n }\n\n // Emit change events for conflict files\n for (const file of conflicted) {\n const ext = file.includes(\".\") ? file.slice(file.lastIndexOf(\".\")) : \"\";\n const base = file.includes(\".\") ? file.slice(0, file.lastIndexOf(\".\")) : file;\n s.emitChange?.({\n path: `${base}.conflict${ext}`,\n action: \"create\",\n source: \"sync\",\n });\n }\n\n return true;\n } catch {\n // Abort if resolution fails\n try {\n if (mode === \"rebase\") {\n git(\"rebase --abort\", mountPath);\n } else {\n git(\"merge --abort\", mountPath);\n }\n } catch {\n /* already clean */\n }\n return false;\n }\n }\n\n /**\n * For a single conflicted file: keep \"ours\", save \"theirs\" as .conflict file.\n */\n private resolveFileConflict(root: string, file: string): void {\n const ext = file.includes(\".\") ? file.slice(file.lastIndexOf(\".\")) : \"\";\n const base = file.includes(\".\") ? file.slice(0, file.lastIndexOf(\".\")) : file;\n const conflictPath = `${base}.conflict${ext}`;\n\n try {\n // Extract \"theirs\" version (stage 3)\n const theirs = git(`show :3:${file}`, root);\n writeFileSync(join(root, conflictPath), theirs);\n } catch {\n // If we can't get theirs, copy the conflicted file as-is\n const fullPath = join(root, file);\n if (existsSync(fullPath)) {\n const content = readFileSync(fullPath, \"utf-8\");\n writeFileSync(join(root, conflictPath), content);\n }\n }\n\n try {\n // Keep \"ours\" version (stage 2)\n const ours = git(`show :2:${file}`, root);\n writeFileSync(join(root, file), ours);\n } catch {\n // Strip conflict markers, keeping our sections\n const fullPath = join(root, file);\n if (existsSync(fullPath)) {\n const content = readFileSync(fullPath, \"utf-8\");\n writeFileSync(fullPath, this.stripConflictKeepOurs(content));\n }\n }\n\n git(`add ${file} ${conflictPath}`, root);\n }\n\n private stripConflictKeepOurs(content: string): string {\n return content.replace(/<<<<<<< .*\\n/g, \"\").replace(/=======\\n[\\s\\S]*?>>>>>>> .*\\n/g, \"\");\n }\n\n // ── Auto-commit on idle ────────────────────────────────────────────────────\n\n private resetAutoCommitTimer(s: GitState, mountPath: string): void {\n if (s.lifecycle.autoCommitIdleMs <= 0) return;\n if (s.autoCommitTimer) clearTimeout(s.autoCommitTimer);\n s.autoCommitTimer = setTimeout(() => {\n this.performAutoCommit(s, mountPath);\n }, s.lifecycle.autoCommitIdleMs);\n }\n\n private performAutoCommit(s: GitState, mountPath: string): void {\n try {\n const message = this.generateCommitMessage(mountPath);\n const result = commitAll(mountPath, message);\n if (!result) return;\n if (s.lifecycle.pushAfterCommit) {\n try {\n git(`push origin ${s.activeBranch}`, mountPath, 60_000);\n } catch {\n // Push is best-effort\n }\n }\n } catch {\n // Auto-commit is best-effort\n }\n }\n\n private generateCommitMessage(mountPath: string): string {\n try {\n git(\"add -A\", mountPath);\n const stat = git(\"diff --cached --stat\", mountPath);\n const lines = stat.split(\"\\n\").filter((l) => l.includes(\"|\"));\n if (lines.length === 0) return \"skaile: auto-save\";\n const files = lines.map((l) => l.split(\"|\")[0]!.trim());\n if (files.length === 1) return `Update ${files[0]}`;\n return `Update ${files.length} files`;\n } catch {\n return \"skaile: auto-save\";\n }\n }\n}\n\n/**\n * Creates a new GitConnector instance.\n * @returns Configured GitConnector ready to be registered in the connector registry.\n * @docLink packages/factory-assets/api-reference#git-connector-factory\n */\nexport function createConnector(): GitConnector {\n return new GitConnector();\n}\n\n/** Test-only surface — exposes the mode→config resolver for unit assertions. */\nexport const __test = { resolveGitConfig };\n","/**\n * GmailConnector — connect to Gmail via Google API OAuth.\n *\n * Auth: oauth:google:<account> — managed by OAuthSecretProvider.\n * Peer dependency: googleapis (lazy-loaded).\n */\n\nimport type {\n ConnectContext,\n ConnectorDeclaration,\n ConnectorFieldSpec,\n ConnectorHandle,\n OperationDescriptor,\n RuntimeSkillDescriptor,\n ToolFace,\n} from \"@skaile/workspaces/connectors\";\nimport { AbstractConnector } from \"@skaile/workspaces/connectors\";\n\ninterface GmailState {\n account: string;\n accessToken: string;\n gmail: any; // googleapis gmail client\n}\n\n/**\n * Connector for Gmail — provides read and send access to email messages and drafts via the Google API.\n * Authenticates using OAuth2 (managed by OAuthSecretProvider). Requires the `googleapis` optional peer dependency.\n * @docLink packages/factory-assets/concepts#gmail-connector\n */\nexport class GmailConnector extends AbstractConnector {\n readonly name = \"gmail\";\n\n tools: ToolFace;\n\n constructor() {\n super();\n this.tools = {\n describeOperations: (handle) => this._describeOperations(handle),\n executeOp: (handle, operation, args) => this._executeOp(handle, operation, args),\n describeSkill: (handle, declaration) => this._describeSkill(handle, declaration),\n };\n }\n\n describeFields(): ConnectorFieldSpec[] {\n return [\n {\n key: \"account\",\n label: \"Gmail Account\",\n description: \"Email address — used to label this connector and scope the OAuth token\",\n type: \"text\",\n required: true,\n sensitive: false,\n group: \"Connection\",\n },\n {\n key: \"auth\",\n label: \"Authentication\",\n description: \"OAuth access token for this Gmail account. Click to authorize.\",\n type: \"oauth\",\n oauthService: \"google\",\n required: true,\n sensitive: true,\n group: \"Authentication\",\n },\n ];\n }\n\n async connect(declaration: ConnectorDeclaration, ctx: ConnectContext): Promise<ConnectorHandle> {\n const account = ctx.resolvedFields?.account ?? String(declaration.options?.account ?? \"\");\n const accessToken =\n ctx.resolvedFields?.auth ?? ctx.secrets?.resolve(declaration.auth ?? \"\") ?? \"\";\n\n if (!accessToken) {\n this.log.warn(\"OAuth access token missing or refresh failed\", { account });\n throw new Error(`GmailConnector requires OAuth access token for account \"${account}\"`);\n }\n\n this.log.info(\"connect\", { account });\n const googleapisPkg = \"googleapis\";\n const { google } = (await import(/* @vite-ignore */ googleapisPkg)) as any;\n const auth = new google.auth.OAuth2();\n auth.setCredentials({ access_token: accessToken });\n const gmail = google.gmail({ version: \"v1\", auth });\n\n return this.makeHandle(declaration, { account, accessToken, gmail } as GmailState);\n }\n\n async disconnect(handle: ConnectorHandle): Promise<void> {\n this.log.info(\"disconnect\");\n // No network teardown required for Gmail OAuth — token expiry is managed externally.\n handle.status = \"disconnected\";\n }\n\n // ── Tool face methods (private, wired in constructor) ─────────────────────\n\n private _describeSkill(\n _handle: ConnectorHandle,\n declaration: ConnectorDeclaration,\n ): RuntimeSkillDescriptor {\n const account = String(declaration.options?.account ?? \"unknown\");\n return {\n id: declaration.id,\n name: `Gmail — ${account}`,\n description: `Read and write email for ${account}`,\n category: \"email\",\n access: declaration.access,\n toolNames:\n declaration.access === \"read-write\"\n ? [\"list_messages\", \"get_message\", \"send_message\", \"search_messages\", \"create_draft\"]\n : [\"list_messages\", \"get_message\", \"search_messages\"],\n };\n }\n\n private _describeOperations(handle: ConnectorHandle): OperationDescriptor[] {\n const ops: OperationDescriptor[] = [\n {\n name: \"list_messages\",\n description: \"List messages in the inbox or a label\",\n accessLevel: \"read\",\n args: [\n {\n name: \"label\",\n type: \"string\",\n required: false,\n description: \"Label ID (default: INBOX)\",\n },\n {\n name: \"limit\",\n type: \"number\",\n required: false,\n description: \"Max results (default: 20)\",\n },\n ],\n },\n {\n name: \"get_message\",\n description: \"Fetch a full message by ID\",\n accessLevel: \"read\",\n args: [{ name: \"id\", type: \"string\", required: true, description: \"Message ID\" }],\n },\n {\n name: \"search_messages\",\n description: \"Search messages using Gmail query syntax\",\n accessLevel: \"read\",\n args: [\n { name: \"query\", type: \"string\", required: true, description: \"Gmail search query\" },\n ],\n },\n ];\n\n if (handle.access === \"read-write\") {\n ops.push(\n {\n name: \"send_message\",\n description: \"Send an email\",\n accessLevel: \"write\",\n args: [\n { name: \"to\", type: \"string\", required: true, description: \"Recipient address\" },\n { name: \"subject\", type: \"string\", required: true, description: \"Subject line\" },\n { name: \"body\", type: \"string\", required: true, description: \"Message body\" },\n {\n name: \"html\",\n type: \"boolean\",\n required: false,\n description: \"Set to true if body is HTML\",\n },\n ],\n },\n {\n name: \"create_draft\",\n description: \"Create a draft without sending\",\n accessLevel: \"write\",\n args: [\n { name: \"to\", type: \"string\", required: true, description: \"Recipient address\" },\n { name: \"subject\", type: \"string\", required: true, description: \"Subject line\" },\n { name: \"body\", type: \"string\", required: true, description: \"Message body\" },\n ],\n },\n );\n }\n\n return ops;\n }\n\n private async _executeOp(\n handle: ConnectorHandle,\n operation: string,\n args: Record<string, unknown>,\n ): Promise<string> {\n const { gmail, account } = handle.state as GmailState;\n\n switch (operation) {\n case \"list_messages\": {\n const res = await gmail.users.messages.list({\n userId: \"me\",\n labelIds: [String(args.label ?? \"INBOX\")],\n maxResults: Number(args.limit ?? 20),\n });\n return JSON.stringify(res.data.messages ?? [], null, 2);\n }\n case \"get_message\": {\n const res = await gmail.users.messages.get({\n userId: \"me\",\n id: String(args.id),\n format: \"full\",\n });\n return JSON.stringify(res.data, null, 2);\n }\n case \"search_messages\": {\n const res = await gmail.users.messages.list({ userId: \"me\", q: String(args.query) });\n return JSON.stringify(res.data.messages ?? [], null, 2);\n }\n case \"send_message\": {\n const raw = this._buildRawMessage(\n account,\n String(args.to),\n String(args.subject),\n String(args.body),\n Boolean(args.html),\n );\n await gmail.users.messages.send({ userId: \"me\", requestBody: { raw } });\n return \"Message sent.\";\n }\n case \"create_draft\": {\n const raw = this._buildRawMessage(\n account,\n String(args.to),\n String(args.subject),\n String(args.body),\n false,\n );\n const res = await gmail.users.drafts.create({\n userId: \"me\",\n requestBody: { message: { raw } },\n });\n return `Draft created: ${res.data.id}`;\n }\n default:\n throw new Error(`GmailConnector has no operation \"${operation}\"`);\n }\n }\n\n private _buildRawMessage(\n from: string,\n to: string,\n subject: string,\n body: string,\n html: boolean,\n ): string {\n const contentType = html ? \"text/html\" : \"text/plain\";\n const message = [\n `From: ${from}`,\n `To: ${to}`,\n `Subject: ${subject}`,\n `MIME-Version: 1.0`,\n `Content-Type: ${contentType}; charset=utf-8`,\n \"\",\n body,\n ].join(\"\\n\");\n return Buffer.from(message).toString(\"base64url\");\n }\n}\n\n/**\n * Creates a new GmailConnector instance.\n * @returns Configured GmailConnector ready to be registered in the connector registry.\n * @docLink packages/factory-assets/api-reference#gmail-connector-factory\n */\nexport function createConnector(): GmailConnector {\n return new GmailConnector();\n}\n","/**\n * GoogleDriveConnector — Google Drive (a.k.a. Google Files) filesystem-face\n * connector backed by rclone FUSE.\n *\n * The whole data plane (enumeration, download, upload, change detection,\n * cache eviction) is delegated to an `rclone mount` subprocess managed by\n * {@link RcloneProcessManager}. This connector only parses the declaration,\n * renders the rclone config, hands it off, and forwards lifecycle hooks.\n */\n\nimport type {\n ConnectContext,\n ConnectorDeclaration,\n ConnectorHandle,\n FilesystemFace,\n GoogleDriveScope,\n RcloneHandle,\n SyncOptions,\n SyncResult,\n} from \"@skaile/workspaces/connectors\";\nimport {\n AbstractConnector,\n ensureDirMode,\n ensureFleetMounted,\n isFleetManaged,\n RcloneProcessManager,\n renderGoogleDriveConfig,\n resolveMountCredentialString,\n} from \"@skaile/workspaces/connectors\";\n\ninterface GoogleDriveState {\n rcloneHandle: RcloneHandle | null;\n fleetManaged?: boolean;\n /**\n * Authoritative remote-size hook read by the mount read path to defeat the\n * rclone VFS stale tail (a shorter remote rewrite served as\n * `[new bytes][leftover tail]`). Absent on fleet mounts — the in-container\n * connector has no rc server to query.\n */\n authoritativeSize?: (relPath: string) => Promise<number | null>;\n}\n\ninterface ParsedAuth {\n accessToken: string;\n refreshToken: string | null;\n expiresAtMs: number | null;\n clientId: string | null;\n clientSecret: string | null;\n serviceAccountFile: string | null;\n}\n\nconst DEFAULT_CACHE_BASE = \"/var/cache/skaile\";\n\n// Cache root for rclone VFS dirs. Read per-connect (not at module load) and\n// overridable via env so the path can follow the host bind-mount and so tests\n// can target a writable (non-root) location. Mirrors the sharepoint driver.\nfunction cacheBase(): string {\n return process.env.SKAILE_RCLONE_CACHE_BASE ?? DEFAULT_CACHE_BASE;\n}\n\nconst ALLOWED_SCOPES: ReadonlySet<GoogleDriveScope> = new Set([\n \"drive\",\n \"drive.readonly\",\n \"drive.file\",\n \"drive.appfolder\",\n \"drive.metadata.readonly\",\n]);\n\n/**\n * Filesystem-face connector for Google Drive — delegates the data plane to an\n * `rclone mount` subprocess via `RcloneProcessManager` using the `drive` backend.\n * Supports OAuth2 access tokens with optional refresh, service-account JSON files,\n * and fleet-managed mode via `SKAILE_FLEET_MANAGED_MOUNTS`.\n * @docLink packages/factory-assets/concepts#googledrive-connector\n */\nexport class GoogleDriveConnector extends AbstractConnector {\n readonly name = \"googledrive\";\n\n private rclone = new RcloneProcessManager();\n\n readonly filesystem: FilesystemFace = {\n deferMount: true,\n sync: (handle: ConnectorHandle, options?: SyncOptions): Promise<SyncResult> => {\n return this._sync(handle, options);\n },\n };\n\n async connect(declaration: ConnectorDeclaration, ctx: ConnectContext): Promise<ConnectorHandle> {\n const targetDir = ctx.mountTarget;\n if (!targetDir) {\n throw new Error(\"GoogleDriveConnector requires ctx.mountTarget to be set by the manager\");\n }\n const secrets = ctx.secrets;\n const tokenMediator = ctx.tokenMediator;\n\n const opts = declaration.options;\n this.log.info(\"mount called\", {\n optionKeys: opts ? Object.keys(opts) : [],\n });\n\n if (isFleetManaged(declaration.id)) {\n this.log.info(\"mount handled by host fleet — skipping in-container rclone spawn\", {\n connectorId: declaration.id,\n targetDir,\n });\n await ensureFleetMounted(targetDir, this.log);\n const fleetState: GoogleDriveState = {\n rcloneHandle: null,\n fleetManaged: true,\n };\n return this.makeHandle(declaration, fleetState, targetDir);\n }\n\n const scopeRaw = opts?.scope !== undefined ? String(opts.scope) : \"drive\";\n if (!ALLOWED_SCOPES.has(scopeRaw as GoogleDriveScope)) {\n throw new Error(\n `Google Drive connector: invalid scope \"${scopeRaw}\" (allowed: ${[...ALLOWED_SCOPES].join(\", \")})`,\n );\n }\n const scope = scopeRaw as GoogleDriveScope;\n\n const auth = parseAuthBlob(\n await resolveMountCredentialString(declaration, secrets, tokenMediator),\n this.log,\n );\n if (!auth.accessToken && !auth.serviceAccountFile) {\n throw new Error(\n \"Google Drive connector: no access token or serviceAccountFile resolved. Use 'auth: backend' (platform) or 'auth: env:GDRIVE_TOKEN' (standalone).\",\n );\n }\n\n const rootFolderId = opts?.rootFolderId !== undefined ? String(opts.rootFolderId) : null;\n const teamDrive = opts?.teamDrive !== undefined ? String(opts.teamDrive) : null;\n const basePath = String(opts?.basePath ?? \"\").replace(/^\\/+|\\/+$/g, \"\");\n\n const remoteName = `skaile-${declaration.id}`;\n const remotePath = basePath.length > 0 ? `/${basePath}` : \"/\";\n const remote = `${remoteName}:${remotePath}`;\n const base = cacheBase();\n const cacheDir = `${base}/${declaration.id}`;\n const vfsCacheMode = declaration.access === \"read-only\" ? \"minimal\" : \"full\";\n\n this.log.info(\"mount params resolved\", {\n scope,\n remote,\n cacheDir,\n vfsCacheMode,\n hasRefresh: auth.refreshToken !== null,\n hasServiceAccount: auth.serviceAccountFile !== null,\n teamDrive,\n });\n\n const rcloneConfig = renderGoogleDriveConfig({\n remoteName,\n accessToken: auth.accessToken,\n refreshToken: auth.refreshToken,\n expiresAtMs: auth.expiresAtMs,\n clientId: auth.clientId,\n clientSecret: auth.clientSecret,\n scope,\n rootFolderId,\n teamDrive,\n serviceAccountFile: auth.serviceAccountFile,\n });\n\n await ensureDirMode(base, this.log);\n await ensureDirMode(cacheDir, this.log);\n await ensureDirMode(targetDir, this.log);\n\n const cacheMaxSize = opts?.cacheMaxSize !== undefined ? String(opts.cacheMaxSize) : undefined;\n const cacheMaxAge = opts?.cacheMaxAge !== undefined ? String(opts.cacheMaxAge) : undefined;\n const vfsWriteBack = opts?.vfsWriteBack !== undefined ? String(opts.vfsWriteBack) : undefined;\n\n const rcloneHandle = await this.rclone.spawn({\n mountId: declaration.id,\n driverName: \"googledrive\",\n mountPoint: targetDir,\n cacheDir,\n rcloneConfig,\n remote,\n vfsCacheMode,\n ...(cacheMaxSize !== undefined ? { cacheMaxSize } : {}),\n ...(cacheMaxAge !== undefined ? { cacheMaxAge } : {}),\n ...(vfsWriteBack !== undefined ? { vfsWriteBack } : {}),\n log: this.log,\n });\n\n this.log.info(\"mount ready\", { pid: rcloneHandle.pid });\n\n const state: GoogleDriveState = {\n rcloneHandle,\n // Safe to close over the handle directly: GoogleDrive has no token-refresh\n // recycle (unlike sharepoint/webdav, which dereference a handleRef so the\n // hook follows the recycled handle). If a refresh/reconfigure path is ever\n // added here, switch this to the handleRef indirection or it will query a\n // stale handle.\n authoritativeSize: (relPath: string) => this.rclone.statSize(rcloneHandle, relPath),\n };\n return this.makeHandle(declaration, state, targetDir);\n }\n\n async disconnect(handle: ConnectorHandle): Promise<void> {\n const s = handle.state as GoogleDriveState;\n if (s.fleetManaged || !s.rcloneHandle) return;\n await this.rclone.stop(s.rcloneHandle, { graceMs: 30_000 });\n }\n\n private async _sync(handle: ConnectorHandle, options?: SyncOptions): Promise<SyncResult> {\n const s = handle.state as GoogleDriveState;\n if (s.fleetManaged || !s.rcloneHandle) {\n options?.onSyncStatus?.({\n phase: \"initial_sync_complete\",\n totalFiles: 0,\n downloadedFiles: 0,\n stubFiles: 0,\n message: \"fleet-managed mount — flush handled by host\",\n });\n return { filesWritten: 0, filesDeleted: 0, bytesTransferred: 0 };\n }\n await this.rclone.flush(s.rcloneHandle);\n options?.onSyncStatus?.({\n phase: \"initial_sync_complete\",\n totalFiles: 0,\n downloadedFiles: 0,\n stubFiles: 0,\n message: \"rclone flush complete\",\n });\n return { filesWritten: 0, filesDeleted: 0, bytesTransferred: 0 };\n }\n\n override async onHibernate(handle: ConnectorHandle): Promise<string | undefined> {\n const s = handle.state as GoogleDriveState;\n if (s.fleetManaged) return \"flushed\";\n await this._sync(handle);\n return \"flushed\";\n }\n\n override async onSessionClose(handle: ConnectorHandle): Promise<string | undefined> {\n const s = handle.state as GoogleDriveState;\n if (s.fleetManaged) return \"flushed\";\n await this._sync(handle);\n return \"flushed\";\n }\n}\n\n/**\n * Creates a new GoogleDriveConnector instance.\n * @returns Configured GoogleDriveConnector ready to be registered in the connector registry.\n * @docLink packages/factory-assets/api-reference#googledrive-connector-factory\n */\nexport function createConnector(): GoogleDriveConnector {\n return new GoogleDriveConnector();\n}\n\n// ── helpers ────────────────────────────────────────────────────────────────\n\nfunction parseAuthBlob(\n raw: string | undefined,\n log?: { warn: (msg: string, data?: object) => void },\n): ParsedAuth {\n const empty: ParsedAuth = {\n accessToken: \"\",\n refreshToken: null,\n expiresAtMs: null,\n clientId: null,\n clientSecret: null,\n serviceAccountFile: null,\n };\n if (!raw) return empty;\n\n if (!raw.startsWith(\"{\")) {\n return { ...empty, accessToken: raw };\n }\n\n try {\n const parsed = JSON.parse(raw) as {\n accessToken?: string;\n refreshToken?: string;\n expiresAt?: number;\n clientId?: string;\n clientSecret?: string;\n serviceAccountFile?: string;\n };\n return {\n accessToken: parsed.accessToken ?? \"\",\n refreshToken: parsed.refreshToken ?? null,\n expiresAtMs: parsed.expiresAt ?? null,\n clientId: parsed.clientId ?? null,\n clientSecret: parsed.clientSecret ?? null,\n serviceAccountFile: parsed.serviceAccountFile ?? null,\n };\n } catch (err) {\n // Looked like a JSON bundle but failed to parse — most likely a truncated\n // credential. Falling back silently lets rclone fail later with an opaque\n // 401; surface a warning so misconfiguration is detectable in the logs.\n log?.warn(\"auth blob starts with '{' but is not valid JSON — treating as raw token\", {\n error: err instanceof Error ? err.message : String(err),\n });\n return { ...empty, accessToken: raw };\n }\n}\n","/**\n * LocalConnector — passthrough to a local directory.\n * Copies (or symlinks) a source directory into the mount point.\n */\n\nimport { cpSync, existsSync, mkdirSync } from \"node:fs\";\nimport { resolve } from \"node:path\";\nimport type {\n ConnectContext,\n ConnectorChangeEvent,\n ConnectorDeclaration,\n ConnectorHandle,\n FilesystemFace,\n SyncOptions,\n SyncResult,\n WatchHandle,\n WatchOptions,\n} from \"@skaile/workspaces/connectors\";\nimport { AbstractConnector, createFsWatcher } from \"@skaile/workspaces/connectors\";\n\ninterface LocalState {\n /** Resolved absolute path to the source directory. */\n sourceDir: string;\n}\n\n/**\n * Filesystem-face connector for local filesystem directories — copies the source directory\n * into the mount target on connect and syncs on demand.\n * No external dependencies; ideal for development and local file access.\n * @docLink packages/factory-assets/concepts#local-connector\n */\nexport class LocalConnector extends AbstractConnector {\n readonly name = \"local\";\n\n readonly filesystem: FilesystemFace = {\n sync: (handle: ConnectorHandle, options?: SyncOptions): Promise<SyncResult> => {\n return this._sync(handle, options);\n },\n };\n\n async connect(declaration: ConnectorDeclaration, ctx: ConnectContext): Promise<ConnectorHandle> {\n const targetDir = ctx.mountTarget;\n if (!targetDir) {\n throw new Error(\"LocalConnector requires ctx.mountTarget to be set by the manager\");\n }\n\n const started = Date.now();\n const source = declaration.mount?.source ?? \"\";\n this.log.info(\"mount start\", { source, targetDir });\n const sourceDir = resolve(String(source));\n if (!existsSync(sourceDir)) {\n this.log.error(\"connect failed: source path does not exist\", undefined, {\n sourceDir,\n });\n throw new Error(`Local source path does not exist: ${sourceDir}`);\n }\n\n mkdirSync(targetDir, { recursive: true });\n\n // Copy source to target (skip if same path or target inside source)\n const src = resolve(sourceDir);\n const tgt = resolve(targetDir);\n if (src !== tgt && !tgt.startsWith(`${src}/`)) {\n cpSync(src, tgt, { recursive: true });\n }\n\n this.log.info(\"mount ok\", { targetDir, durationMs: Date.now() - started });\n return this.makeHandle(declaration, { sourceDir } satisfies LocalState, targetDir);\n }\n\n async disconnect(_handle: ConnectorHandle): Promise<void> {\n this.log.info(\"unmount\");\n // No-op for local filesystem — don't delete the mount directory\n }\n\n private async _sync(handle: ConnectorHandle, _options?: SyncOptions): Promise<SyncResult> {\n this.log.debug(\"sync start\");\n const { sourceDir } = handle.state as LocalState;\n const src = resolve(sourceDir);\n const tgt = resolve(handle.mountPath!);\n\n if (src === tgt || tgt.startsWith(`${src}/`)) {\n this.log.debug(\"sync ok (no-op: source equals target)\");\n return { filesWritten: 0, filesDeleted: 0, bytesTransferred: 0 };\n }\n\n mkdirSync(handle.mountPath!, { recursive: true });\n cpSync(src, handle.mountPath!, { recursive: true });\n\n this.log.debug(\"sync ok\");\n return { filesWritten: 0, filesDeleted: 0, bytesTransferred: 0 };\n }\n\n override watch(\n handle: ConnectorHandle,\n callback: (event: ConnectorChangeEvent) => void,\n options?: WatchOptions,\n ): WatchHandle {\n let fsWatcher: WatchHandle | null = null;\n let closed = false;\n\n createFsWatcher(handle.mountPath!, callback, options)\n .then((w) => {\n // close() may have already run before creation resolved — dispose\n // immediately so the late watcher does not leak.\n if (closed) void w.close();\n else fsWatcher = w;\n })\n .catch((err) => {\n this.log.warn(\"watcher creation failed\", {\n error: err instanceof Error ? err.message : String(err),\n });\n });\n\n return {\n close: async () => {\n closed = true;\n await fsWatcher?.close();\n },\n };\n }\n}\n\n/**\n * Creates a new LocalConnector instance.\n * @returns Configured LocalConnector ready to be registered in the connector registry.\n * @docLink packages/factory-assets/api-reference#local-connector-factory\n */\nexport function createConnector(): LocalConnector {\n return new LocalConnector();\n}\n","/**\n * MattermostConnector — connect to Mattermost via REST API v4.\n *\n * Auth: env:MM_BOT_TOKEN or inline bot token.\n * No npm peer dependencies — uses native fetch + WebSocket (Bun builtins).\n */\n\nimport type {\n ConnectContext,\n ConnectorContent,\n ConnectorDeclaration,\n ConnectorFieldSpec,\n ConnectorHandle,\n OperationDescriptor,\n RuntimeSkillDescriptor,\n ToolFace,\n} from \"@skaile/workspaces/connectors\";\nimport { AbstractConnector } from \"@skaile/workspaces/connectors\";\n\ninterface MattermostState {\n url: string;\n token: string;\n channelFilter: Set<string>;\n botUserId: string;\n}\n\n/**\n * Connector for Mattermost — reads and posts messages via the REST API v4.\n * No npm peer dependencies; uses native fetch and Bun WebSocket. Authenticates with a bot token.\n * @docLink packages/factory-assets/concepts#mattermost-connector\n */\nexport class MattermostConnector extends AbstractConnector {\n readonly name = \"mattermost\";\n\n tools: ToolFace;\n\n constructor() {\n super();\n this.tools = {\n read: (handle, path) => this._read(handle, path),\n write: (handle, path, content) => this._write(handle, path, content),\n describeOperations: (handle) => this._describeOperations(handle),\n executeOp: (handle, operation, args) => this._executeOp(handle, operation, args),\n describeSkill: (handle, declaration) => this._describeSkill(handle, declaration),\n };\n }\n\n describeFields(): ConnectorFieldSpec[] {\n return [\n {\n key: \"url\",\n label: \"Server URL\",\n description: \"Mattermost server URL (e.g. https://chat.example.com)\",\n type: \"url\",\n required: true,\n sensitive: false,\n group: \"Connection\",\n example: \"https://chat.example.com\",\n },\n {\n key: \"token\",\n label: \"Bot Token\",\n description: \"Bot user access token from Mattermost\",\n type: \"api-key\",\n required: true,\n sensitive: true,\n group: \"Authentication\",\n },\n {\n key: \"channels\",\n label: \"Channel Filter\",\n description: \"Comma-separated channel IDs to restrict operations to.\",\n type: \"text\",\n required: false,\n sensitive: false,\n group: \"Options\",\n },\n ];\n }\n\n async connect(declaration: ConnectorDeclaration, ctx: ConnectContext): Promise<ConnectorHandle> {\n const url = (ctx.resolvedFields?.url ?? String(declaration.options?.url ?? \"\")).replace(\n /\\/$/,\n \"\",\n );\n const token = ctx.resolvedFields?.token ?? ctx.secrets?.resolve(declaration.auth ?? \"\") ?? \"\";\n const channelsRaw = ctx.resolvedFields?.channels ?? String(declaration.options?.channels ?? \"\");\n\n if (!url) throw new Error(\"MattermostConnector requires a server URL\");\n if (!token) throw new Error(\"MattermostConnector requires a bot token\");\n\n this.log.info(\"connect start\", { url });\n const channelFilter = new Set(\n channelsRaw\n .split(\",\")\n .map((s) => s.trim())\n .filter(Boolean),\n );\n try {\n const me = await this._apiGet(url, token, \"/api/v4/users/me\");\n const botUserId = String((me as Record<string, unknown>).id ?? \"\");\n if (!botUserId) throw new Error(\"MattermostConnector: failed to authenticate\");\n\n this.log.info(\"connect ok\", { url, botUserId });\n return this.makeHandle(declaration, {\n url,\n token,\n channelFilter,\n botUserId,\n } satisfies MattermostState);\n } catch (err) {\n this.log.error(\"connect failed\", err, { url });\n throw err;\n }\n }\n\n async disconnect(handle: ConnectorHandle): Promise<void> {\n this.log.info(\"disconnect\");\n // No network teardown required — token is stateless.\n handle.status = \"disconnected\";\n }\n\n // ── Tool face methods (private, wired in constructor) ─────────────────────\n\n private async _read(handle: ConnectorHandle, path: string): Promise<ConnectorContent | null> {\n const state = handle.state as MattermostState;\n try {\n const post = (await this._apiGet(state.url, state.token, `/api/v4/posts/${path}`)) as Record<\n string,\n unknown\n >;\n this._assertChannelAccess(String(post.channel_id ?? \"\"), state.channelFilter);\n return { data: JSON.stringify(post, null, 2), contentType: \"application/json\" };\n } catch {\n return null;\n }\n }\n\n private async _write(\n handle: ConnectorHandle,\n path: string,\n content: ConnectorContent,\n ): Promise<void> {\n if (handle.access === \"read-only\")\n throw new Error(\"MattermostConnector: write denied — read-only\");\n const state = handle.state as MattermostState;\n const message = typeof content === \"string\" ? content : String(content.data ?? \"\");\n await this._apiPut(state.url, state.token, `/api/v4/posts/${path}`, { id: path, message });\n this.emitChange?.({ path, action: \"edit\", source: \"operation\" });\n }\n\n private _describeSkill(\n handle: ConnectorHandle,\n declaration: ConnectorDeclaration,\n ): RuntimeSkillDescriptor {\n const state = handle.state as MattermostState;\n const channelCount = state.channelFilter.size;\n const scope = channelCount > 0 ? `${channelCount} channel(s)` : \"all channels\";\n return {\n id: declaration.id,\n name: `Mattermost — ${scope}`,\n description: `Read and write messages in Mattermost (${scope})`,\n category: \"messaging\",\n access: declaration.access,\n toolNames:\n declaration.access === \"read-write\"\n ? [\n \"list_channels\",\n \"get_channel\",\n \"list_posts\",\n \"get_thread\",\n \"create_post\",\n \"reply_to_thread\",\n \"update_post\",\n \"search_posts\",\n \"get_user\",\n ]\n : [\n \"list_channels\",\n \"get_channel\",\n \"list_posts\",\n \"get_thread\",\n \"search_posts\",\n \"get_user\",\n ],\n };\n }\n\n private _describeOperations(handle: ConnectorHandle): OperationDescriptor[] {\n const ops: OperationDescriptor[] = [\n {\n name: \"list_channels\",\n description: \"List channels the bot has access to\",\n accessLevel: \"read\",\n args: [\n { name: \"team_id\", type: \"string\", required: false, description: \"Team ID\" },\n {\n name: \"limit\",\n type: \"number\",\n required: false,\n description: \"Max results (default: 50)\",\n },\n ],\n },\n {\n name: \"get_channel\",\n description: \"Get channel details by ID\",\n accessLevel: \"read\",\n args: [{ name: \"channel_id\", type: \"string\", required: true, description: \"Channel ID\" }],\n },\n {\n name: \"list_posts\",\n description: \"List recent posts in a channel\",\n accessLevel: \"read\",\n args: [\n { name: \"channel_id\", type: \"string\", required: true, description: \"Channel ID\" },\n {\n name: \"limit\",\n type: \"number\",\n required: false,\n description: \"Max results (default: 30)\",\n },\n {\n name: \"before\",\n type: \"string\",\n required: false,\n description: \"Post ID to paginate before\",\n },\n ],\n },\n {\n name: \"get_thread\",\n description: \"Get all posts in a thread\",\n accessLevel: \"read\",\n args: [{ name: \"post_id\", type: \"string\", required: true, description: \"Root post ID\" }],\n },\n {\n name: \"search_posts\",\n description: \"Search posts across channels\",\n accessLevel: \"read\",\n args: [\n { name: \"terms\", type: \"string\", required: true, description: \"Search terms\" },\n { name: \"team_id\", type: \"string\", required: false, description: \"Scope to a team\" },\n ],\n },\n {\n name: \"get_user\",\n description: \"Get user details by ID\",\n accessLevel: \"read\",\n args: [{ name: \"user_id\", type: \"string\", required: true, description: \"User ID\" }],\n },\n ];\n\n if (handle.access === \"read-write\") {\n ops.push(\n {\n name: \"create_post\",\n description: \"Post a new message\",\n accessLevel: \"write\",\n args: [\n { name: \"channel_id\", type: \"string\", required: true, description: \"Channel ID\" },\n { name: \"message\", type: \"string\", required: true, description: \"Message content\" },\n ],\n },\n {\n name: \"reply_to_thread\",\n description: \"Reply to a thread\",\n accessLevel: \"write\",\n args: [\n { name: \"channel_id\", type: \"string\", required: true, description: \"Channel ID\" },\n { name: \"root_id\", type: \"string\", required: true, description: \"Root post ID\" },\n { name: \"message\", type: \"string\", required: true, description: \"Reply content\" },\n ],\n },\n {\n name: \"update_post\",\n description: \"Edit an existing post\",\n accessLevel: \"write\",\n args: [\n { name: \"post_id\", type: \"string\", required: true, description: \"Post ID\" },\n { name: \"message\", type: \"string\", required: true, description: \"Updated content\" },\n ],\n },\n );\n }\n\n return ops;\n }\n\n private async _executeOp(\n handle: ConnectorHandle,\n operation: string,\n args: Record<string, unknown>,\n ): Promise<string> {\n const state = handle.state as MattermostState;\n\n switch (operation) {\n case \"list_channels\": {\n const teamId = args.team_id ? String(args.team_id) : undefined;\n const limit = Number(args.limit ?? 50);\n const endpoint = teamId\n ? `/api/v4/users/me/teams/${teamId}/channels?per_page=${limit}`\n : `/api/v4/users/me/channels?per_page=${limit}`;\n const channels = await this._apiGet(state.url, state.token, endpoint);\n return JSON.stringify(\n this._filterChannels(channels as unknown[], state.channelFilter),\n null,\n 2,\n );\n }\n case \"get_channel\": {\n this._assertChannelAccess(String(args.channel_id), state.channelFilter);\n return JSON.stringify(\n await this._apiGet(state.url, state.token, `/api/v4/channels/${args.channel_id}`),\n null,\n 2,\n );\n }\n case \"list_posts\": {\n const cid = String(args.channel_id);\n this._assertChannelAccess(cid, state.channelFilter);\n const limit = Number(args.limit ?? 30);\n const before = args.before ? `&before=${args.before}` : \"\";\n return JSON.stringify(\n await this._apiGet(\n state.url,\n state.token,\n `/api/v4/channels/${cid}/posts?per_page=${limit}${before}`,\n ),\n null,\n 2,\n );\n }\n case \"get_thread\": {\n const postId = String(args.post_id);\n // Resolve the post's channel first so the thread can't bypass the filter.\n const post = (await this._apiGet(\n state.url,\n state.token,\n `/api/v4/posts/${postId}`,\n )) as Record<string, unknown>;\n this._assertChannelAccess(String(post.channel_id ?? \"\"), state.channelFilter);\n return JSON.stringify(\n await this._apiGet(state.url, state.token, `/api/v4/posts/${postId}/thread`),\n null,\n 2,\n );\n }\n case \"search_posts\": {\n const body: Record<string, unknown> = { terms: String(args.terms), is_or_search: false };\n if (args.team_id) body.team_id = String(args.team_id);\n return JSON.stringify(\n await this._apiPost(state.url, state.token, \"/api/v4/posts/search\", body),\n null,\n 2,\n );\n }\n case \"get_user\":\n // Not channel-addressed — no channel to scope against, so the filter\n // does not apply here.\n return JSON.stringify(\n await this._apiGet(state.url, state.token, `/api/v4/users/${args.user_id}`),\n null,\n 2,\n );\n case \"create_post\": {\n this._assertWriteAccess(handle);\n const cid = String(args.channel_id);\n this._assertChannelAccess(cid, state.channelFilter);\n const post = await this._apiPost(state.url, state.token, \"/api/v4/posts\", {\n channel_id: cid,\n message: String(args.message),\n });\n const postId = String((post as Record<string, unknown>).id ?? \"\");\n this.emitChange?.({\n path: `channels/${cid}/posts/${postId}`,\n action: \"create\",\n source: \"operation\",\n });\n return JSON.stringify(post, null, 2);\n }\n case \"reply_to_thread\": {\n this._assertWriteAccess(handle);\n const cid = String(args.channel_id);\n this._assertChannelAccess(cid, state.channelFilter);\n const post = await this._apiPost(state.url, state.token, \"/api/v4/posts\", {\n channel_id: cid,\n root_id: String(args.root_id),\n message: String(args.message),\n });\n const postId = String((post as Record<string, unknown>).id ?? \"\");\n this.emitChange?.({\n path: `channels/${cid}/posts/${postId}`,\n action: \"create\",\n source: \"operation\",\n });\n return JSON.stringify(post, null, 2);\n }\n case \"update_post\": {\n this._assertWriteAccess(handle);\n const pid = String(args.post_id);\n const updated = await this._apiPut(state.url, state.token, `/api/v4/posts/${pid}`, {\n id: pid,\n message: String(args.message),\n });\n this.emitChange?.({ path: `posts/${pid}`, action: \"edit\", source: \"operation\" });\n return JSON.stringify(updated, null, 2);\n }\n default:\n throw new Error(`MattermostConnector has no operation \"${operation}\"`);\n }\n }\n\n private _assertWriteAccess(handle: ConnectorHandle): void {\n if (handle.access === \"read-only\")\n throw new Error(\"MattermostConnector: operation denied — read-only\");\n }\n\n private _assertChannelAccess(channelId: string, filter: Set<string>): void {\n if (filter.size > 0 && !filter.has(channelId))\n throw new Error(`MattermostConnector: channel \"${channelId}\" not in filter`);\n }\n\n private _filterChannels(channels: unknown[], filter: Set<string>): unknown[] {\n if (filter.size === 0) return channels;\n return channels.filter((ch) => {\n const id = (ch as Record<string, unknown>).id;\n return typeof id === \"string\" && filter.has(id);\n });\n }\n\n private async _apiGet(baseUrl: string, token: string, path: string): Promise<unknown> {\n const res = await fetch(baseUrl + path, { headers: { Authorization: `Bearer ${token}` } });\n if (!res.ok) {\n const body = await res.text();\n this.log.warn(\"REST error\", { method: \"GET\", endpoint: path, status: res.status });\n throw new Error(`Mattermost GET ${path}: ${res.status} ${body}`);\n }\n return res.json();\n }\n\n private async _apiPost(\n baseUrl: string,\n token: string,\n path: string,\n body: unknown,\n ): Promise<unknown> {\n const res = await fetch(baseUrl + path, {\n method: \"POST\",\n headers: { Authorization: `Bearer ${token}`, \"Content-Type\": \"application/json\" },\n body: JSON.stringify(body),\n });\n if (!res.ok) throw new Error(`Mattermost POST ${path}: ${res.status} ${await res.text()}`);\n return res.json();\n }\n\n private async _apiPut(\n baseUrl: string,\n token: string,\n path: string,\n body: unknown,\n ): Promise<unknown> {\n const res = await fetch(baseUrl + path, {\n method: \"PUT\",\n headers: { Authorization: `Bearer ${token}`, \"Content-Type\": \"application/json\" },\n body: JSON.stringify(body),\n });\n if (!res.ok) throw new Error(`Mattermost PUT ${path}: ${res.status} ${await res.text()}`);\n return res.json();\n }\n}\n\n/**\n * Creates a new MattermostConnector instance.\n * @returns Configured MattermostConnector ready to be registered in the connector registry.\n * @docLink packages/factory-assets/api-reference#mattermost-connector-factory\n */\nexport function createConnector(): MattermostConnector {\n return new MattermostConnector();\n}\n","/**\n * MemoryConnector — in-process key-value store.\n * Not mountable. Used for scratch state, agent-to-agent coordination, config.\n */\n\nimport type {\n ConnectContext,\n ConnectorContent,\n ConnectorDeclaration,\n ConnectorEntry,\n ConnectorHandle,\n ListOptions,\n OperationDescriptor,\n SearchOptions,\n SearchResult,\n ToolFace,\n} from \"@skaile/workspaces/connectors\";\nimport { AbstractConnector } from \"@skaile/workspaces/connectors\";\n\ninterface MemoryState {\n store: Map<string, string>;\n namespace: string;\n}\n\n/**\n * Connector for an in-process key-value store. Useful for scratch state, agent coordination, and config.\n * No external dependencies — the store lives entirely in process memory and is cleared on disconnect.\n * @docLink packages/factory-assets/concepts#memory-connector\n */\nexport class MemoryConnector extends AbstractConnector {\n readonly name = \"memory\";\n\n tools: ToolFace;\n\n constructor() {\n super();\n this.tools = {\n read: (handle, path) => this._read(handle, path),\n write: (handle, path, content) => this._write(handle, path, content),\n delete: (handle, path) => this._delete(handle, path),\n list: (handle, path, options) => this._list(handle, path, options),\n search: (handle, query, options) => this._search(handle, query, options),\n describeOperations: (handle) => this._describeOperations(handle),\n executeOp: (handle, operation, args) => this._executeOp(handle, operation, args),\n };\n }\n\n async connect(declaration: ConnectorDeclaration, ctx: ConnectContext): Promise<ConnectorHandle> {\n this.log.info(\"connect\", { id: declaration.id });\n const namespace = String(declaration.options?.namespace ?? declaration.id);\n return this.makeHandle(declaration, { store: new Map(), namespace } satisfies MemoryState);\n }\n\n async disconnect(handle: ConnectorHandle): Promise<void> {\n this.log.info(\"disconnect\");\n (handle.state as MemoryState).store.clear();\n handle.status = \"disconnected\";\n }\n\n private store(handle: ConnectorHandle): Map<string, string> {\n return (handle.state as MemoryState).store;\n }\n\n private async _read(handle: ConnectorHandle, path: string): Promise<ConnectorContent | null> {\n const value = this.store(handle).get(path);\n if (value === undefined) return null;\n return { data: value, contentType: \"application/json\" };\n }\n\n private async _write(\n handle: ConnectorHandle,\n path: string,\n content: ConnectorContent,\n ): Promise<void> {\n const isNew = !this.store(handle).has(path);\n this.store(handle).set(\n path,\n typeof content.data === \"string\" ? content.data : content.data.toString(\"utf-8\"),\n );\n this.emitChange?.({ path, action: isNew ? \"create\" : \"edit\", source: \"operation\" });\n }\n\n private async _delete(handle: ConnectorHandle, path: string): Promise<boolean> {\n const deleted = this.store(handle).delete(path);\n if (deleted) this.emitChange?.({ path, action: \"delete\", source: \"operation\" });\n return deleted;\n }\n\n private async _list(\n handle: ConnectorHandle,\n path?: string,\n options?: ListOptions,\n ): Promise<ConnectorEntry[]> {\n const prefix = path ?? \"\";\n const entries: ConnectorEntry[] = [];\n for (const key of this.store(handle).keys()) {\n if (prefix && !key.startsWith(prefix)) continue;\n if (options?.glob && !matchGlob(key, options.glob)) continue;\n if (options?.limit && entries.length >= options.limit) break;\n entries.push({ name: key, path: key, type: \"key\" });\n }\n return entries;\n }\n\n private async _search(\n handle: ConnectorHandle,\n query: string,\n options?: SearchOptions,\n ): Promise<SearchResult[]> {\n const results: SearchResult[] = [];\n for (const [key, value] of this.store(handle)) {\n if (options?.maxResults && results.length >= options.maxResults) break;\n if (key.includes(query) || value.includes(query)) {\n results.push({ path: key, snippet: value.slice(0, 200) });\n }\n }\n return results;\n }\n\n private _describeOperations(_handle: ConnectorHandle): OperationDescriptor[] {\n return [\n {\n name: \"get\",\n description: \"Get value by key\",\n accessLevel: \"read\",\n args: [{ name: \"key\", type: \"string\", required: true, description: \"Key name\" }],\n examples: ['get --key \"config:theme\"'],\n },\n {\n name: \"set\",\n description: \"Set a key-value pair\",\n accessLevel: \"write\",\n args: [\n { name: \"key\", type: \"string\", required: true, description: \"Key name\" },\n {\n name: \"value\",\n type: \"string\",\n required: true,\n description: \"Value (stored as string)\",\n },\n ],\n examples: ['set --key \"status\" --value \"running\"'],\n },\n {\n name: \"keys\",\n description: \"List all keys matching a pattern\",\n accessLevel: \"read\",\n args: [\n {\n name: \"pattern\",\n type: \"string\",\n required: false,\n description: \"Glob pattern (default: all)\",\n },\n ],\n },\n {\n name: \"del\",\n description: \"Delete a key\",\n accessLevel: \"write\",\n args: [{ name: \"key\", type: \"string\", required: true, description: \"Key to delete\" }],\n },\n ];\n }\n\n private async _executeOp(\n handle: ConnectorHandle,\n operation: string,\n args: Record<string, unknown>,\n ): Promise<string> {\n switch (operation) {\n case \"get\": {\n const key = String(args.key ?? \"\");\n const value = this.store(handle).get(key);\n return value ?? \"\";\n }\n case \"set\": {\n const key = String(args.key ?? \"\");\n const value = String(args.value ?? \"\");\n const isNew = !this.store(handle).has(key);\n this.store(handle).set(key, value);\n this.emitChange?.({ path: key, action: isNew ? \"create\" : \"edit\", source: \"operation\" });\n return \"OK\";\n }\n case \"keys\": {\n const pattern = args.pattern ? String(args.pattern) : undefined;\n const keys = [...this.store(handle).keys()];\n const filtered = pattern ? keys.filter((k) => matchGlob(k, pattern)) : keys;\n return JSON.stringify(filtered);\n }\n case \"del\": {\n const key = String(args.key ?? \"\");\n const deleted = this.store(handle).delete(key);\n if (deleted) this.emitChange?.({ path: key, action: \"delete\", source: \"operation\" });\n return deleted ? \"Deleted\" : \"Not found\";\n }\n default:\n throw new Error(`Memory adapter has no operation: ${operation}`);\n }\n }\n}\n\nfunction matchGlob(str: string, pattern: string): boolean {\n // Escape regex metacharacters first, then translate the glob wildcards so a\n // pattern like \"a.b*\" matches literally rather than as a regex.\n const escaped = pattern.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n const regex = new RegExp(`^${escaped.replace(/\\\\\\*/g, \".*\").replace(/\\\\\\?/g, \".\")}$`);\n return regex.test(str);\n}\n\n/**\n * Creates a new MemoryConnector instance.\n * @returns Configured MemoryConnector ready to be registered in the connector registry.\n * @docLink packages/factory-assets/api-reference#memory-connector-factory\n */\nexport function createConnector(): MemoryConnector {\n return new MemoryConnector();\n}\n","/**\n * MinIOConnector — S3-compatible object storage via MinIO.\n *\n * Auth: access-key + secret-key resolved via SecretProviderChain.\n * Peer dependency: minio (lazy-loaded).\n */\n\nimport type {\n ConnectContext,\n ConnectorContent,\n ConnectorDeclaration,\n ConnectorEntry,\n ConnectorFieldSpec,\n ConnectorHandle,\n OperationDescriptor,\n RuntimeSkillDescriptor,\n ToolFace,\n} from \"@skaile/workspaces/connectors\";\nimport { AbstractConnector } from \"@skaile/workspaces/connectors\";\n\ninterface MinIOState {\n client: any; // minio.Client\n bucket: string;\n endpoint: string;\n}\n\n/**\n * Connector for MinIO and S3-compatible object storage.\n * Provides list, get, put, delete, and presign operations against a single bucket. Requires the `minio` optional peer dependency.\n * @docLink packages/factory-assets/concepts#minio-connector\n */\nexport class MinIOConnector extends AbstractConnector {\n readonly name = \"minio\";\n\n tools: ToolFace;\n\n constructor() {\n super();\n this.tools = {\n list: (handle, path) => this._list(handle, path),\n read: (handle, path) => this._read(handle, path),\n describeOperations: (handle) => this._describeOperations(handle),\n executeOp: (handle, operation, args) => this._executeOp(handle, operation, args),\n describeSkill: (handle, declaration) => this._describeSkill(handle, declaration),\n };\n }\n\n describeFields(): ConnectorFieldSpec[] {\n return [\n {\n key: \"endpoint\",\n label: \"MinIO Endpoint\",\n type: \"url\",\n required: true,\n sensitive: false,\n group: \"Connection\",\n },\n {\n key: \"bucket\",\n label: \"Bucket\",\n type: \"text\",\n required: true,\n sensitive: false,\n group: \"Connection\",\n },\n {\n key: \"region\",\n label: \"Region\",\n type: \"text\",\n required: false,\n sensitive: false,\n group: \"Connection\",\n default: \"us-east-1\",\n },\n {\n key: \"use-ssl\",\n label: \"Use SSL\",\n type: \"boolean\",\n required: false,\n sensitive: false,\n group: \"Connection\",\n default: \"true\",\n },\n {\n key: \"access-key\",\n label: \"Access Key\",\n type: \"api-key\",\n required: true,\n sensitive: true,\n group: \"Authentication\",\n },\n {\n key: \"secret-key\",\n label: \"Secret Key\",\n type: \"password\",\n required: true,\n sensitive: true,\n group: \"Authentication\",\n },\n ];\n }\n\n private _describeSkill(\n _handle: ConnectorHandle,\n declaration: ConnectorDeclaration,\n ): RuntimeSkillDescriptor {\n const endpoint = String(declaration.options?.endpoint ?? \"minio\");\n const bucket = String(declaration.options?.bucket ?? \"unknown\");\n return {\n id: declaration.id,\n name: `MinIO — ${bucket}`,\n description: `Object storage at ${endpoint}, bucket: ${bucket}`,\n category: \"storage\",\n access: declaration.access,\n toolNames: [\"list_objects\", \"get_object\", \"put_object\", \"delete_object\", \"presign\"],\n };\n }\n\n async connect(declaration: ConnectorDeclaration, ctx: ConnectContext): Promise<ConnectorHandle> {\n const endpoint = ctx.resolvedFields?.endpoint ?? String(declaration.options?.endpoint ?? \"\");\n const bucket = ctx.resolvedFields?.bucket ?? String(declaration.options?.bucket ?? \"\");\n const accessKey =\n ctx.resolvedFields?.[\"access-key\"] ??\n ctx.secrets?.resolve((declaration.options?.[\"access-key\"] as string | undefined) ?? \"\") ??\n \"\";\n const secretKey =\n ctx.resolvedFields?.[\"secret-key\"] ??\n ctx.secrets?.resolve((declaration.options?.[\"secret-key\"] as string | undefined) ?? \"\") ??\n \"\";\n const useSSL =\n (ctx.resolvedFields?.[\"use-ssl\"] ?? declaration.options?.[\"use-ssl\"] ?? \"true\") !== \"false\";\n\n if (!endpoint) throw new Error(\"MinIOAdapter requires an endpoint\");\n if (!bucket) throw new Error(\"MinIOAdapter requires a bucket\");\n if (!accessKey || !secretKey)\n throw new Error(\"MinIOAdapter requires access-key and secret-key\");\n\n this.log.info(\"connect start\", { endpoint, bucket });\n try {\n const minioMod = \"minio\";\n const { Client } = (await import(/* @vite-ignore */ minioMod)) as any;\n const url = new URL(endpoint);\n const client = new Client({\n endPoint: url.hostname,\n port: url.port ? Number(url.port) : useSSL ? 443 : 80,\n useSSL,\n accessKey,\n secretKey,\n });\n\n await client.bucketExists(bucket);\n this.log.info(\"connect ok\", { endpoint, bucket });\n\n return this.makeHandle(declaration, { client, bucket, endpoint } as MinIOState);\n } catch (err) {\n this.log.error(\"connect failed\", err, { endpoint, bucket });\n throw err;\n }\n }\n\n async disconnect(handle: ConnectorHandle): Promise<void> {\n this.log.info(\"disconnect\");\n handle.status = \"disconnected\";\n }\n\n private _describeOperations(handle: ConnectorHandle): OperationDescriptor[] {\n const ops: OperationDescriptor[] = [\n {\n name: \"list_objects\",\n description: \"List objects in the bucket\",\n accessLevel: \"read\",\n args: [\n {\n name: \"prefix\",\n type: \"string\",\n required: false,\n description: \"Object key prefix filter\",\n },\n {\n name: \"recursive\",\n type: \"boolean\",\n required: false,\n description: \"List recursively (default: false)\",\n },\n ],\n },\n {\n name: \"get_object\",\n description: \"Download an object and return its content\",\n accessLevel: \"read\",\n args: [{ name: \"key\", type: \"string\", required: true, description: \"Object key\" }],\n },\n {\n name: \"presign\",\n description: \"Generate a pre-signed URL for temporary access\",\n accessLevel: \"read\",\n args: [\n { name: \"key\", type: \"string\", required: true, description: \"Object key\" },\n {\n name: \"expiry\",\n type: \"number\",\n required: false,\n description: \"Expiry in seconds (default: 3600)\",\n },\n ],\n },\n ];\n\n if (handle.access === \"read-write\") {\n ops.push(\n {\n name: \"put_object\",\n description: \"Upload content as an object\",\n accessLevel: \"write\",\n args: [\n { name: \"key\", type: \"string\", required: true, description: \"Object key\" },\n { name: \"content\", type: \"string\", required: true, description: \"Object content\" },\n {\n name: \"content-type\",\n type: \"string\",\n required: false,\n description: \"MIME type (default: text/plain)\",\n },\n ],\n },\n {\n name: \"delete_object\",\n description: \"Delete an object from the bucket\",\n accessLevel: \"write\",\n args: [{ name: \"key\", type: \"string\", required: true, description: \"Object key\" }],\n },\n );\n }\n\n return ops;\n }\n\n private async _list(\n handle: ConnectorHandle,\n path?: string,\n recursive = false,\n ): Promise<ConnectorEntry[]> {\n const { client, bucket } = handle.state as MinIOState;\n const entries: ConnectorEntry[] = [];\n const stream = client.listObjects(bucket, path ?? \"\", recursive);\n return new Promise((resolve, reject) => {\n stream.on(\"data\", (obj: any) => {\n entries.push({\n name: obj.name,\n path: obj.name,\n type: \"file\",\n size: obj.size,\n modifiedAt: obj.lastModified,\n });\n });\n stream.on(\"end\", () => resolve(entries));\n stream.on(\"error\", reject);\n });\n }\n\n private async _read(handle: ConnectorHandle, path: string): Promise<ConnectorContent | null> {\n const { client, bucket } = handle.state as MinIOState;\n const chunks: Buffer[] = [];\n const stream = await client.getObject(bucket, path);\n return new Promise((resolve, reject) => {\n stream.on(\"data\", (chunk: Buffer) => chunks.push(chunk));\n stream.on(\"end\", () => resolve({ data: Buffer.concat(chunks).toString() }));\n stream.on(\"error\", reject);\n });\n }\n\n private async _executeOp(\n handle: ConnectorHandle,\n operation: string,\n args: Record<string, unknown>,\n ): Promise<string> {\n const { client, bucket } = handle.state as MinIOState;\n\n switch (operation) {\n case \"list_objects\":\n return JSON.stringify(\n await this._list(handle, String(args.prefix ?? \"\"), Boolean(args.recursive)),\n null,\n 2,\n );\n case \"get_object\": {\n const content = await this._read(handle, String(args.key));\n return content?.data?.toString() ?? \"(empty)\";\n }\n case \"put_object\": {\n const content = String(args.content ?? \"\");\n const contentType = String(args[\"content-type\"] ?? \"text/plain\");\n const buf = Buffer.from(content);\n await client.putObject(bucket, String(args.key), buf, buf.length, {\n \"Content-Type\": contentType,\n });\n return \"Object uploaded.\";\n }\n case \"delete_object\": {\n await client.removeObject(bucket, String(args.key));\n return \"Object deleted.\";\n }\n case \"presign\":\n return await client.presignedGetObject(\n bucket,\n String(args.key),\n Number(args.expiry ?? 3600),\n );\n default:\n throw new Error(`MinIOAdapter has no operation \"${operation}\"`);\n }\n }\n}\n\n/**\n * Creates a new MinIOConnector instance.\n * @returns Configured MinIOConnector ready to be registered in the connector registry.\n * @docLink packages/factory-assets/api-reference#minio-connector-factory\n */\nexport function createConnector(): MinIOConnector {\n return new MinIOConnector();\n}\n","/**\n * PostgresConnector — PostgreSQL database resource.\n * Not mountable (but supports snapshot sync to dump schema + sample data).\n * Custom operations: query, schema, execute.\n *\n * Requires `pg` as an optional peer dependency.\n */\n\nimport type {\n ConnectContext,\n ConnectorContent,\n ConnectorDeclaration,\n ConnectorEntry,\n ConnectorFieldSpec,\n ConnectorHandle,\n ListOptions,\n OperationDescriptor,\n RuntimeSkillDescriptor,\n SearchOptions,\n SearchResult,\n ToolFace,\n} from \"@skaile/workspaces/connectors\";\nimport { AbstractConnector } from \"@skaile/workspaces/connectors\";\n\ninterface PgState {\n pool: any; // pg.Pool\n dsn: string;\n}\n\n/** Escape an identifier for safe interpolation inside double quotes. */\nfunction quoteIdent(ident: string): string {\n return ident.replace(/\"/g, '\"\"');\n}\n\n/**\n * Connector for PostgreSQL databases — provides query, schema inspection, and execute operations.\n * Also supports snapshot sync that dumps schema and sample data to JSON files. Requires the `pg` optional peer dependency.\n * @docLink packages/factory-assets/concepts#postgres-connector\n */\nexport class PostgresConnector extends AbstractConnector {\n readonly name = \"postgres\";\n\n tools: ToolFace;\n\n constructor() {\n super();\n this.tools = {\n read: (handle, path) => this._read(handle, path),\n list: (handle, path, options) => this._list(handle, path, options),\n search: (handle, query, options) => this._search(handle, query, options),\n describeOperations: (handle) => this._describeOperations(handle),\n executeOp: (handle, operation, args) => this._executeOp(handle, operation, args),\n describeSkill: (handle, declaration) => this._describeSkill(handle, declaration),\n };\n }\n\n describeFields(): ConnectorFieldSpec[] {\n return [\n {\n key: \"dsn\",\n label: \"Connection String\",\n description: \"PostgreSQL connection URL (e.g. postgres://user:pass@host/db)\",\n type: \"url\",\n required: true,\n sensitive: true,\n group: \"Authentication\",\n },\n ];\n }\n\n private _describeSkill(\n _handle: ConnectorHandle,\n declaration: ConnectorDeclaration,\n ): RuntimeSkillDescriptor {\n const dsn = String(declaration.options?.dsn ?? \"\");\n let hostLabel = declaration.id;\n try {\n hostLabel = new URL(dsn).hostname;\n } catch {}\n return {\n id: declaration.id,\n name: `PostgreSQL — ${hostLabel}`,\n description: `Query PostgreSQL database at ${hostLabel}`,\n category: \"database\",\n access: declaration.access,\n toolNames:\n declaration.access === \"read-write\" ? [\"query\", \"schema\", \"execute\"] : [\"query\", \"schema\"],\n };\n }\n\n async connect(declaration: ConnectorDeclaration, ctx: ConnectContext): Promise<ConnectorHandle> {\n const started = Date.now();\n let dsn = ctx.resolvedFields?.dsn ?? String(declaration.options?.dsn ?? \"\");\n\n // Backend-mediated: the platform minted the DSN; resolve it via the wrapped\n // mediator (pre-mint initial, real mediator for refresh). Off-disk by design.\n if (!dsn && declaration.auth === \"backend\" && ctx.tokenMediator) {\n const mint = await ctx.tokenMediator({ connectorId: declaration.id, reason: \"initial\" });\n if (mint.ok) dsn = mint.token;\n else\n throw new Error(\n `PostgresAdapter '${declaration.id}': backend credential ${mint.code} — ${mint.message}`,\n );\n }\n\n // Fall back to the secrets chain for env:/pat: refs (non-backend auth).\n if (!dsn) dsn = ctx.secrets?.resolve(declaration.auth ?? \"\") ?? \"\";\n\n if (!dsn) {\n this.log.error(\"connect failed: missing dsn\", undefined);\n throw new Error(\"PostgresAdapter requires auth (connection string) or options.dsn\");\n }\n\n let host = \"(unknown)\";\n try {\n host = new URL(dsn).hostname;\n } catch {}\n this.log.info(\"connect start\", { host });\n\n try {\n const pgPkg = \"pg\";\n const pg = (await import(/* @vite-ignore */ pgPkg)) as any;\n const Pool = pg.default?.Pool ?? pg.Pool;\n const pool = new Pool({ connectionString: dsn });\n\n // Verify connectivity\n const client = await pool.connect();\n client.release();\n\n this.log.info(\"connect ok\", { host, durationMs: Date.now() - started });\n return this.makeHandle(declaration, { pool, dsn } satisfies PgState);\n } catch (err) {\n this.log.error(\"connect failed\", err, { host });\n throw err;\n }\n }\n\n async disconnect(handle: ConnectorHandle): Promise<void> {\n this.log.info(\"disconnect\");\n const { pool } = handle.state as PgState;\n try {\n await pool.end();\n } finally {\n handle.status = \"disconnected\";\n }\n }\n\n private pool(handle: ConnectorHandle): any {\n return (handle.state as PgState).pool;\n }\n\n // Base ops map to table/row access via path convention: <table>/<pk>\n\n private async _read(handle: ConnectorHandle, path: string): Promise<ConnectorContent | null> {\n const parts = path.split(\"/\");\n if (parts.length === 1) {\n // Read table schema\n const table = parts[0]!;\n const result = await this.pool(handle).query(\n `SELECT column_name, data_type, is_nullable, column_default\n FROM information_schema.columns WHERE table_name = $1 ORDER BY ordinal_position`,\n [table],\n );\n if (result.rows.length === 0) return null;\n return { data: JSON.stringify(result.rows, null, 2), contentType: \"application/json\" };\n }\n // Read row by PK: <table>/<pk_value>\n const [table, pk] = parts;\n const result = await this.pool(handle).query(\n `SELECT * FROM \"${quoteIdent(table!)}\" WHERE id = $1 LIMIT 1`,\n [pk],\n );\n if (result.rows.length === 0) return null;\n return { data: JSON.stringify(result.rows[0], null, 2), contentType: \"application/json\" };\n }\n\n private async _list(\n handle: ConnectorHandle,\n path?: string,\n options?: ListOptions,\n ): Promise<ConnectorEntry[]> {\n if (!path) {\n // List tables\n const result = await this.pool(handle).query(\n `SELECT table_name FROM information_schema.tables\n WHERE table_schema = 'public' ORDER BY table_name`,\n );\n return result.rows.map((r: any) => ({\n name: r.table_name,\n path: r.table_name,\n type: \"directory\" as const,\n }));\n }\n // List rows in a table\n const limit = options?.limit ?? 100;\n const result = await this.pool(handle).query(`SELECT * FROM \"${quoteIdent(path)}\" LIMIT $1`, [\n limit,\n ]);\n return result.rows.map((row: any, i: number) => ({\n name: String(row.id ?? i),\n path: `${path}/${row.id ?? i}`,\n type: \"row\" as const,\n }));\n }\n\n private async _search(\n handle: ConnectorHandle,\n query: string,\n options?: SearchOptions,\n ): Promise<SearchResult[]> {\n // Search across all text columns in all tables\n const tables = await this._list(handle);\n const results: SearchResult[] = [];\n const maxResults = options?.maxResults ?? 50;\n\n for (const table of tables) {\n if (results.length >= maxResults) break;\n try {\n const cols = await this.pool(handle).query(\n `SELECT column_name FROM information_schema.columns\n WHERE table_name = $1 AND data_type IN ('text', 'character varying', 'varchar')`,\n [table.name],\n );\n if (cols.rows.length === 0) continue;\n\n const conditions = cols.rows\n .map((c: any) => `\"${quoteIdent(String(c.column_name))}\"::text ILIKE $1`)\n .join(\" OR \");\n const searchResult = await this.pool(handle).query(\n `SELECT * FROM \"${quoteIdent(table.name)}\" WHERE ${conditions} LIMIT $2`,\n [`%${query}%`, maxResults - results.length],\n );\n for (const row of searchResult.rows) {\n results.push({\n path: `${table.name}/${row.id ?? \"?\"}`,\n snippet: JSON.stringify(row).slice(0, 200),\n });\n }\n } catch {\n // Skip tables that error (permissions, etc.)\n }\n }\n return results;\n }\n\n private _describeOperations(handle: ConnectorHandle): OperationDescriptor[] {\n const ops: OperationDescriptor[] = [\n {\n name: \"query\",\n description: \"Execute a read-only SQL query. Returns JSON rows.\",\n accessLevel: \"read\",\n args: [\n { name: \"sql\", type: \"string\", required: true, description: \"SQL SELECT statement\" },\n {\n name: \"params\",\n type: \"json\",\n required: false,\n description: \"Query parameters as JSON array\",\n },\n ],\n examples: [\n 'query --sql \"SELECT id, name FROM users LIMIT 10\"',\n \"query --sql \\\"SELECT * FROM orders WHERE user_id = $1\\\" --params '[42]'\",\n ],\n },\n {\n name: \"schema\",\n description: \"Inspect database schema — tables, columns, types, constraints.\",\n accessLevel: \"read\",\n args: [\n {\n name: \"table\",\n type: \"string\",\n required: false,\n description: \"Specific table (omit for full schema)\",\n },\n ],\n examples: [\"schema\", \"schema --table users\"],\n },\n ];\n\n if (handle.access === \"read-write\") {\n ops.push({\n name: \"execute\",\n description: \"Execute a SQL mutation (INSERT, UPDATE, DELETE). Returns affected row count.\",\n accessLevel: \"write\",\n args: [\n { name: \"sql\", type: \"string\", required: true, description: \"SQL statement\" },\n {\n name: \"params\",\n type: \"json\",\n required: false,\n description: \"Query parameters as JSON array\",\n },\n ],\n examples: [\n \"execute --sql \\\"UPDATE users SET active = true WHERE id = $1\\\" --params '[42]'\",\n ],\n });\n }\n\n return ops;\n }\n\n private async _executeOp(\n handle: ConnectorHandle,\n operation: string,\n args: Record<string, unknown>,\n ): Promise<string> {\n const pool = this.pool(handle);\n\n switch (operation) {\n case \"query\":\n return this._opQuery(pool, args);\n case \"schema\":\n return this._opSchema(pool, args);\n case \"execute\":\n return this._opExecute(pool, args);\n default:\n throw new Error(`PostgresAdapter has no operation: ${operation}`);\n }\n }\n\n /** Parse the params argument shared by the query/execute ops (JSON string or passthrough). */\n private parseParams(params: unknown): unknown {\n return params ? (typeof params === \"string\" ? JSON.parse(params) : params) : [];\n }\n\n private async _opQuery(pool: any, args: Record<string, unknown>): Promise<string> {\n const sql = String(args.sql ?? args._positional ?? \"\");\n if (!sql) return \"Error: sql argument is required\";\n const params = this.parseParams(args.params);\n const queryStart = Date.now();\n try {\n const result = await pool.query(sql, params);\n const ms = Date.now() - queryStart;\n if (ms > 1000) {\n this.log.warn(\"slow query\", { ms, sql: sql.slice(0, 200) });\n }\n return JSON.stringify(result.rows, null, 2);\n } catch (err) {\n this.log.error(\"query failed\", err, { sql: sql.slice(0, 200) });\n throw err;\n }\n }\n\n private async _opSchema(pool: any, args: Record<string, unknown>): Promise<string> {\n const table = args.table ? String(args.table) : undefined;\n if (table) {\n const result = await pool.query(\n `SELECT column_name, data_type, is_nullable, column_default\n FROM information_schema.columns WHERE table_name = $1 ORDER BY ordinal_position`,\n [table],\n );\n return JSON.stringify(result.rows, null, 2);\n }\n // Full schema: tables + row counts\n const tables = await pool.query(\n `SELECT t.table_name,\n (SELECT count(*) FROM information_schema.columns c WHERE c.table_name = t.table_name) as column_count\n FROM information_schema.tables t\n WHERE t.table_schema = 'public' ORDER BY t.table_name`,\n );\n return JSON.stringify(tables.rows, null, 2);\n }\n\n private async _opExecute(pool: any, args: Record<string, unknown>): Promise<string> {\n const sql = String(args.sql ?? args._positional ?? \"\");\n if (!sql) return \"Error: sql argument is required\";\n const params = this.parseParams(args.params);\n const result = await pool.query(sql, params);\n return JSON.stringify({ rowCount: result.rowCount, command: result.command });\n }\n}\n\n/**\n * Creates a new PostgresConnector instance.\n * @returns Configured PostgresConnector ready to be registered in the connector registry.\n * @docLink packages/factory-assets/api-reference#postgres-connector-factory\n */\nexport function createConnector(): PostgresConnector {\n return new PostgresConnector();\n}\n","/**\n * S3Connector — AWS S3 / S3-compatible object storage filesystem-face connector.\n * Mounts by syncing objects to a local directory.\n */\n\nimport { mkdirSync, writeFileSync } from \"node:fs\";\nimport { dirname, join } from \"node:path\";\nimport type {\n ConnectContext,\n ConnectorDeclaration,\n ConnectorHandle,\n FilesystemFace,\n SyncOptions,\n SyncResult,\n} from \"@skaile/workspaces/connectors\";\nimport { AbstractConnector } from \"@skaile/workspaces/connectors\";\n\nconst s3Pkg = \"@aws-sdk/client-s3\";\n\n/**\n * Minimal shape of the AWS S3 SDK module used internally.\n * Declared here so tests can provide a lightweight fake without importing the\n * real (optional) `@aws-sdk/client-s3` package.\n */\nexport interface S3SdkModule {\n S3Client: new (\n config: object,\n ) => {\n send(cmd: object): Promise<any>;\n destroy(): void;\n };\n ListObjectsV2Command: new (input: object) => object;\n GetObjectCommand: new (input: object) => object;\n}\n\ninterface S3State {\n client: InstanceType<S3SdkModule[\"S3Client\"]>;\n bucket: string;\n prefix: string;\n region: string;\n}\n\n/**\n * Filesystem-face connector for AWS S3 and S3-compatible object storage — downloads all\n * objects from a bucket prefix into a local directory on connect and re-downloads on sync.\n * Requires the `@aws-sdk/client-s3` optional peer dependency.\n * @docLink packages/factory-assets/concepts#s3-connector\n */\nexport class S3Connector extends AbstractConnector {\n readonly name = \"s3\";\n\n /** Optional SDK module override — used in tests to avoid importing the real AWS SDK. */\n private _sdkOverride?: S3SdkModule;\n\n constructor(sdkOverride?: S3SdkModule) {\n super();\n this._sdkOverride = sdkOverride;\n }\n\n readonly filesystem: FilesystemFace = {\n sync: (handle: ConnectorHandle, options?: SyncOptions): Promise<SyncResult> => {\n return this._sync(handle, options);\n },\n };\n\n private async _loadSdk(): Promise<S3SdkModule> {\n if (this._sdkOverride) return this._sdkOverride;\n return (await import(/* @vite-ignore */ s3Pkg)) as S3SdkModule;\n }\n\n async connect(declaration: ConnectorDeclaration, ctx: ConnectContext): Promise<ConnectorHandle> {\n const targetDir = ctx.mountTarget;\n if (!targetDir) {\n throw new Error(\"S3Connector requires ctx.mountTarget to be set by the manager\");\n }\n const secrets = ctx.secrets;\n\n const started = Date.now();\n const opts = declaration.options;\n const bucket = String(opts?.bucket ?? \"\");\n if (!bucket) {\n this.log.error(\"connect failed: missing bucket option\", undefined);\n throw new Error(\"S3Connector requires options.bucket\");\n }\n\n const prefix = String(opts?.prefix ?? \"\");\n const region = String(opts?.region ?? \"us-east-1\");\n const endpoint = opts?.endpoint ? String(opts.endpoint) : undefined;\n this.log.info(\"mount start\", { bucket, prefix, region, endpoint, targetDir });\n\n const s3Mod = await this._loadSdk();\n const { S3Client } = s3Mod;\n\n const clientConfig: any = { region };\n if (endpoint) clientConfig.endpoint = endpoint;\n\n // Pass the profile via the client config rather than mutating process.env\n // (AWS_PROFILE), which leaks process-wide and is never restored.\n const profile = secrets?.resolve(declaration.auth ?? \"\");\n if (profile) {\n clientConfig.profile = profile;\n }\n\n const client = new S3Client(clientConfig);\n const state: S3State = { client, bucket, prefix, region };\n\n // Initial sync: download objects to targetDir\n mkdirSync(targetDir, { recursive: true });\n try {\n const result = await this.downloadAll(state, targetDir);\n this.log.info(\"mount ok\", {\n targetDir,\n filesWritten: result.filesWritten,\n durationMs: Date.now() - started,\n });\n return this.makeHandle(declaration, state, targetDir);\n } catch (err) {\n this.log.error(\"connect failed\", err, { bucket, targetDir });\n throw err;\n }\n }\n\n async disconnect(handle: ConnectorHandle): Promise<void> {\n this.log.info(\"unmount\");\n const { client } = handle.state as S3State;\n client.destroy();\n }\n\n private async _sync(handle: ConnectorHandle, _options?: SyncOptions): Promise<SyncResult> {\n this.log.debug(\"sync start\");\n const state = handle.state as S3State;\n try {\n const result = await this.downloadAll(state, handle.mountPath!);\n this.log.debug(\"sync ok\", { filesWritten: result.filesWritten });\n return result;\n } catch (err) {\n this.log.error(\"sync failed\", err);\n throw err;\n }\n }\n\n private async downloadAll(state: S3State, targetDir: string): Promise<SyncResult> {\n const s3Mod = await this._loadSdk();\n const { client, bucket, prefix } = state;\n\n // List all objects\n const entries: Array<{ key: string; relPath: string }> = [];\n let continuationToken: string | undefined;\n\n do {\n const resp = await client.send(\n new s3Mod.ListObjectsV2Command({\n Bucket: bucket,\n Prefix: prefix,\n MaxKeys: 1000,\n ContinuationToken: continuationToken,\n }),\n );\n\n for (const obj of resp.Contents ?? []) {\n const relPath =\n prefix && obj.Key?.startsWith(prefix) ? obj.Key.slice(prefix.length) : obj.Key;\n if (!relPath) continue;\n entries.push({ key: obj.Key, relPath });\n }\n\n continuationToken = resp.IsTruncated ? resp.NextContinuationToken : undefined;\n } while (continuationToken);\n\n // Download each file\n let filesWritten = 0;\n let bytesTransferred = 0;\n for (const { key, relPath } of entries) {\n try {\n const resp = await client.send(new s3Mod.GetObjectCommand({ Bucket: bucket, Key: key }));\n // transformToByteArray preserves binary content; transformToString would\n // UTF-8 decode and corrupt non-text objects.\n const bytes = await resp.Body?.transformToByteArray();\n if (bytes == null) continue;\n const body = Buffer.from(bytes);\n\n const localPath = join(targetDir, relPath);\n mkdirSync(dirname(localPath), { recursive: true });\n writeFileSync(localPath, body);\n filesWritten++;\n bytesTransferred += body.byteLength;\n } catch (err) {\n this.log.warn(\"object download failed\", {\n key,\n error: err instanceof Error ? err.message : String(err),\n });\n }\n }\n\n return { filesWritten, filesDeleted: 0, bytesTransferred };\n }\n}\n\n/**\n * Creates a new S3Connector instance.\n * @param sdkOverride - Optional SDK module to use instead of dynamically importing\n * `@aws-sdk/client-s3`. Intended for testing only.\n * @returns Configured S3Connector ready to be registered in the connector registry.\n * @docLink packages/factory-assets/api-reference#s3-connector-factory\n */\nexport function createConnector(sdkOverride?: S3SdkModule): S3Connector {\n return new S3Connector(sdkOverride);\n}\n","/**\n * SharePointConnector — SharePoint/OneDrive filesystem-face connector backed by rclone FUSE.\n *\n * The whole data plane (enumeration, download, upload, change detection,\n * cache eviction) is delegated to an `rclone mount` subprocess managed by\n * {@link RcloneProcessManager}. This connector only parses the declaration,\n * renders the rclone config, hands it off, and forwards lifecycle hooks.\n */\n\nimport type {\n ConnectContext,\n ConnectorDeclaration,\n ConnectorHandle,\n FilesystemFace,\n RcloneHandle,\n SyncOptions,\n SyncResult,\n} from \"@skaile/workspaces/connectors\";\nimport {\n AbstractConnector,\n createRcloneTokenRefresh,\n ensureDirMode,\n ensureFleetMounted,\n isFleetManaged,\n type RcloneTokenRefreshController,\n RcloneProcessManager,\n renderOneDriveConfig,\n resolveMountCredential,\n} from \"@skaile/workspaces/connectors\";\n\ninterface SharePointState {\n /** Mutable holder of the live rclone handle; reassigned on every token-refresh recycle. */\n handleRef: { current: RcloneHandle | null };\n /** Proactive + reactive token-refresh controller; absent for non-backend / fleet mounts. */\n refresh?: RcloneTokenRefreshController;\n fleetManaged?: boolean;\n /**\n * Authoritative remote-size hook read by the mount read path to defeat the\n * rclone VFS stale tail (a shorter remote rewrite served as\n * `[new bytes][leftover tail]`). Absent on fleet mounts — the in-container\n * connector has no rc server to query.\n */\n authoritativeSize?: (relPath: string) => Promise<number | null>;\n}\n\ninterface ParsedAuth {\n accessToken: string;\n refreshToken: string | null;\n expiresAtMs: number | null;\n tenantId: string | null;\n clientId: string | null;\n clientSecret: string | null;\n}\n\nconst DEFAULT_CACHE_BASE = \"/var/cache/skaile\";\n\n// Cache root for rclone VFS dirs. Read per-connect (not at module load) and\n// overridable via env so the path can follow the host bind-mount and so tests\n// can target a writable (non-root) location.\nfunction cacheBase(): string {\n return process.env.SKAILE_RCLONE_CACHE_BASE ?? DEFAULT_CACHE_BASE;\n}\n\n/**\n * Filesystem-face connector for SharePoint and OneDrive — delegates the data plane to an\n * `rclone mount` subprocess via `RcloneProcessManager` using the OneDrive backend.\n * Supports OAuth2 access tokens with optional refresh, and fleet-managed mode via\n * `SKAILE_FLEET_MANAGED_MOUNTS`.\n * @docLink packages/factory-assets/concepts#sharepoint-connector\n */\nexport class SharePointConnector extends AbstractConnector {\n readonly name = \"sharepoint\";\n\n private rclone = new RcloneProcessManager();\n\n readonly filesystem: FilesystemFace = {\n deferMount: true,\n sync: (handle: ConnectorHandle, options?: SyncOptions): Promise<SyncResult> => {\n return this._sync(handle, options);\n },\n };\n\n async connect(declaration: ConnectorDeclaration, ctx: ConnectContext): Promise<ConnectorHandle> {\n const targetDir = ctx.mountTarget;\n if (!targetDir) {\n throw new Error(\"SharePointConnector requires ctx.mountTarget to be set by the manager\");\n }\n const secrets = ctx.secrets;\n const tokenMediator = ctx.tokenMediator;\n\n const opts = declaration.options;\n this.log.info(\"mount called\", {\n optionKeys: opts ? Object.keys(opts) : [],\n });\n\n // Phase 7B: when the host fleet has already mounted this share, the\n // container received a bind at `targetDir` and there is nothing for\n // the in-container connector to spawn. Verify the bind is live, then\n // produce a no-op handle that the rest of the lifecycle can carry.\n if (isFleetManaged(declaration.id)) {\n this.log.info(\"mount handled by host fleet — skipping in-container rclone spawn\", {\n connectorId: declaration.id,\n targetDir,\n });\n await ensureFleetMounted(targetDir, this.log);\n const fleetState: SharePointState = {\n handleRef: { current: null },\n fleetManaged: true,\n };\n return this.makeHandle(declaration, fleetState, targetDir);\n }\n\n const driveId = String(opts?.driveId ?? \"\");\n if (!driveId) {\n throw new Error(\"SharePoint connector requires options.driveId\");\n }\n\n const folderPath = String(opts?.folderPath ?? \"\").trim();\n if (!folderPath) {\n throw new Error(\n \"SharePoint connector requires options.folderPath (rclone backend needs a path string, not just folderId)\",\n );\n }\n\n const basePath = String(opts?.basePath ?? \"\").replace(/^\\/+|\\/+$/g, \"\");\n const cred = await resolveMountCredential(declaration, secrets, tokenMediator, \"initial\");\n const auth = parseAuthBlob(cred.token, this.log);\n if (!auth.accessToken) {\n throw new Error(\n \"SharePoint connector: no access token resolved. Use 'auth: backend' (platform) or 'auth: env:SHAREPOINT_TOKEN' (standalone).\",\n );\n }\n\n const remoteName = `skaile-${declaration.id}`;\n const remotePath = buildRemotePath(folderPath, basePath);\n const remote = `${remoteName}:${remotePath}`;\n const base = cacheBase();\n const cacheDir = `${base}/${declaration.id}`;\n const vfsCacheMode = declaration.access === \"read-only\" ? \"minimal\" : \"full\";\n\n this.log.info(\"mount params resolved\", {\n driveId,\n remote,\n cacheDir,\n vfsCacheMode,\n hasRefresh: auth.refreshToken !== null,\n });\n\n // Re-render the rclone INI from a (possibly refreshed) credential blob. The\n // token-refresh controller calls this on each recycle; the initial spawn\n // uses it too so the rendering path is shared.\n const renderConfig = (rawToken: string): string => {\n const a = parseAuthBlob(rawToken, this.log);\n return renderOneDriveConfig({\n remoteName,\n accessToken: a.accessToken,\n refreshToken: a.refreshToken,\n expiresAtMs: a.expiresAtMs,\n tenantId: a.tenantId,\n clientId: a.clientId,\n clientSecret: a.clientSecret,\n driveId,\n });\n };\n\n // Skaile-managed Entra blobs strip the client_secret so rclone cannot\n // self-refresh; arm a proactive refresh (reactive auth-error as net) for\n // backend-mediated mounts. Standalone env:/inline auth has no mediator and\n // no expiry — it stays static.\n const handleRef: { current: RcloneHandle | null } = { current: null };\n const refresh: RcloneTokenRefreshController | undefined =\n declaration.auth === \"backend\" && tokenMediator\n ? createRcloneTokenRefresh({\n connectorId: declaration.id,\n tokenMediator,\n renderConfig,\n rclone: this.rclone,\n handleRef,\n log: (line) => this.log.info(line),\n })\n : undefined;\n\n const rcloneConfig = renderConfig(cred.token ?? \"\");\n\n // Create + chmod 0770 on every dir we own. See `ensureDirMode` in\n // @skaile/workspaces/connectors for the umask / EPERM rationale.\n await ensureDirMode(base, this.log);\n await ensureDirMode(cacheDir, this.log);\n await ensureDirMode(targetDir, this.log);\n\n const cacheMaxSize = opts?.cacheMaxSize !== undefined ? String(opts.cacheMaxSize) : undefined;\n const cacheMaxAge = opts?.cacheMaxAge !== undefined ? String(opts.cacheMaxAge) : undefined;\n const vfsWriteBack = opts?.vfsWriteBack !== undefined ? String(opts.vfsWriteBack) : undefined;\n const ignoreSizeCheck = opts?.ignoreSizeCheck === true;\n\n if (ignoreSizeCheck) {\n this.log.warn(\n \"ignoreSizeCheck enabled — rclone post-transfer size/checksum verification disabled for this mount\",\n { connectorId: declaration.id },\n );\n }\n\n const rcloneHandle = await this.rclone.spawn({\n mountId: declaration.id,\n driverName: \"sharepoint\",\n mountPoint: targetDir,\n cacheDir,\n rcloneConfig,\n remote,\n vfsCacheMode,\n ...(cacheMaxSize !== undefined ? { cacheMaxSize } : {}),\n ...(cacheMaxAge !== undefined ? { cacheMaxAge } : {}),\n ...(vfsWriteBack !== undefined ? { vfsWriteBack } : {}),\n ...(ignoreSizeCheck ? { ignoreSizeCheck: true } : {}),\n ...(refresh ? { onAuthError: () => refresh.onAuthError() } : {}),\n log: this.log,\n });\n\n this.log.info(\"mount ready\", { pid: rcloneHandle.pid });\n\n handleRef.current = rcloneHandle;\n refresh?.schedule(cred.expiresAt);\n\n const state: SharePointState = {\n handleRef,\n refresh,\n authoritativeSize: (relPath: string) => {\n const h = handleRef.current;\n return h ? this.rclone.statSize(h, relPath) : Promise.resolve(null);\n },\n };\n return this.makeHandle(declaration, state, targetDir);\n }\n\n async disconnect(handle: ConnectorHandle): Promise<void> {\n const s = handle.state as SharePointState;\n s.refresh?.cancel();\n if (s.fleetManaged || !s.handleRef.current) return;\n await this.rclone.stop(s.handleRef.current, { graceMs: 30_000 });\n }\n\n private async _sync(handle: ConnectorHandle, options?: SyncOptions): Promise<SyncResult> {\n const s = handle.state as SharePointState;\n if (s.fleetManaged || !s.handleRef.current) {\n // Host fleet owns the rclone process; flushing is a fleet concern.\n options?.onSyncStatus?.({\n phase: \"initial_sync_complete\",\n totalFiles: 0,\n downloadedFiles: 0,\n stubFiles: 0,\n message: \"fleet-managed mount — flush handled by host\",\n });\n return { filesWritten: 0, filesDeleted: 0, bytesTransferred: 0 };\n }\n await this.rclone.flush(s.handleRef.current);\n options?.onSyncStatus?.({\n phase: \"initial_sync_complete\",\n totalFiles: 0,\n downloadedFiles: 0,\n stubFiles: 0,\n message: \"rclone flush complete\",\n });\n return { filesWritten: 0, filesDeleted: 0, bytesTransferred: 0 };\n }\n\n override async onHibernate(handle: ConnectorHandle): Promise<string | undefined> {\n const s = handle.state as SharePointState;\n if (s.fleetManaged) return \"flushed\";\n await this._sync(handle);\n return \"flushed\";\n }\n\n override async onSessionClose(handle: ConnectorHandle): Promise<string | undefined> {\n const s = handle.state as SharePointState;\n if (s.fleetManaged) return \"flushed\";\n await this._sync(handle);\n return \"flushed\";\n }\n}\n\n/**\n * Creates a new SharePointConnector instance.\n * @returns Configured SharePointConnector ready to be registered in the connector registry.\n * @docLink packages/factory-assets/api-reference#sharepoint-connector-factory\n */\nexport function createConnector(): SharePointConnector {\n return new SharePointConnector();\n}\n\n// ── helpers ────────────────────────────────────────────────────────────────\n\nfunction parseAuthBlob(\n raw: string | undefined,\n log?: { warn: (msg: string, data?: object) => void },\n): ParsedAuth {\n const empty: ParsedAuth = {\n accessToken: \"\",\n refreshToken: null,\n expiresAtMs: null,\n tenantId: null,\n clientId: null,\n clientSecret: null,\n };\n if (!raw) return empty;\n\n if (!raw.startsWith(\"{\")) {\n return { ...empty, accessToken: raw };\n }\n\n try {\n const parsed = JSON.parse(raw) as {\n accessToken?: string;\n refreshToken?: string;\n expiresAt?: number;\n tenantId?: string;\n clientId?: string;\n clientSecret?: string;\n };\n return {\n accessToken: parsed.accessToken ?? \"\",\n refreshToken: parsed.refreshToken ?? null,\n expiresAtMs: parsed.expiresAt ?? null,\n tenantId: parsed.tenantId ?? null,\n clientId: parsed.clientId ?? null,\n clientSecret: parsed.clientSecret ?? null,\n };\n } catch (err) {\n // Looked like a JSON bundle but failed to parse — most likely a truncated\n // credential. Falling back silently lets rclone fail later with an opaque\n // 401; surface a warning so misconfiguration is detectable in the logs.\n log?.warn(\"auth blob starts with '{' but is not valid JSON — treating as raw token\", {\n error: err instanceof Error ? err.message : String(err),\n });\n return { ...empty, accessToken: raw };\n }\n}\n\n/**\n * Compose the remote path portion (after `remoteName:`) from a human-readable\n * folder path and an optional sub-base. rclone's onedrive backend takes a\n * path within the drive; an empty path means the drive root.\n */\nfunction buildRemotePath(folderPath: string, basePath: string): string {\n const folder = folderPath.replace(/^\\/+|\\/+$/g, \"\");\n const base = basePath.replace(/^\\/+|\\/+$/g, \"\");\n const joined = [folder, base].filter((p) => p.length > 0).join(\"/\");\n return joined.length > 0 ? `/${joined}` : \"/\";\n}\n","/**\n * SQLiteConnector — SQLite database resource via sql.js (WASM).\n * Not mountable. Custom operations: query, schema, execute.\n *\n * Uses sql.js — SQLite compiled to WebAssembly. Runs on Node, Bun, and\n * browsers without native compilation or platform-specific binaries.\n *\n * Requires `sql.js` as an optional peer dependency.\n */\n\nimport { existsSync, readFileSync, writeFileSync } from \"node:fs\";\nimport type {\n ConnectContext,\n ConnectorContent,\n ConnectorDeclaration,\n ConnectorEntry,\n ConnectorHandle,\n ListOptions,\n OperationDescriptor,\n SearchOptions,\n SearchResult,\n ToolFace,\n} from \"@skaile/workspaces/connectors\";\nimport { AbstractConnector } from \"@skaile/workspaces/connectors\";\n\ninterface SqliteState {\n db: any; // sql.js Database instance\n dbPath: string;\n readonly: boolean;\n}\n\n/** Escape an identifier for safe interpolation inside double quotes. */\nfunction quoteIdent(ident: string): string {\n return ident.replace(/\"/g, '\"\"');\n}\n\n/**\n * Connector for SQLite databases via sql.js (WASM). Supports in-memory and file-backed databases.\n * Provides query, schema inspection, and execute operations. Requires the `sql.js` optional peer dependency.\n * @docLink packages/factory-assets/concepts#sqlite-connector\n */\nexport class SQLiteConnector extends AbstractConnector {\n readonly name = \"sqlite\";\n\n tools: ToolFace;\n\n constructor() {\n super();\n this.tools = {\n read: (handle, path) => this._read(handle, path),\n list: (handle, path, options) => this._list(handle, path, options),\n search: (handle, query, options) => this._search(handle, query, options),\n describeOperations: (handle) => this._describeOperations(handle),\n executeOp: (handle, operation, args) => this._executeOp(handle, operation, args),\n };\n }\n\n async connect(declaration: ConnectorDeclaration, ctx: ConnectContext): Promise<ConnectorHandle> {\n const started = Date.now();\n const dbPath =\n ctx.secrets?.resolve(declaration.auth ?? \"\") ?? String(declaration.options?.path ?? \"\");\n if (!dbPath) {\n this.log.error(\"connect failed: missing path\", undefined);\n throw new Error(\"SQLiteAdapter requires auth (db path) or options.path\");\n }\n this.log.info(\"connect start\", { dbPath });\n\n const sqljsPkg = \"sql.js\";\n const initSqlJs = await import(/* @vite-ignore */ sqljsPkg).then((m) => m.default ?? m);\n const SQL = await initSqlJs();\n\n const isReadonly = declaration.access === \"read-only\";\n let db: any;\n\n if (dbPath === \":memory:\") {\n db = new SQL.Database();\n } else if (existsSync(dbPath)) {\n const buffer = readFileSync(dbPath);\n db = new SQL.Database(buffer);\n } else if (!isReadonly) {\n // Create new database file\n db = new SQL.Database();\n } else {\n this.log.error(\"connect failed: db file not found\", undefined, { dbPath });\n throw new Error(`SQLite database not found: ${dbPath}`);\n }\n\n this.log.info(\"connect ok\", { dbPath, durationMs: Date.now() - started });\n\n // Enable WAL mode for file-backed databases (not supported in sql.js but\n // harmless — sql.js operates in-memory and flushes to disk on save)\n if (!isReadonly && dbPath !== \":memory:\") {\n try {\n db.run(\"PRAGMA journal_mode = WAL\");\n } catch {\n /* ignored in WASM */\n }\n }\n\n return this.makeHandle(declaration, { db, dbPath, readonly: isReadonly } satisfies SqliteState);\n }\n\n async disconnect(handle: ConnectorHandle): Promise<void> {\n this.log.info(\"disconnect\");\n const { db, dbPath, readonly: isReadonly } = handle.state as SqliteState;\n // Persist changes to disk before closing (sql.js is in-memory)\n if (!isReadonly && dbPath !== \":memory:\") {\n this.saveToDisk(db, dbPath);\n }\n db.close();\n handle.status = \"disconnected\";\n }\n\n private db(handle: ConnectorHandle): any {\n return (handle.state as SqliteState).db;\n }\n\n /** sql.js operates in-memory — flush to disk explicitly. */\n private saveToDisk(db: any, dbPath: string): void {\n try {\n const data = db.export();\n const buffer = Buffer.from(data);\n writeFileSync(dbPath, buffer);\n } catch {\n /* best-effort */\n }\n }\n\n /** Run a query that returns rows. sql.js uses stmt.getAsObject() pattern. */\n private queryRows(db: any, sql: string, params?: unknown[]): Record<string, unknown>[] {\n const stmt = db.prepare(sql);\n if (params?.length) stmt.bind(params);\n const rows: Record<string, unknown>[] = [];\n while (stmt.step()) {\n rows.push(stmt.getAsObject());\n }\n stmt.free();\n return rows;\n }\n\n /** Run a statement that modifies data. Returns changes count. */\n private runStmt(db: any, sql: string, params?: unknown[]): number {\n if (params?.length) {\n db.run(sql, params);\n } else {\n db.run(sql);\n }\n const changes = db.getRowsModified();\n return changes;\n }\n\n private async _read(handle: ConnectorHandle, path: string): Promise<ConnectorContent | null> {\n const parts = path.split(\"/\");\n if (parts.length === 1) {\n const table = parts[0]!;\n const info = this.queryRows(this.db(handle), `PRAGMA table_info(\"${quoteIdent(table)}\")`);\n if (info.length === 0) return null;\n return { data: JSON.stringify(info, null, 2), contentType: \"application/json\" };\n }\n const [table, rowid] = parts;\n const rows = this.queryRows(\n this.db(handle),\n `SELECT * FROM \"${quoteIdent(table!)}\" WHERE rowid = ?`,\n [rowid],\n );\n if (rows.length === 0) return null;\n return { data: JSON.stringify(rows[0], null, 2), contentType: \"application/json\" };\n }\n\n private async _list(\n handle: ConnectorHandle,\n path?: string,\n options?: ListOptions,\n ): Promise<ConnectorEntry[]> {\n if (!path) {\n const tables = this.queryRows(\n this.db(handle),\n \"SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%' ORDER BY name\",\n );\n return tables.map((t: any) => ({\n name: t.name,\n path: t.name,\n type: \"directory\" as const,\n }));\n }\n const limit = options?.limit ?? 100;\n const rows = this.queryRows(\n this.db(handle),\n `SELECT rowid, * FROM \"${quoteIdent(path)}\" LIMIT ?`,\n [limit],\n );\n return rows.map((row: any) => ({\n name: String(row.rowid ?? row.id ?? \"?\"),\n path: `${path}/${row.rowid ?? row.id ?? \"?\"}`,\n type: \"row\" as const,\n }));\n }\n\n private async _search(\n handle: ConnectorHandle,\n query: string,\n options?: SearchOptions,\n ): Promise<SearchResult[]> {\n const tables = await this._list(handle);\n const results: SearchResult[] = [];\n const maxResults = options?.maxResults ?? 50;\n\n for (const table of tables) {\n if (results.length >= maxResults) break;\n try {\n const info = this.queryRows(\n this.db(handle),\n `PRAGMA table_info(\"${quoteIdent(table.name)}\")`,\n );\n const textCols = info.filter((c: any) => /text|varchar|char/i.test(String(c.type ?? \"\")));\n if (textCols.length === 0) continue;\n\n const conditions = textCols\n .map((c: any) => `\"${quoteIdent(String(c.name))}\" LIKE ?`)\n .join(\" OR \");\n const params: unknown[] = textCols.map(() => `%${query}%`);\n params.push(maxResults - results.length);\n const rows = this.queryRows(\n this.db(handle),\n `SELECT rowid, * FROM \"${quoteIdent(table.name)}\" WHERE ${conditions} LIMIT ?`,\n params,\n );\n\n for (const row of rows) {\n results.push({\n path: `${table.name}/${row.rowid ?? \"?\"}`,\n snippet: JSON.stringify(row).slice(0, 200),\n });\n }\n } catch {\n // Skip inaccessible tables\n }\n }\n return results;\n }\n\n private _describeOperations(handle: ConnectorHandle): OperationDescriptor[] {\n const ops: OperationDescriptor[] = [\n {\n name: \"query\",\n description: \"Execute a read-only SQL query. Returns JSON rows.\",\n accessLevel: \"read\",\n args: [\n { name: \"sql\", type: \"string\", required: true, description: \"SQL SELECT statement\" },\n ],\n examples: [\n 'query --sql \"SELECT * FROM users LIMIT 10\"',\n 'query --sql \"SELECT count(*) as total FROM orders\"',\n ],\n },\n {\n name: \"schema\",\n description: \"Inspect database schema — tables and their columns.\",\n accessLevel: \"read\",\n args: [\n {\n name: \"table\",\n type: \"string\",\n required: false,\n description: \"Specific table (omit for all tables)\",\n },\n ],\n examples: [\"schema\", \"schema --table users\"],\n },\n ];\n\n if (handle.access === \"read-write\") {\n ops.push({\n name: \"execute\",\n description:\n \"Execute a SQL statement (INSERT, UPDATE, DELETE, CREATE). Returns changes count.\",\n accessLevel: \"write\",\n args: [{ name: \"sql\", type: \"string\", required: true, description: \"SQL statement\" }],\n examples: [\"execute --sql \\\"INSERT INTO users (name) VALUES ('Alice')\\\"\"],\n });\n }\n\n return ops;\n }\n\n private async _executeOp(\n handle: ConnectorHandle,\n operation: string,\n args: Record<string, unknown>,\n ): Promise<string> {\n const db = this.db(handle);\n const state = handle.state as SqliteState;\n\n switch (operation) {\n case \"query\": {\n const sql = String(args.sql ?? args._positional ?? \"\");\n if (!sql) return \"Error: sql argument is required\";\n const rows = this.queryRows(db, sql);\n return JSON.stringify(rows, null, 2);\n }\n case \"schema\": {\n const table = args.table ? String(args.table) : undefined;\n if (table) {\n const info = this.queryRows(db, `PRAGMA table_info(\"${quoteIdent(table)}\")`);\n return JSON.stringify(info, null, 2);\n }\n const tables = this.queryRows(\n db,\n \"SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%' ORDER BY name\",\n );\n const result: Record<string, any> = {};\n for (const t of tables) {\n result[t.name as string] = this.queryRows(\n db,\n `PRAGMA table_info(\"${quoteIdent(String(t.name))}\")`,\n );\n }\n return JSON.stringify(result, null, 2);\n }\n case \"execute\": {\n const sql = String(args.sql ?? args._positional ?? \"\");\n if (!sql) return \"Error: sql argument is required\";\n const changes = this.runStmt(db, sql);\n // Persist after mutation\n if (!state.readonly && state.dbPath !== \":memory:\") {\n this.saveToDisk(db, state.dbPath);\n }\n return JSON.stringify({ changes });\n }\n default:\n throw new Error(`SQLiteAdapter has no operation: ${operation}`);\n }\n }\n}\n\n/**\n * Creates a new SQLiteConnector instance.\n * @returns Configured SQLiteConnector ready to be registered in the connector registry.\n * @docLink packages/factory-assets/api-reference#sqlite-connector-factory\n */\nexport function createConnector(): SQLiteConnector {\n return new SQLiteConnector();\n}\n","/**\n * StaticServerConnector — serve a directory of static files over HTTP.\n * Category: service\n *\n * Built on `node:http` + `node:fs`, so it runs under both Node and Bun.\n */\n\nimport { createReadStream, existsSync, statSync } from \"node:fs\";\nimport { createServer, type Server as HttpServer, type ServerResponse } from \"node:http\";\nimport { join, resolve, sep } from \"node:path\";\nimport type {\n ConnectContext,\n ConnectorDeclaration,\n ConnectorHandle,\n OperationDescriptor,\n RuntimeSkillDescriptor,\n ToolFace,\n} from \"@skaile/workspaces/connectors\";\nimport {\n AbstractConnector,\n createWorktree,\n findGitRoot,\n PortPool,\n} from \"@skaile/workspaces/connectors\";\nimport mime from \"mime\";\n\ninterface StaticInstance {\n id: string;\n port: number;\n dir: string;\n server: HttpServer;\n ref?: string;\n worktreePath?: string;\n worktreeCleanup?: () => Promise<void>;\n startedAt: string;\n status: \"healthy\" | \"stopped\";\n}\n\ninterface StaticServerState {\n instances: Map<string, StaticInstance>;\n pool: PortPool;\n repoRoot: string | null;\n worktreeDir: string;\n}\n\nconst DEFAULT_PORT_RANGE: [number, number] = [14000, 14099];\nconst DEFAULT_WORKTREE_DIR = \"/tmp/skaile-static-worktrees\";\n\n/**\n * Connector for serving static file directories over HTTP.\n * Supports multiple concurrent instances, port allocation, and optional git worktree isolation.\n * @docLink packages/factory-assets/concepts#static-server-connector\n */\nexport class StaticServerConnector extends AbstractConnector {\n readonly name = \"static-server\";\n\n tools: ToolFace;\n\n constructor() {\n super();\n this.tools = {\n describeOperations: (handle) => this._describeOperations(handle),\n executeOp: (handle, operation, args) => this._executeOp(handle, operation, args),\n describeSkill: (handle, declaration) => this._describeSkill(handle, declaration),\n };\n }\n\n async connect(declaration: ConnectorDeclaration, _ctx: ConnectContext): Promise<ConnectorHandle> {\n this.log.info(\"connect\", { id: declaration.id });\n const range = (declaration.options?.port_range as [number, number]) ?? DEFAULT_PORT_RANGE;\n const worktreeDir = String(declaration.options?.worktree_dir ?? DEFAULT_WORKTREE_DIR);\n let repoRoot: string | null = null;\n try {\n repoRoot = findGitRoot(process.cwd());\n } catch {}\n\n return this.makeHandle(declaration, {\n instances: new Map(),\n pool: new PortPool(range),\n repoRoot,\n worktreeDir,\n } as StaticServerState);\n }\n\n async disconnect(handle: ConnectorHandle): Promise<void> {\n this.log.info(\"disconnect\");\n try {\n await this._stopAll(handle);\n } finally {\n handle.status = \"disconnected\";\n }\n }\n\n override async onSessionClose(handle: ConnectorHandle): Promise<string | undefined> {\n await this._stopAll(handle);\n return undefined;\n }\n\n // ── Tool face methods (private, wired in constructor) ─────────────────────\n\n private async _stopAll(handle: ConnectorHandle): Promise<void> {\n const state = handle.state as StaticServerState;\n for (const [, instance] of state.instances) {\n stopHttpServer(instance.server);\n instance.status = \"stopped\";\n if (instance.worktreeCleanup) {\n try {\n await instance.worktreeCleanup();\n } catch {}\n }\n state.pool.release(instance.port);\n }\n state.instances.clear();\n }\n\n private _describeOperations(_handle: ConnectorHandle): OperationDescriptor[] {\n return [\n {\n name: \"serve\",\n description: \"Serve a directory of static files over HTTP.\",\n accessLevel: \"write\",\n args: [\n { name: \"dir\", type: \"string\", required: true, description: \"Directory to serve\" },\n { name: \"port\", type: \"number\", required: false, description: \"Explicit port\" },\n { name: \"label\", type: \"string\", required: false, description: \"Instance label\" },\n { name: \"ref\", type: \"string\", required: false, description: \"Git ref for worktree\" },\n ],\n },\n {\n name: \"stop\",\n description: \"Stop a static server.\",\n accessLevel: \"write\",\n args: [{ name: \"instance\", type: \"string\", required: true, description: \"Instance ID\" }],\n },\n {\n name: \"status\",\n description: \"Get instance status.\",\n accessLevel: \"read\",\n args: [\n {\n name: \"instance\",\n type: \"string\",\n required: false,\n description: \"Instance ID (omit for all)\",\n },\n ],\n },\n {\n name: \"list_instances\",\n description: \"List all active instances.\",\n accessLevel: \"read\",\n args: [],\n },\n { name: \"free_port\", description: \"Reserve a free port.\", accessLevel: \"read\", args: [] },\n ];\n }\n\n private async _executeOp(\n handle: ConnectorHandle,\n operation: string,\n args: Record<string, unknown>,\n ): Promise<string> {\n const state = handle.state as StaticServerState;\n if ((operation === \"serve\" || operation === \"stop\") && handle.access === \"read-only\") {\n throw new Error(`StaticServerConnector: \"${operation}\" requires read-write access`);\n }\n\n switch (operation) {\n case \"serve\":\n return this._opServe(state, args);\n case \"stop\":\n return this._opStop(state, args);\n case \"status\":\n return this._opStatus(state, args);\n case \"list_instances\":\n return this._opListInstances(state);\n case \"free_port\":\n return this._opFreePort(state);\n default:\n throw new Error(`StaticServerConnector: unknown operation \"${operation}\"`);\n }\n }\n\n private async _opServe(state: StaticServerState, args: Record<string, unknown>): Promise<string> {\n let dir = args.dir ? String(args.dir) : \"\";\n if (!dir && !args.ref) throw new Error(\"serve requires a dir or ref\");\n const label = args.label ? String(args.label) : `static-${Date.now()}`;\n const port = args.port ? Number(args.port) : await state.pool.allocate();\n if (args.port) state.pool.reserve(port);\n\n let worktreePath: string | undefined;\n let worktreeCleanup: (() => Promise<void>) | undefined;\n let ref: string | undefined;\n\n if (args.ref) {\n if (!state.repoRoot) throw new Error(\"ref-based serving requires a git repository\");\n ref = String(args.ref);\n const wt = await createWorktree({\n repoRoot: state.repoRoot,\n ref,\n baseDir: state.worktreeDir,\n label,\n owner: `static:${label}`,\n });\n worktreePath = wt.path;\n worktreeCleanup = wt.cleanup;\n dir = dir ? join(wt.path, dir) : wt.path;\n }\n\n const serveDir = dir;\n const server = createServer((req, res) => {\n serveStaticFile(serveDir, req.url ?? \"/\", res);\n });\n server.listen(port);\n\n state.instances.set(label, {\n id: label,\n port,\n dir: serveDir,\n server,\n ref,\n worktreePath,\n worktreeCleanup,\n startedAt: new Date().toISOString(),\n status: \"healthy\",\n });\n this.emitChange?.({ path: label, action: \"create\", source: \"operation\" });\n return JSON.stringify({ instance_id: label, port, url: `http://localhost:${port}` });\n }\n\n private async _opStop(state: StaticServerState, args: Record<string, unknown>): Promise<string> {\n const id = String(args.instance ?? \"\");\n const instance = state.instances.get(id);\n if (!instance) throw new Error(`Instance \"${id}\" not found`);\n stopHttpServer(instance.server);\n instance.status = \"stopped\";\n state.pool.release(instance.port);\n if (instance.worktreeCleanup) {\n try {\n await instance.worktreeCleanup();\n } catch {}\n }\n state.instances.delete(id);\n this.emitChange?.({ path: id, action: \"delete\", source: \"operation\" });\n return JSON.stringify({ stopped: true });\n }\n\n private _opStatus(state: StaticServerState, args: Record<string, unknown>): string {\n if (args.instance) {\n const inst = state.instances.get(String(args.instance));\n if (!inst) throw new Error(`Instance \"${args.instance}\" not found`);\n return JSON.stringify(instanceToStatus(inst));\n }\n return JSON.stringify([...state.instances.values()].map(instanceToStatus));\n }\n\n private _opListInstances(state: StaticServerState): string {\n return JSON.stringify(\n [...state.instances.values()].map((i) => ({\n id: i.id,\n port: i.port,\n dir: i.dir,\n url: `http://localhost:${i.port}`,\n ref: i.ref,\n status: i.status,\n started_at: i.startedAt,\n })),\n );\n }\n\n private async _opFreePort(state: StaticServerState): Promise<string> {\n return JSON.stringify({ port: await state.pool.allocate() });\n }\n\n private _describeSkill(\n handle: ConnectorHandle,\n declaration: ConnectorDeclaration,\n ): RuntimeSkillDescriptor {\n return {\n id: declaration.id,\n name: \"Static File Server\",\n description: \"Serve directories of static files over HTTP.\",\n category: \"service\",\n access: handle.access,\n toolNames: this._describeOperations(handle).map((o) => o.name),\n };\n }\n}\n\n/**\n * Serve a single file from `rootDir` for the given request URL. Rejects paths\n * that escape `rootDir` (path traversal), 404s missing files, and resolves\n * directory requests to `index.html`.\n */\nfunction serveStaticFile(rootDir: string, reqUrl: string, res: ServerResponse): void {\n const root = resolve(rootDir);\n const pathname = decodeURIComponent(new URL(reqUrl, \"http://localhost\").pathname);\n let filePath = resolve(root, `.${pathname}`);\n // Containment guard — never serve a file outside the configured directory.\n if (filePath !== root && !filePath.startsWith(root + sep)) {\n res.writeHead(403, { \"content-type\": \"text/plain\" });\n res.end(\"Forbidden\");\n return;\n }\n if (pathname.endsWith(\"/\") || (existsSync(filePath) && statSync(filePath).isDirectory())) {\n filePath = join(filePath, \"index.html\");\n }\n if (!existsSync(filePath) || !statSync(filePath).isFile()) {\n res.writeHead(404, { \"content-type\": \"text/plain\" });\n res.end(\"Not Found\");\n return;\n }\n res.writeHead(200, { \"content-type\": mime.getType(filePath) ?? \"application/octet-stream\" });\n const stream = createReadStream(filePath);\n stream.on(\"error\", () => {\n if (!res.headersSent) res.writeHead(500, { \"content-type\": \"text/plain\" });\n res.end();\n });\n stream.pipe(res);\n}\n\n/** Stop an HTTP server, terminating any in-flight connections immediately. */\nfunction stopHttpServer(server: HttpServer): void {\n server.closeAllConnections();\n server.close();\n}\n\nfunction instanceToStatus(instance: StaticInstance) {\n return {\n id: instance.id,\n port: instance.port,\n dir: instance.dir,\n url: `http://localhost:${instance.port}`,\n ref: instance.ref,\n status: instance.status,\n started_at: instance.startedAt,\n uptime_ms: Date.now() - new Date(instance.startedAt).getTime(),\n };\n}\n\n/**\n * Creates a new StaticServerConnector instance.\n * @returns Configured StaticServerConnector ready to be registered in the connector registry.\n * @docLink packages/factory-assets/api-reference#static-server-connector-factory\n */\nexport function createConnector(): StaticServerConnector {\n return new StaticServerConnector();\n}\n","/**\n * TunnelConnector — expose local ports to the internet via cloudflare/ngrok/mock.\n * Category: service\n */\n\nimport type {\n ConnectContext,\n ConnectorDeclaration,\n ConnectorHandle,\n OperationDescriptor,\n RuntimeSkillDescriptor,\n ToolFace,\n} from \"@skaile/workspaces/connectors\";\nimport { AbstractConnector } from \"@skaile/workspaces/connectors\";\nimport { portableSpawn } from \"@skaile/workspaces/core\";\n\ninterface TunnelInstance {\n id: string;\n port: number;\n publicUrl: string;\n process?: { kill(): void };\n startedAt: string;\n status: \"connected\" | \"disconnected\";\n}\n\ninterface TunnelState {\n provider: string;\n tunnels: Map<string, TunnelInstance>;\n}\n\n/**\n * Connector for exposing local ports to the internet via Cloudflare Tunnel or ngrok.\n * Manages tunnel lifecycle (expose, close, status) and supports a mock provider for testing.\n * @docLink packages/factory-assets/concepts#tunnel-connector\n */\nexport class TunnelConnector extends AbstractConnector {\n readonly name = \"tunnel\";\n\n tools: ToolFace;\n\n constructor() {\n super();\n this.tools = {\n describeOperations: (handle) => this._describeOperations(handle),\n executeOp: (handle, operation, args) => this._executeOp(handle, operation, args),\n describeSkill: (handle, declaration) => this._describeSkill(handle, declaration),\n };\n }\n\n async connect(declaration: ConnectorDeclaration, _ctx: ConnectContext): Promise<ConnectorHandle> {\n const provider = String(declaration.options?.provider ?? \"cloudflare\");\n this.log.info(\"connect\", { id: declaration.id, provider });\n if (provider !== \"mock\") {\n const cli = provider === \"cloudflare\" ? \"cloudflared\" : \"ngrok\";\n const found = await checkCliExists(cli);\n if (!found) {\n this.log.error(\"connect failed: CLI not found\", undefined, { cli });\n throw new Error(`TunnelConnector: \"${cli}\" not found on PATH.`);\n }\n }\n return this.makeHandle(declaration, { provider, tunnels: new Map() } as TunnelState);\n }\n\n async disconnect(handle: ConnectorHandle): Promise<void> {\n this.log.info(\"disconnect\");\n try {\n await this._closeAll(handle);\n } finally {\n handle.status = \"disconnected\";\n }\n }\n\n override async onSessionClose(handle: ConnectorHandle): Promise<string | undefined> {\n await this._closeAll(handle);\n return undefined;\n }\n\n // ── Tool face methods (private, wired in constructor) ─────────────────────\n\n private async _closeAll(handle: ConnectorHandle): Promise<void> {\n const state = handle.state as TunnelState;\n for (const [id, tunnel] of state.tunnels) {\n tunnel.process?.kill();\n tunnel.status = \"disconnected\";\n this.emitChange?.({ path: id, action: \"delete\", source: \"operation\" });\n }\n state.tunnels.clear();\n }\n\n private _describeOperations(_handle: ConnectorHandle): OperationDescriptor[] {\n return [\n {\n name: \"expose\",\n description: \"Create a tunnel to a local port.\",\n accessLevel: \"write\",\n args: [\n { name: \"port\", type: \"number\", required: true, description: \"Local port\" },\n { name: \"label\", type: \"string\", required: false, description: \"Tunnel label\" },\n {\n name: \"subdomain\",\n type: \"string\",\n required: false,\n description: \"Requested subdomain\",\n },\n ],\n },\n {\n name: \"close\",\n description: \"Tear down a tunnel.\",\n accessLevel: \"write\",\n args: [{ name: \"tunnel\", type: \"string\", required: true, description: \"Tunnel ID\" }],\n },\n {\n name: \"status\",\n description: \"Get tunnel status.\",\n accessLevel: \"read\",\n args: [\n {\n name: \"tunnel\",\n type: \"string\",\n required: false,\n description: \"Tunnel ID (omit for all)\",\n },\n ],\n },\n { name: \"list\", description: \"List all active tunnels.\", accessLevel: \"read\", args: [] },\n ];\n }\n\n private async _executeOp(\n handle: ConnectorHandle,\n operation: string,\n args: Record<string, unknown>,\n ): Promise<string> {\n const state = handle.state as TunnelState;\n if ((operation === \"expose\" || operation === \"close\") && handle.access === \"read-only\") {\n throw new Error(`TunnelConnector: \"${operation}\" requires read-write access`);\n }\n\n switch (operation) {\n case \"expose\": {\n const port = Number(args.port);\n if (!port || Number.isNaN(port)) throw new Error(\"expose requires a valid port\");\n const label = args.label ? String(args.label) : String(port);\n let publicUrl: string;\n let proc: TunnelInstance[\"process\"] | undefined;\n if (state.provider === \"mock\") {\n publicUrl = `http://mock-tunnel-${label}.localhost`;\n } else if (state.provider === \"cloudflare\") {\n const result = await spawnCloudflaredTunnel(port);\n publicUrl = result.url;\n proc = result.process;\n } else if (state.provider === \"ngrok\") {\n const result = await spawnNgrokTunnel(port);\n publicUrl = result.url;\n proc = result.process;\n } else throw new Error(`Unknown provider \"${state.provider}\"`);\n const tunnel: TunnelInstance = {\n id: label,\n port,\n publicUrl,\n process: proc,\n startedAt: new Date().toISOString(),\n status: \"connected\",\n };\n state.tunnels.set(label, tunnel);\n this.log.info(\"tunnel exposed\", { label, port, publicUrl });\n this.emitChange?.({ path: label, action: \"create\", source: \"operation\" });\n return JSON.stringify({ tunnel_id: label, public_url: publicUrl });\n }\n case \"close\": {\n const id = String(args.tunnel ?? \"\");\n const tunnel = state.tunnels.get(id);\n if (!tunnel) throw new Error(`Tunnel \"${id}\" not found`);\n tunnel.process?.kill();\n tunnel.status = \"disconnected\";\n state.tunnels.delete(id);\n this.emitChange?.({ path: id, action: \"delete\", source: \"operation\" });\n return JSON.stringify({ closed: true });\n }\n case \"status\": {\n if (args.tunnel) {\n const t = state.tunnels.get(String(args.tunnel));\n if (!t) throw new Error(`Tunnel \"${args.tunnel}\" not found`);\n return JSON.stringify(tunnelToStatus(t));\n }\n return JSON.stringify([...state.tunnels.values()].map(tunnelToStatus));\n }\n case \"list\":\n return JSON.stringify(\n [...state.tunnels.values()].map((t) => ({\n id: t.id,\n port: t.port,\n public_url: t.publicUrl,\n status: t.status,\n started_at: t.startedAt,\n })),\n );\n default:\n throw new Error(`TunnelConnector: unknown operation \"${operation}\"`);\n }\n }\n\n private _describeSkill(\n handle: ConnectorHandle,\n declaration: ConnectorDeclaration,\n ): RuntimeSkillDescriptor {\n const state = handle.state as TunnelState;\n return {\n id: declaration.id,\n name: `Tunnel — ${state.provider}`,\n description: `Expose local ports to the internet via ${state.provider}.`,\n category: \"service\",\n access: handle.access,\n toolNames: this._describeOperations(handle).map((o) => o.name),\n };\n }\n}\n\nfunction tunnelToStatus(t: TunnelInstance) {\n return {\n id: t.id,\n port: t.port,\n public_url: t.publicUrl,\n status: t.status,\n started_at: t.startedAt,\n uptime_ms: Date.now() - new Date(t.startedAt).getTime(),\n };\n}\n\nasync function checkCliExists(cli: string): Promise<boolean> {\n try {\n const proc = portableSpawn([\"which\", cli]);\n return (await proc.exited) === 0;\n } catch {\n return false;\n }\n}\n\nasync function spawnCloudflaredTunnel(\n port: number,\n): Promise<{ url: string; process: { kill(): void } }> {\n return new Promise((resolve, reject) => {\n const proc = portableSpawn([\"cloudflared\", \"tunnel\", \"--url\", `http://localhost:${port}`]);\n const decoder = new TextDecoder();\n const reader = proc.stderr.getReader();\n const readLoop = async () => {\n while (true) {\n const { done, value } = await reader.read();\n if (done) break;\n const chunk = decoder.decode(value);\n const match = chunk.match(/https:\\/\\/[^\\s\"]+\\.trycloudflare\\.com/);\n if (match) {\n resolve({ url: match[0], process: proc });\n return;\n }\n }\n proc.kill();\n reject(new Error(\"cloudflared: failed to parse public URL\"));\n };\n readLoop().catch(reject);\n setTimeout(() => {\n proc.kill();\n reject(new Error(\"cloudflared: timed out\"));\n }, 30_000);\n });\n}\n\nasync function spawnNgrokTunnel(port: number): Promise<{ url: string; process: { kill(): void } }> {\n const proc = portableSpawn([\"ngrok\", \"http\", String(port)]);\n const deadline = Date.now() + 15_000;\n while (Date.now() < deadline) {\n await new Promise((r) => setTimeout(r, 500));\n try {\n const res = await fetch(\"http://localhost:4040/api/tunnels\");\n if (res.ok) {\n const data = (await res.json()) as { tunnels?: Array<{ public_url: string }> };\n const t = data.tunnels?.find((t) => t.public_url.startsWith(\"https://\"));\n if (t) return { url: t.public_url, process: proc };\n }\n } catch {}\n }\n proc.kill();\n throw new Error(\"ngrok: timed out\");\n}\n\n/**\n * Creates a new TunnelConnector instance.\n * @returns Configured TunnelConnector ready to be registered in the connector registry.\n * @docLink packages/factory-assets/api-reference#tunnel-connector-factory\n */\nexport function createConnector(): TunnelConnector {\n return new TunnelConnector();\n}\n","/**\n * WebDAVConnector -- WebDAV server filesystem-face connector backed by rclone FUSE.\n *\n * The whole data plane (enumeration, download, upload, change detection,\n * cache eviction) is delegated to an `rclone mount` subprocess managed by\n * {@link RcloneProcessManager}. This connector only parses the declaration,\n * obscures the password, renders the rclone config, hands it off, and\n * forwards lifecycle hooks.\n */\n\nimport { execFile } from \"node:child_process\";\nimport { promisify } from \"node:util\";\nimport type {\n ConnectContext,\n ConnectorDeclaration,\n ConnectorHandle,\n FilesystemFace,\n RcloneHandle,\n SyncOptions,\n SyncResult,\n} from \"@skaile/workspaces/connectors\";\nimport {\n AbstractConnector,\n createRcloneTokenRefresh,\n ensureDirMode,\n ensureFleetMounted,\n isFleetManaged,\n type RcloneTokenRefreshController,\n RcloneProcessManager,\n renderWebDAVConfig,\n resolveMountCredential,\n type WebDAVVendor,\n} from \"@skaile/workspaces/connectors\";\n\ninterface WebDAVState {\n /** Mutable holder of the live rclone handle; reassigned on every token-refresh recycle. */\n handleRef: { current: RcloneHandle | null };\n /** Proactive + reactive token-refresh controller; absent for non-backend / fleet mounts. */\n refresh?: RcloneTokenRefreshController;\n fleetManaged?: boolean;\n /**\n * Authoritative remote-size hook read by the mount read path to defeat the\n * rclone VFS stale tail (a shorter remote rewrite served as\n * `[new bytes][leftover tail]`). Absent on fleet mounts — the in-container\n * connector has no rc server to query.\n */\n authoritativeSize?: (relPath: string) => Promise<number | null>;\n}\n\ninterface ParsedAuth {\n username: string | null;\n password: string | null;\n bearerToken: string | null;\n}\n\nconst DEFAULT_CACHE_BASE = \"/var/cache/skaile\";\n\n// Cache root for rclone VFS dirs. Read per-connect (not at module load) and\n// overridable via env so the path can follow the host bind-mount and so tests\n// can target a writable (non-root) location. Mirrors the sharepoint driver.\nfunction cacheBase(): string {\n return process.env.SKAILE_RCLONE_CACHE_BASE ?? DEFAULT_CACHE_BASE;\n}\n\nconst ALLOWED_VENDORS: ReadonlySet<WebDAVVendor> = new Set([\n \"nextcloud\",\n \"owncloud\",\n \"sharepoint\",\n \"fastmail\",\n \"other\",\n]);\n\nconst execFileP = promisify(execFile);\n\n/**\n * Filesystem-face connector for WebDAV servers (Nextcloud, ownCloud, SharePoint-WebDAV,\n * Fastmail, generic) — delegates the data plane to an `rclone mount` subprocess via\n * `RcloneProcessManager`. Supports fleet-managed mode where the host has pre-mounted\n * the share via `SKAILE_FLEET_MANAGED_MOUNTS`.\n * @docLink packages/factory-assets/concepts#webdav-connector\n */\nexport class WebDAVConnector extends AbstractConnector {\n readonly name = \"webdav\";\n\n private rclone = new RcloneProcessManager();\n\n // Injectable so tests can stub the `rclone obscure` shell-out; production\n // wires the real binary via createConnector().\n constructor(private readonly obscure: (plain: string) => Promise<string> = obscurePassword) {\n super();\n }\n\n readonly filesystem: FilesystemFace = {\n deferMount: true,\n sync: (handle: ConnectorHandle, options?: SyncOptions): Promise<SyncResult> => {\n return this._sync(handle, options);\n },\n };\n\n async connect(declaration: ConnectorDeclaration, ctx: ConnectContext): Promise<ConnectorHandle> {\n const targetDir = ctx.mountTarget;\n if (!targetDir) {\n throw new Error(\"WebDAVConnector requires ctx.mountTarget to be set by the manager\");\n }\n const secrets = ctx.secrets;\n const tokenMediator = ctx.tokenMediator;\n\n const opts = declaration.options;\n this.log.info(\"mount called\", {\n optionKeys: opts ? Object.keys(opts) : [],\n hasAuth: declaration.auth !== undefined,\n });\n\n // Phase 7B: when the host fleet has already mounted this share, the\n // container received a bind at `targetDir` and there is nothing for\n // the in-container connector to spawn. Verify the bind is live, then\n // produce a no-op handle that the rest of the lifecycle can carry.\n if (isFleetManaged(declaration.id)) {\n this.log.info(\"mount handled by host fleet — skipping in-container rclone spawn\", {\n connectorId: declaration.id,\n targetDir,\n });\n await ensureFleetMounted(targetDir, this.log);\n const fleetState: WebDAVState = {\n handleRef: { current: null },\n fleetManaged: true,\n };\n return this.makeHandle(declaration, fleetState, targetDir);\n }\n\n const url = String(declaration.mount?.source ?? \"\").trim();\n if (!url) {\n throw new Error(\"WebDAV connector requires declaration.mount.source (server URL)\");\n }\n\n const vendorRaw = opts?.vendor !== undefined ? String(opts.vendor) : \"other\";\n if (!ALLOWED_VENDORS.has(vendorRaw as WebDAVVendor)) {\n throw new Error(\n `WebDAV connector: invalid vendor \"${vendorRaw}\" (allowed: ${[...ALLOWED_VENDORS].join(\", \")})`,\n );\n }\n const vendor = vendorRaw as WebDAVVendor;\n\n const basePath = String(opts?.basePath ?? \"\").replace(/^\\/+|\\/+$/g, \"\");\n const remotePath = basePath.length > 0 ? `/${basePath}` : \"/\";\n\n const cred = await resolveMountCredential(declaration, secrets, tokenMediator, \"initial\");\n const auth = parseAuth(cred.token);\n\n const remoteName = `skaile-${declaration.id}`;\n const remote = `${remoteName}:${remotePath}`;\n const base = cacheBase();\n const cacheDir = `${base}/${declaration.id}`;\n const vfsCacheMode = declaration.access === \"read-only\" ? \"minimal\" : \"full\";\n\n this.log.info(\"mount params resolved\", {\n url,\n vendor,\n remote,\n cacheDir,\n vfsCacheMode,\n authKind: auth.bearerToken ? \"bearer\" : auth.username ? \"basic\" : \"anonymous\",\n });\n\n // Re-render the rclone INI from a (possibly refreshed) credential string.\n // Async because a `user:pass` credential must be obscured via rclone. The\n // token-refresh controller calls this on each recycle; the initial spawn\n // shares the path.\n const renderConfig = async (rawToken: string): Promise<string> => {\n const a = parseAuth(rawToken);\n const obscured = a.password ? await this.obscure(a.password) : null;\n return renderWebDAVConfig({\n remoteName,\n url,\n vendor,\n username: a.username,\n obscuredPassword: obscured,\n bearerToken: a.bearerToken,\n });\n };\n\n // Backend-mediated bearer tokens expire; arm a proactive refresh (reactive\n // auth-error as net). Standalone env:/inline auth has no mediator/expiry.\n const handleRef: { current: RcloneHandle | null } = { current: null };\n const refresh: RcloneTokenRefreshController | undefined =\n declaration.auth === \"backend\" && tokenMediator\n ? createRcloneTokenRefresh({\n connectorId: declaration.id,\n tokenMediator,\n renderConfig,\n rclone: this.rclone,\n handleRef,\n log: (line) => this.log.info(line),\n })\n : undefined;\n\n const rcloneConfig = await renderConfig(cred.token ?? \"\");\n\n // Create + chmod 0770 on every dir we own. See `ensureDirMode` in\n // @skaile/workspaces/connectors for the umask / EPERM rationale.\n await ensureDirMode(base, this.log);\n await ensureDirMode(cacheDir, this.log);\n await ensureDirMode(targetDir, this.log);\n\n const cacheMaxSize = opts?.cacheMaxSize !== undefined ? String(opts.cacheMaxSize) : undefined;\n const cacheMaxAge = opts?.cacheMaxAge !== undefined ? String(opts.cacheMaxAge) : undefined;\n const vfsWriteBack = opts?.vfsWriteBack !== undefined ? String(opts.vfsWriteBack) : undefined;\n\n const rcloneHandle = await this.rclone.spawn({\n mountId: declaration.id,\n driverName: \"webdav\",\n mountPoint: targetDir,\n cacheDir,\n rcloneConfig,\n remote,\n vfsCacheMode,\n ...(cacheMaxSize !== undefined ? { cacheMaxSize } : {}),\n ...(cacheMaxAge !== undefined ? { cacheMaxAge } : {}),\n ...(vfsWriteBack !== undefined ? { vfsWriteBack } : {}),\n ...(refresh ? { onAuthError: () => refresh.onAuthError() } : {}),\n log: this.log,\n });\n\n this.log.info(\"mount ready\", { pid: rcloneHandle.pid });\n\n handleRef.current = rcloneHandle;\n refresh?.schedule(cred.expiresAt);\n\n const state: WebDAVState = {\n handleRef,\n refresh,\n authoritativeSize: (relPath: string) => {\n const h = handleRef.current;\n return h ? this.rclone.statSize(h, relPath) : Promise.resolve(null);\n },\n };\n return this.makeHandle(declaration, state, targetDir);\n }\n\n async disconnect(handle: ConnectorHandle): Promise<void> {\n const s = handle.state as WebDAVState;\n s.refresh?.cancel();\n if (s.fleetManaged || !s.handleRef.current) return;\n await this.rclone.stop(s.handleRef.current, { graceMs: 30_000 });\n }\n\n private async _sync(handle: ConnectorHandle, options?: SyncOptions): Promise<SyncResult> {\n const s = handle.state as WebDAVState;\n if (s.fleetManaged || !s.handleRef.current) {\n // Host fleet owns the rclone process; flushing is a fleet concern.\n options?.onSyncStatus?.({\n phase: \"initial_sync_complete\",\n totalFiles: 0,\n downloadedFiles: 0,\n stubFiles: 0,\n message: \"fleet-managed mount — flush handled by host\",\n });\n return { filesWritten: 0, filesDeleted: 0, bytesTransferred: 0 };\n }\n await this.rclone.flush(s.handleRef.current);\n options?.onSyncStatus?.({\n phase: \"initial_sync_complete\",\n totalFiles: 0,\n downloadedFiles: 0,\n stubFiles: 0,\n message: \"rclone flush complete\",\n });\n return { filesWritten: 0, filesDeleted: 0, bytesTransferred: 0 };\n }\n\n override async onHibernate(handle: ConnectorHandle): Promise<string | undefined> {\n const s = handle.state as WebDAVState;\n if (s.fleetManaged) return \"flushed\";\n await this._sync(handle);\n return \"flushed\";\n }\n\n override async onSessionClose(handle: ConnectorHandle): Promise<string | undefined> {\n const s = handle.state as WebDAVState;\n if (s.fleetManaged) return \"flushed\";\n await this._sync(handle);\n return \"flushed\";\n }\n}\n\n/**\n * Creates a new WebDAVConnector instance.\n * @returns Configured WebDAVConnector ready to be registered in the connector registry.\n * @docLink packages/factory-assets/api-reference#webdav-connector-factory\n */\nexport function createConnector(): WebDAVConnector {\n return new WebDAVConnector();\n}\n\n// ── helpers ────────────────────────────────────────────────────────────────\n\nfunction parseAuth(raw: string | undefined): ParsedAuth {\n const empty: ParsedAuth = {\n username: null,\n password: null,\n bearerToken: null,\n };\n if (!raw) return empty;\n\n const colonIdx = raw.indexOf(\":\");\n if (colonIdx === -1) {\n return { ...empty, bearerToken: raw };\n }\n\n const username = raw.slice(0, colonIdx);\n const password = raw.slice(colonIdx + 1);\n return { username, password, bearerToken: null };\n}\n\n/**\n * Run `rclone obscure <plain>` and return the trimmed stdout. rclone is\n * required at runtime for this driver and is provisioned in the agent\n * container Dockerfiles; surface a clear error if it is missing in\n * local-dev/test environments.\n */\nasync function obscurePassword(plain: string): Promise<string> {\n try {\n const { stdout } = await execFileP(\"rclone\", [\"obscure\", plain]);\n return stdout.trim();\n } catch (err) {\n const code = (err as NodeJS.ErrnoException)?.code;\n if (code === \"ENOENT\") {\n throw new Error(\n \"WebDAV connector: rclone binary not found on PATH (install rclone to use the webdav connector)\",\n );\n }\n throw new Error(\n `WebDAV connector: 'rclone obscure' failed: ${err instanceof Error ? err.message : String(err)}`,\n );\n }\n}\n","/**\n * XStateConnector — full state machine resource via XState v5.\n * Not mountable. Provides guarded transitions, entry/exit actions,\n * context, and serializable snapshots.\n *\n * Requires `xstate` (v5+) as an optional peer dependency.\n */\n\nimport { existsSync, readFileSync } from \"node:fs\";\nimport type {\n ConnectContext,\n ConnectorContent,\n ConnectorDeclaration,\n ConnectorEntry,\n ConnectorHandle,\n ListOptions,\n OperationDescriptor,\n SearchResult,\n ToolFace,\n} from \"@skaile/workspaces/connectors\";\nimport { AbstractConnector } from \"@skaile/workspaces/connectors\";\n\ninterface XStateState {\n actor: any; // XState Actor\n machine: any; // XState Machine (for introspection)\n definition: any; // Raw definition object\n history: Array<{ event: string; from: string; to: string; at: string }>;\n onChange?: (snapshot: { value: any; context: any }) => void;\n actions: Record<string, (...args: any[]) => void>;\n guards: Record<string, (...args: any[]) => boolean>;\n}\n\n/**\n * Connector for XState v5 state machines — drives guarded transitions, tracks history, and exposes\n * the current state and context to agents. Machine definitions can be provided inline or loaded\n * from a JSON/YAML file. Requires the `xstate` optional peer dependency.\n * @docLink packages/factory-assets/concepts#xstate-connector\n */\nexport class XStateConnector extends AbstractConnector {\n readonly name = \"xstate\";\n\n tools: ToolFace;\n\n constructor() {\n super();\n this.tools = {\n read: (handle, path) => this._read(handle, path),\n list: (handle, path, options) => this._list(handle, path, options),\n search: (handle, query) => this._search(handle, query),\n describeOperations: (handle) => this._describeOperations(handle),\n executeOp: (handle, operation, args) => this._executeOp(handle, operation, args),\n };\n }\n\n async connect(declaration: ConnectorDeclaration, _ctx: ConnectContext): Promise<ConnectorHandle> {\n this.log.info(\"connect\", { id: declaration.id });\n const xstatePkg = \"xstate\";\n const xstate = (await import(/* @vite-ignore */ xstatePkg)) as any;\n const { createMachine, createActor } = xstate;\n\n // Load machine definition\n let definition = declaration.options?.machine as Record<string, unknown> | undefined;\n if (!definition && declaration.options?.definitionPath) {\n const defPath = String(declaration.options.definitionPath);\n if (!existsSync(defPath)) throw new Error(`Machine definition not found: ${defPath}`);\n const raw = readFileSync(defPath, \"utf-8\");\n if (defPath.endsWith(\".json\")) {\n definition = JSON.parse(raw);\n } else {\n const { parse } = (await import(/* @vite-ignore */ \"yaml\")) as any;\n definition = parse(raw);\n }\n }\n\n if (!definition)\n throw new Error(\"XStateAdapter requires options.machine or options.definitionPath\");\n\n const state: XStateState = {\n actor: null,\n machine: null,\n definition,\n history: [],\n actions: {},\n guards: {},\n };\n\n // Build the machine — actions and guards are proxied so they can be\n // registered after connection (by the runner or Nuxt server)\n const actionProxy: Record<string, (...args: any[]) => void> = {};\n const guardProxy: Record<string, (...args: any[]) => boolean> = {};\n\n // Collect action/guard names from definition\n const actionNames = this.collectNames(definition, \"actions\");\n const guardNames = this.collectNames(definition, \"guard\");\n\n for (const name of actionNames) {\n actionProxy[name] = (...args: any[]) => {\n if (state.actions[name]) state.actions[name](...args);\n };\n }\n for (const name of guardNames) {\n guardProxy[name] = (...args: any[]) => {\n return state.guards[name] ? state.guards[name](...args) : true;\n };\n }\n\n const machineConfig = {\n ...definition,\n // Ensure context is an object\n context: definition.context ?? {},\n };\n\n const machine = createMachine(machineConfig, {\n actions: actionProxy,\n guards: guardProxy,\n });\n\n const actor = createActor(machine);\n\n // Track state changes\n actor.subscribe((snapshot: any) => {\n state.onChange?.({ value: snapshot.value, context: snapshot.context });\n });\n\n actor.start();\n\n state.actor = actor;\n state.machine = machine;\n\n return this.makeHandle(declaration, state);\n }\n\n async disconnect(handle: ConnectorHandle): Promise<void> {\n this.log.info(\"disconnect\");\n const s = handle.state as XStateState;\n try {\n s.actor?.stop();\n } finally {\n handle.status = \"disconnected\";\n }\n }\n\n private s(handle: ConnectorHandle): XStateState {\n return handle.state as XStateState;\n }\n\n /**\n * Register action implementations. Call after connect().\n */\n registerActions(\n handle: ConnectorHandle,\n actions: Record<string, (...args: any[]) => void>,\n ): void {\n Object.assign(this.s(handle).actions, actions);\n }\n\n /**\n * Register guard implementations. Call after connect().\n */\n registerGuards(\n handle: ConnectorHandle,\n guards: Record<string, (...args: any[]) => boolean>,\n ): void {\n Object.assign(this.s(handle).guards, guards);\n }\n\n /**\n * Register a callback fired on every state change.\n */\n onStateChange(\n handle: ConnectorHandle,\n cb: (snapshot: { value: any; context: any }) => void,\n ): void {\n this.s(handle).onChange = cb;\n }\n\n // ── Tool face methods (private, wired in constructor) ─────────────────────\n\n private async _read(handle: ConnectorHandle, path: string): Promise<ConnectorContent | null> {\n const snapshot = this.s(handle).actor.getSnapshot();\n if (path === \"\" || path === \"state\") {\n return { data: JSON.stringify(snapshot.value), contentType: \"application/json\" };\n }\n if (path === \"context\") {\n return { data: JSON.stringify(snapshot.context, null, 2), contentType: \"application/json\" };\n }\n // Read a specific context key\n const value = snapshot.context?.[path];\n if (value === undefined) return null;\n return { data: JSON.stringify(value), contentType: \"application/json\" };\n }\n\n private async _list(\n handle: ConnectorHandle,\n _path?: string,\n _options?: ListOptions,\n ): Promise<ConnectorEntry[]> {\n const snapshot = this.s(handle).actor.getSnapshot();\n const entries: ConnectorEntry[] = [\n { name: \"state\", path: \"state\", type: \"key\" },\n { name: \"context\", path: \"context\", type: \"key\" },\n ];\n if (snapshot.context && typeof snapshot.context === \"object\") {\n for (const key of Object.keys(snapshot.context)) {\n entries.push({ name: key, path: `context/${key}`, type: \"key\" });\n }\n }\n return entries;\n }\n\n private async _search(handle: ConnectorHandle, query: string): Promise<SearchResult[]> {\n const snapshot = this.s(handle).actor.getSnapshot();\n const full = JSON.stringify({ value: snapshot.value, context: snapshot.context });\n if (full.includes(query)) {\n return [{ path: \"state\", snippet: full.slice(0, 200) }];\n }\n return [];\n }\n\n private _describeOperations(handle: ConnectorHandle): OperationDescriptor[] {\n const ops: OperationDescriptor[] = [\n {\n name: \"get_state\",\n description: \"Get the current state value, context, and list of available transitions.\",\n accessLevel: \"read\",\n args: [],\n },\n {\n name: \"get_definition\",\n description: \"Get the machine definition (states, transitions, guards).\",\n accessLevel: \"read\",\n args: [],\n },\n {\n name: \"history\",\n description: \"Get the transition history log.\",\n accessLevel: \"read\",\n args: [\n {\n name: \"limit\",\n type: \"number\",\n required: false,\n description: \"Max entries (default: 50)\",\n },\n ],\n },\n {\n name: \"can\",\n description: \"Check if a specific event/transition is currently allowed.\",\n accessLevel: \"read\",\n args: [\n { name: \"event\", type: \"string\", required: true, description: \"Event type to check\" },\n ],\n },\n ];\n\n if (handle.access === \"read-write\") {\n ops.push({\n name: \"send\",\n description: \"Send an event to the state machine, triggering a transition if valid.\",\n accessLevel: \"write\",\n args: [\n {\n name: \"event\",\n type: \"string\",\n required: true,\n description: \"Event type (e.g., SUBMIT, APPROVE)\",\n },\n { name: \"data\", type: \"json\", required: false, description: \"Event payload data (JSON)\" },\n ],\n examples: [\"send --event APPROVE\", 'send --event SUBMIT --data \\'{\"reviewer\":\"alice\"}\\''],\n });\n }\n\n return ops;\n }\n\n private async _executeOp(\n handle: ConnectorHandle,\n operation: string,\n args: Record<string, unknown>,\n ): Promise<string> {\n const s = this.s(handle);\n\n switch (operation) {\n case \"get_state\": {\n const snapshot = s.actor.getSnapshot();\n const nextEvents = this.getAvailableEvents(handle);\n return JSON.stringify(\n {\n value: snapshot.value,\n context: snapshot.context,\n availableEvents: nextEvents,\n },\n null,\n 2,\n );\n }\n\n case \"get_definition\":\n return JSON.stringify(s.definition, null, 2);\n\n case \"history\": {\n const limit = Number(args.limit ?? 50);\n return JSON.stringify(s.history.slice(-limit), null, 2);\n }\n\n case \"can\": {\n const event = String(args.event ?? \"\");\n const snapshot = s.actor.getSnapshot();\n const can =\n snapshot.can?.({ type: event }) ?? this.getAvailableEvents(handle).includes(event);\n return JSON.stringify({ event, allowed: can });\n }\n\n case \"send\": {\n const eventType = String(args.event ?? args._positional ?? \"\");\n if (!eventType) return \"Error: event argument is required\";\n\n const snapshot = s.actor.getSnapshot();\n const fromState =\n typeof snapshot.value === \"string\" ? snapshot.value : JSON.stringify(snapshot.value);\n\n let eventPayload: Record<string, unknown> = { type: eventType };\n if (args.data) {\n const data = typeof args.data === \"string\" ? JSON.parse(args.data) : args.data;\n eventPayload = { type: eventType, ...data };\n }\n\n s.actor.send(eventPayload);\n\n const newSnapshot = s.actor.getSnapshot();\n const toState =\n typeof newSnapshot.value === \"string\"\n ? newSnapshot.value\n : JSON.stringify(newSnapshot.value);\n\n const transitioned = fromState !== toState;\n s.history.push({\n event: eventType,\n from: fromState,\n to: toState,\n at: new Date().toISOString(),\n });\n\n // Cap history\n if (s.history.length > 500) s.history = s.history.slice(-500);\n\n if (transitioned) {\n this.emitChange?.({ path: \"state\", action: \"edit\", source: \"operation\" });\n }\n\n return JSON.stringify(\n {\n transitioned,\n from: fromState,\n to: toState,\n context: newSnapshot.context,\n availableEvents: this.getAvailableEvents(handle),\n },\n null,\n 2,\n );\n }\n\n default:\n throw new Error(`XStateAdapter has no operation: ${operation}`);\n }\n }\n\n // ── Private helpers ────────────────────────────────────────────────────────\n\n private getAvailableEvents(handle: ConnectorHandle): string[] {\n const snapshot = this.s(handle).actor.getSnapshot();\n const currentState = typeof snapshot.value === \"string\" ? snapshot.value : null;\n if (!currentState) return [];\n const stateDef = this.s(handle).definition?.states?.[currentState];\n if (!stateDef?.on) return [];\n return Object.keys(stateDef.on);\n }\n\n /** Collect all named actions or guards from a machine definition tree. */\n private collectNames(def: any, key: \"actions\" | \"guard\"): string[] {\n const names = new Set<string>();\n const walk = (obj: any) => {\n if (!obj || typeof obj !== \"object\") return;\n if (key === \"actions\") {\n for (const field of [\"actions\", \"entry\", \"exit\"]) {\n const val = obj[field];\n if (typeof val === \"string\") names.add(val);\n if (Array.isArray(val))\n val.forEach((v: any) => {\n if (typeof v === \"string\") names.add(v);\n });\n }\n }\n if (key === \"guard\" && typeof obj.guard === \"string\") {\n names.add(obj.guard);\n }\n for (const v of Object.values(obj)) {\n if (v && typeof v === \"object\") walk(v);\n }\n };\n walk(def);\n return [...names];\n }\n}\n\n/**\n * Creates a new XStateConnector instance.\n * @returns Configured XStateConnector ready to be registered in the connector registry.\n * @docLink packages/factory-assets/api-reference#xstate-connector-factory\n */\nexport function createConnector(): XStateConnector {\n return new XStateConnector();\n}\n","/**\n * XStateStoreConnector — lightweight typed event store via @xstate/store.\n * Not mountable. Provides a shared event-driven store between UI and agents.\n *\n * Requires `@xstate/store` as an optional peer dependency.\n */\n\nimport type {\n ConnectContext,\n ConnectorContent,\n ConnectorDeclaration,\n ConnectorEntry,\n ConnectorHandle,\n ListOptions,\n OperationDescriptor,\n SearchOptions,\n SearchResult,\n ToolFace,\n} from \"@skaile/workspaces/connectors\";\nimport { AbstractConnector } from \"@skaile/workspaces/connectors\";\n\ninterface StoreState {\n store: any; // @xstate/store Store instance\n history: Array<{ event: string; payload: unknown; at: string }>;\n onChange?: (snapshot: Record<string, unknown>) => void;\n}\n\n/**\n * Connector for `@xstate/store` — a lightweight event-driven key-value store shared between agents and UI clients.\n * Provides get, set, merge, and reset operations with an event history log. Requires the `@xstate/store` optional peer dependency.\n * @docLink packages/factory-assets/concepts#xstate-store-connector\n */\nexport class XStateStoreConnector extends AbstractConnector {\n readonly name = \"xstate-store\";\n\n tools: ToolFace;\n\n constructor() {\n super();\n this.tools = {\n read: (handle, path) => this._read(handle, path),\n write: (handle, path, content) => this._write(handle, path, content),\n delete: (handle, path) => this._delete(handle, path),\n list: (handle, path, options) => this._list(handle, path, options),\n search: (handle, query, options) => this._search(handle, query, options),\n describeOperations: (handle) => this._describeOperations(handle),\n executeOp: (handle, operation, args) => this._executeOp(handle, operation, args),\n };\n }\n\n async connect(declaration: ConnectorDeclaration, _ctx: ConnectContext): Promise<ConnectorHandle> {\n this.log.info(\"connect\", { id: declaration.id });\n const { createStore } = (await import(\"@xstate/store\")) as any;\n\n const initial = (declaration.options?.initial as Record<string, unknown>) ?? {};\n\n // Create a dynamic store that accepts get/set/merge/delete events\n const store = createStore({\n context: { ...initial },\n on: {\n set: (ctx: Record<string, unknown>, event: { key: string; value: unknown }) => ({\n ...ctx,\n [event.key]: event.value,\n }),\n merge: (ctx: Record<string, unknown>, event: { data: Record<string, unknown> }) => ({\n ...ctx,\n ...event.data,\n }),\n delete: (ctx: Record<string, unknown>, event: { key: string }) => {\n const next = { ...ctx };\n delete next[event.key];\n return next;\n },\n reset: (_ctx: Record<string, unknown>, event: { initial?: Record<string, unknown> }) => ({\n ...(event.initial ?? initial),\n }),\n },\n });\n\n const state: StoreState = { store, history: [] };\n\n // Wire up subscription for change notifications\n store.subscribe((snapshot: any) => {\n state.onChange?.(snapshot.context);\n });\n\n return this.makeHandle(declaration, state);\n }\n\n async disconnect(handle: ConnectorHandle): Promise<void> {\n this.log.info(\"disconnect\");\n handle.status = \"disconnected\";\n }\n\n private storeState(handle: ConnectorHandle): StoreState {\n return handle.state as StoreState;\n }\n\n private context(handle: ConnectorHandle): Record<string, unknown> {\n return this.storeState(handle).store.getSnapshot().context;\n }\n\n /**\n * Register a callback fired on every state change.\n */\n onStoreChange(handle: ConnectorHandle, cb: (snapshot: Record<string, unknown>) => void): void {\n (handle.state as StoreState).onChange = cb;\n }\n\n // ── Tool face methods (private, wired in constructor) ─────────────────────\n\n private async _read(handle: ConnectorHandle, path: string): Promise<ConnectorContent | null> {\n const ctx = this.context(handle);\n if (path === \"*\") {\n if (Object.keys(ctx).length === 0) return null;\n return { data: JSON.stringify(ctx, null, 2), contentType: \"application/json\" };\n }\n const value = ctx[path];\n if (value === undefined) return null;\n return { data: JSON.stringify(value), contentType: \"application/json\" };\n }\n\n private async _write(\n handle: ConnectorHandle,\n path: string,\n content: ConnectorContent,\n ): Promise<void> {\n const data = typeof content.data === \"string\" ? content.data : content.data.toString(\"utf-8\");\n let value: unknown;\n try {\n value = JSON.parse(data);\n } catch {\n value = data;\n }\n this.storeState(handle).store.send({ type: \"set\", key: path, value });\n this._recordHistory(handle, \"set\", { key: path, value });\n }\n\n private async _delete(handle: ConnectorHandle, path: string): Promise<boolean> {\n const ctx = this.context(handle);\n if (!(path in ctx)) return false;\n this.storeState(handle).store.send({ type: \"delete\", key: path });\n this._recordHistory(handle, \"delete\", { key: path });\n return true;\n }\n\n private async _list(\n handle: ConnectorHandle,\n _path?: string,\n options?: ListOptions,\n ): Promise<ConnectorEntry[]> {\n const ctx = this.context(handle);\n let keys = Object.keys(ctx);\n if (options?.glob) {\n // Escape regex metacharacters before substituting the `*` wildcard so a\n // glob like \"a.b*\" matches literally rather than as a regex.\n const escaped = options.glob.replace(/[.+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n const regex = new RegExp(`^${escaped.replace(/\\*/g, \".*\")}$`);\n keys = keys.filter((k) => regex.test(k));\n }\n if (options?.limit) keys = keys.slice(0, options.limit);\n return keys.map((k) => ({ name: k, path: k, type: \"key\" as const }));\n }\n\n private async _search(\n handle: ConnectorHandle,\n query: string,\n options?: SearchOptions,\n ): Promise<SearchResult[]> {\n const ctx = this.context(handle);\n const results: SearchResult[] = [];\n for (const [key, value] of Object.entries(ctx)) {\n if (options?.maxResults && results.length >= options.maxResults) break;\n const str = JSON.stringify(value);\n if (key.includes(query) || str.includes(query)) {\n results.push({ path: key, snippet: str.slice(0, 200) });\n }\n }\n return results;\n }\n\n private _describeOperations(handle: ConnectorHandle): OperationDescriptor[] {\n const ops: OperationDescriptor[] = [\n {\n name: \"get\",\n description: \"Get the full store snapshot (all keys and values).\",\n accessLevel: \"read\",\n args: [],\n },\n {\n name: \"get_key\",\n description: \"Get a single value by key.\",\n accessLevel: \"read\",\n args: [{ name: \"key\", type: \"string\", required: true, description: \"Key name\" }],\n },\n {\n name: \"history\",\n description: \"Get the event history log.\",\n accessLevel: \"read\",\n args: [\n {\n name: \"limit\",\n type: \"number\",\n required: false,\n description: \"Max entries (default: 50)\",\n },\n ],\n },\n ];\n\n if (handle.access === \"read-write\") {\n ops.push(\n {\n name: \"set\",\n description: \"Set a key to a value.\",\n accessLevel: \"write\",\n args: [\n { name: \"key\", type: \"string\", required: true, description: \"Key name\" },\n {\n name: \"value\",\n type: \"string\",\n required: true,\n description: \"Value (JSON-encoded for objects)\",\n },\n ],\n examples: [\"set --key theme --value '\\\"dark\\\"'\", \"set --key count --value 42\"],\n },\n {\n name: \"merge\",\n description: \"Merge an object into the store context (shallow merge).\",\n accessLevel: \"write\",\n args: [\n {\n name: \"data\",\n type: \"json\",\n required: true,\n description: \"JSON object to merge into context\",\n },\n ],\n examples: ['merge --data \\'{\"theme\":\"dark\",\"locale\":\"de\"}\\''],\n },\n {\n name: \"delete\",\n description: \"Delete a single key from the store context.\",\n accessLevel: \"write\",\n args: [\n { name: \"key\", type: \"string\", required: true, description: \"Key name to delete\" },\n ],\n examples: [\"delete --key theme\"],\n },\n {\n name: \"reset\",\n description: \"Reset the store to its initial context.\",\n accessLevel: \"write\",\n args: [],\n },\n );\n }\n\n return ops;\n }\n\n private async _executeOp(\n handle: ConnectorHandle,\n operation: string,\n args: Record<string, unknown>,\n ): Promise<string> {\n switch (operation) {\n case \"get\":\n return this._opGet(handle);\n case \"get_key\":\n return this._opGetKey(handle, args);\n case \"history\":\n return this._opHistory(handle, args);\n case \"set\":\n return this._opSet(handle, args);\n case \"merge\":\n return this._opMerge(handle, args);\n case \"delete\":\n return this._opDelete(handle, args);\n case \"reset\":\n return this._opReset(handle);\n default:\n throw new Error(`XStateStoreConnector has no operation: ${operation}`);\n }\n }\n\n private _opGet(handle: ConnectorHandle): string {\n return JSON.stringify(this.context(handle), null, 2);\n }\n\n private _opGetKey(handle: ConnectorHandle, args: Record<string, unknown>): string {\n const key = String(args.key ?? \"\");\n const value = this.context(handle)[key];\n return value !== undefined ? JSON.stringify(value) : \"\";\n }\n\n private _opHistory(handle: ConnectorHandle, args: Record<string, unknown>): string {\n const s = this.storeState(handle);\n const limit = Number(args.limit ?? 50);\n return JSON.stringify(s.history.slice(-limit), null, 2);\n }\n\n private _opSet(handle: ConnectorHandle, args: Record<string, unknown>): string {\n const s = this.storeState(handle);\n const key = String(args.key ?? \"\");\n let value: unknown = args.value;\n if (typeof value === \"string\") {\n try {\n value = JSON.parse(value);\n } catch {\n /* keep as string */\n }\n }\n const hadKey = key in this.context(handle);\n s.store.send({ type: \"set\", key, value });\n this._recordHistory(handle, \"set\", { key, value });\n this.emitChange?.({ path: key, action: hadKey ? \"edit\" : \"create\", source: \"operation\" });\n return \"OK\";\n }\n\n private _opMerge(handle: ConnectorHandle, args: Record<string, unknown>): string {\n const s = this.storeState(handle);\n let data = args.data;\n if (typeof data === \"string\") data = JSON.parse(data);\n s.store.send({ type: \"merge\", data });\n this._recordHistory(handle, \"merge\", { data });\n if (typeof data === \"object\" && data !== null) {\n const ctx = this.context(handle);\n for (const key of Object.keys(data as Record<string, unknown>)) {\n this.emitChange?.({\n path: key,\n action: key in ctx ? \"edit\" : \"create\",\n source: \"operation\",\n });\n }\n }\n return \"OK\";\n }\n\n private _opDelete(handle: ConnectorHandle, args: Record<string, unknown>): string {\n const s = this.storeState(handle);\n // Mirrors the tool-face `_delete`: skip absent keys (no phantom history\n // or broadcast), else mutate the store, record, and emit the change.\n const key = String(args.key ?? \"\");\n if (!(key in this.context(handle))) return \"OK\";\n s.store.send({ type: \"delete\", key });\n this._recordHistory(handle, \"delete\", { key });\n this.emitChange?.({ path: key, action: \"delete\", source: \"operation\" });\n return \"OK\";\n }\n\n private _opReset(handle: ConnectorHandle): string {\n const s = this.storeState(handle);\n s.store.send({ type: \"reset\" });\n s.history = [];\n this.emitChange?.({ path: \"\", action: \"edit\", source: \"operation\" });\n return \"OK\";\n }\n\n private _recordHistory(handle: ConnectorHandle, event: string, payload: unknown): void {\n const s = this.storeState(handle);\n s.history.push({ event, payload, at: new Date().toISOString() });\n if (s.history.length > 500) s.history = s.history.slice(-500);\n }\n}\n\n/**\n * Creates a new XStateStoreConnector instance.\n * @returns Configured XStateStoreConnector ready to be registered in the connector registry.\n * @docLink packages/factory-assets/api-reference#xstate-store-connector-factory\n */\nexport function createConnector(): XStateStoreConnector {\n return new XStateStoreConnector();\n}\n","/**\n * Connector registry.\n *\n * Built-in connectors from `@skaile/workspaces/factory-assets` are registered here\n * via static ESM imports of their subpath exports so they are bundled into any\n * `bun --compile`'d agent binary AND any tsup-emitted ESM tarball. Each built-in\n * factory is wrapped in a `ConnectorTarget` and registered into the unified\n * `pluginRegistry` (`@skaile/workspaces/plugin-registry`). The public read\n * helpers (`getConnector` / `tryGetConnector` / `listConnectors`) are thin\n * kind-typed wrappers over that registry.\n *\n * The catalog path in `ConnectorManager.resolveConnector`\n * (`await import(connectorPath)` of raw TS) is a dev-only fallback for\n * project-local third-party connectors — it cannot work inside a compiled\n * binary because bun cannot share its bundled symbol graph with\n * externally-loaded TS files (the import silently hangs while trying to\n * resolve `@skaile/workspaces/connectors` against an absent `node_modules`).\n *\n * **Static import discipline.** Every subpath specifier below must be a\n * string-literal `from \"@skaile/workspaces/factory-assets/connectors/<name>\"` —\n * never aliased through a variable. Indirection defeats `bun --compile`'s\n * static analysis and silently drops the module from the binary.\n * Regression test: `tests/connector-tools-regression.test.ts`.\n */\n\nimport { createConnector as createDeployConnector } from \"@skaile/workspaces/factory-assets/connectors/deploy\";\n// Service connectors (migrated in Task 9)\nimport { createConnector as createDevserverConnector } from \"@skaile/workspaces/factory-assets/connectors/devserver\";\n// State connectors (migrated in Task 8)\nimport { createConnector as createFlowConnector } from \"@skaile/workspaces/factory-assets/connectors/flow\";\n\n// Static subpath imports — string literals only.\n// Filesystem-face connectors (mount drivers migrated in Task 6)\nimport { createConnector as createGitConnector } from \"@skaile/workspaces/factory-assets/connectors/git\";\nimport { createConnector as createGmailConnector } from \"@skaile/workspaces/factory-assets/connectors/gmail\";\nimport { createConnector as createGoogleDriveConnector } from \"@skaile/workspaces/factory-assets/connectors/googledrive\";\nimport { createConnector as createLocalConnector } from \"@skaile/workspaces/factory-assets/connectors/local\";\nimport { createConnector as createMattermostConnector } from \"@skaile/workspaces/factory-assets/connectors/mattermost\";\n// Data connectors (migrated in Task 7)\nimport { createConnector as createMemoryConnector } from \"@skaile/workspaces/factory-assets/connectors/memory\";\nimport { createConnector as createMinioConnector } from \"@skaile/workspaces/factory-assets/connectors/minio\";\nimport { createConnector as createPostgresConnector } from \"@skaile/workspaces/factory-assets/connectors/postgres\";\nimport { createConnector as createS3Connector } from \"@skaile/workspaces/factory-assets/connectors/s3\";\nimport { createConnector as createSharepointConnector } from \"@skaile/workspaces/factory-assets/connectors/sharepoint\";\nimport { createConnector as createSqliteConnector } from \"@skaile/workspaces/factory-assets/connectors/sqlite\";\n// Subpath and registry key (CONNECTOR.md `name:`) are both `static-server`.\nimport { createConnector as createStaticConnector } from \"@skaile/workspaces/factory-assets/connectors/static-server\";\nimport { createConnector as createTunnelConnector } from \"@skaile/workspaces/factory-assets/connectors/tunnel\";\nimport { createConnector as createWebdavConnector } from \"@skaile/workspaces/factory-assets/connectors/webdav\";\nimport { createConnector as createXstateConnector } from \"@skaile/workspaces/factory-assets/connectors/xstate\";\nimport { createConnector as createXstateStoreConnector } from \"@skaile/workspaces/factory-assets/connectors/xstate-store\";\nimport {\n type ConnectorTarget,\n type PluginRegistry,\n pluginRegistry,\n} from \"@skaile/workspaces/plugin-registry\";\nimport * as z from \"zod\";\nimport type { Connector, ConnectorFactory } from \"./connector-types.js\";\n\n// ── Unified Connector registry ───────────────────────────────────────────────\n// Built-ins are stored in the shared pluginRegistry under the \"connector\" kind.\n\n/**\n * Static metadata for every built-in connector — pure data, no imports.\n *\n * Mirrors the ids registered by {@link registerBuiltinConnectors}; selection UIs\n * use it to enumerate the built-in set without loading any connector module\n * (parity with `BUILTIN_DRIVER_CATALOG`).\n *\n * @docLink packages/connectors/api-reference#builtin-connector-catalog\n */\nexport const BUILTIN_CONNECTOR_CATALOG: readonly { id: string; displayName: string }[] = [\n { id: \"git\", displayName: \"git\" },\n { id: \"local\", displayName: \"local\" },\n { id: \"s3\", displayName: \"s3\" },\n { id: \"webdav\", displayName: \"webdav\" },\n { id: \"sharepoint\", displayName: \"sharepoint\" },\n { id: \"googledrive\", displayName: \"googledrive\" },\n { id: \"memory\", displayName: \"memory\" },\n { id: \"postgres\", displayName: \"postgres\" },\n { id: \"sqlite\", displayName: \"sqlite\" },\n { id: \"minio\", displayName: \"minio\" },\n { id: \"flow\", displayName: \"flow\" },\n { id: \"xstate\", displayName: \"xstate\" },\n { id: \"xstate-store\", displayName: \"xstate-store\" },\n { id: \"devserver\", displayName: \"devserver\" },\n { id: \"static-server\", displayName: \"static-server\" },\n { id: \"tunnel\", displayName: \"tunnel\" },\n { id: \"deploy\", displayName: \"deploy\" },\n { id: \"gmail\", displayName: \"gmail\" },\n { id: \"mattermost\", displayName: \"mattermost\" },\n];\n\n/**\n * Build a `ConnectorTarget` wrapping an existing connector factory.\n *\n * Connectors take no construct-time config, so `configSchema` is a passthrough\n * and `create()` simply calls the factory. Lifecycle config arrives later via\n * `Connector.connect(declaration, ctx)`.\n */\nfunction connectorTargetFromFactory(id: string, factory: ConnectorFactory): ConnectorTarget {\n return {\n id,\n displayName: id,\n apiVersion: 1,\n configSchema: z.unknown(),\n create: (_config, _ctx) => factory(),\n };\n}\n\nlet _connectorsRegistered = false;\n\n/**\n * Register every built-in connector into the plugin registry.\n *\n * **Static import discipline.** Every subpath specifier in this file must be a\n * string-literal `from \"@skaile/workspaces/factory-assets/connectors/<name>\"` —\n * never aliased through a variable. Indirection defeats `bun --compile`'s\n * static analysis and silently drops the module from the binary.\n *\n * Idempotent: guarded by a module flag so a second call is a no-op (a duplicate\n * `register` would otherwise throw `RegistrationError`).\n *\n * @docLink packages/connectors/api-reference#register-builtin-connectors\n */\nexport function registerBuiltinConnectors(registry: PluginRegistry = pluginRegistry): void {\n if (registry === pluginRegistry && _connectorsRegistered) return;\n\n const reg = (id: string, factory: ConnectorFactory): void => {\n if (registry.get(\"connector\", id)) return;\n registry.register(\"connector\", connectorTargetFromFactory(id, factory));\n };\n\n // Filesystem-face connectors (former mount drivers, migrated in Task 6)\n reg(\"git\", () => createGitConnector());\n reg(\"local\", () => createLocalConnector());\n reg(\"s3\", () => createS3Connector());\n reg(\"webdav\", () => createWebdavConnector());\n reg(\"sharepoint\", () => createSharepointConnector());\n reg(\"googledrive\", () => createGoogleDriveConnector());\n\n // Data connectors (migrated in Task 7)\n reg(\"memory\", () => createMemoryConnector());\n reg(\"postgres\", () => createPostgresConnector());\n reg(\"sqlite\", () => createSqliteConnector());\n reg(\"minio\", () => createMinioConnector());\n\n // State connectors (migrated in Task 8)\n reg(\"flow\", () => createFlowConnector());\n reg(\"xstate\", () => createXstateConnector());\n reg(\"xstate-store\", () => createXstateStoreConnector());\n\n // Service connectors (migrated in Task 9)\n reg(\"devserver\", () => createDevserverConnector());\n // Subpath and registry key (CONNECTOR.md `name:`) are both `static-server`.\n reg(\"static-server\", () => createStaticConnector());\n reg(\"tunnel\", () => createTunnelConnector());\n reg(\"deploy\", () => createDeployConnector());\n\n // Integration connectors (migrated in Task 10)\n reg(\"gmail\", () => createGmailConnector());\n reg(\"mattermost\", () => createMattermostConnector());\n\n if (registry === pluginRegistry) _connectorsRegistered = true;\n}\n\n/**\n * Get a connector by name, calling its target's factory to produce a fresh\n * instance. Ensures the built-ins are registered first (cheap, idempotent).\n * @param name - Connector key (e.g. `\"postgres\"`).\n * @returns A fresh `Connector` instance.\n * @throws {Error} when no connector is registered under `name`.\n * @docLink packages/connectors/api-reference#get-connector\n */\nexport function getConnector(name: string): Connector {\n ensureBuiltinsRegistered();\n const target = pluginRegistry.get(\"connector\", name);\n if (!target) {\n const available = pluginRegistry\n .list(\"connector\")\n .map((m) => m.id)\n .join(\", \");\n throw new Error(`Unknown connector: \"${name}\". Available: ${available || \"none\"}`);\n }\n return target.create({}, {});\n}\n\n/**\n * Get a connector by name, or return `undefined` if not registered. Ensures the\n * built-ins are registered first (cheap, idempotent).\n * @param name - Connector key.\n * @returns A fresh `Connector` instance or `undefined`.\n * @docLink packages/connectors/api-reference#try-get-connector\n */\nexport function tryGetConnector(name: string): Connector | undefined {\n ensureBuiltinsRegistered();\n return pluginRegistry.get(\"connector\", name)?.create({}, {});\n}\n\n/**\n * Return the names of all currently registered connectors. Ensures the built-ins\n * are registered first (cheap, idempotent).\n * @returns Array of connector keys.\n * @docLink packages/connectors/api-reference#list-connectors\n */\nexport function listConnectors(): string[] {\n ensureBuiltinsRegistered();\n return pluginRegistry.list(\"connector\").map((m) => m.id);\n}\n\n/**\n * Lazily register the built-ins unless they have already been registered.\n *\n * Production registers them eagerly at startup (`serve.ts`, connector-manager);\n * this is the cheap safety net for callers / tests that look a connector up\n * before that startup hook runs. Gating on the `_connectorsRegistered` flag\n * (not registry emptiness) keeps built-ins available even when a third-party\n * connector plugin registered first — an empty-check would skip the built-ins\n * entirely and make `getConnector(\"git\")` fail. `registerBuiltinConnectors`\n * skips ids already present, so a pre-seeded fake is never clobbered.\n */\nfunction ensureBuiltinsRegistered(): void {\n if (!_connectorsRegistered) {\n registerBuiltinConnectors();\n }\n}\n","/**\n * Connector adapter infrastructure types.\n *\n * Connectors are external backends (databases, KV stores, object stores,\n * in-process state, git repos, etc.). A connector exposes up to two faces: a\n * `ToolFace` (agents access it through injected tools) and/or a\n * `FilesystemFace` (the connector projects content into a mounted directory).\n *\n * @docLink packages/connectors/concepts#connector-types\n */\n\nimport type {\n ConnectorContent,\n ConnectorEntry,\n ListOptions,\n OperationDescriptor,\n SearchOptions,\n SearchResult,\n SyncOptions,\n SyncResult,\n WatchHandle,\n WatchOptions,\n} from \"./shared-types.js\";\n\nexport type { OperationDescriptor } from \"./shared-types.js\";\n\nimport type { Logger } from \"@skaile/workspaces/types\";\nimport type { SecretProvider } from \"./secrets.js\";\n\n// ── Connector declaration (runtime config, resolved from skaile.yaml) ────────\n\n/**\n * Parsed connector configuration from `skaile.yaml`, passed to `ConnectorAdapter.connect()` and held by `ConnectorManager`.\n * @docLink packages/connectors/concepts#connector-declaration\n */\nexport interface ConnectorDeclaration {\n /** Unique identifier for this connector instance. */\n id: string;\n /** Driver type: \"postgres\", \"redis\", \"memory\", \"xstate\", \"yjs\", etc. */\n driver: string;\n /**\n * Human-readable connection name, projected from the materialized CONNECTOR.md\n * frontmatter `label`. The platform resource-explorer tab renders this over the\n * driver name when present; absent for connectors with no configured name.\n */\n label?: string;\n /** Access level enforced by the manager. */\n access: \"read-only\" | \"read-write\";\n /** Credential reference: \"env:VAR_NAME\" or inline value. */\n auth?: string;\n /**\n * Backend provider link id for `auth: \"backend\"` connectors. The runner's\n * token-refresh mediator passes this as the `host.refresh_credential` `id` so\n * the platform resolves the credential against the right provider link.\n */\n providerLinkId?: string;\n /**\n * Operating mode for connectors that manage a working copy. Orthogonal to\n * faces. `agent` = the agent drives the source natively (e.g. native git) and\n * the connector only provisions short-lived credentials. `sync` = the\n * connector owns the working copy (clone + watch + auto-commit/pull). Absent =\n * the driver's legacy `options.{session,sync,lifecycle}` blocks decide.\n */\n mode?: \"agent\" | \"sync\";\n /** Driver-specific configuration. */\n options?: Record<string, unknown>;\n /**\n * Owner-authored instruction text projected from the materialized\n * CONNECTOR.md body (preset custom instructions). Injected eagerly into the\n * agent system prompt. Absent when the body is empty.\n */\n instructions?: string;\n /** Filesystem-face config — only meaningful for mountable connectors. */\n mount?: {\n /** Source URL or path (repo URL, bucket name, host path). */\n source: string;\n /** Override mount target directory (default: `.mounts/<id>/`). */\n target?: string;\n /** Watch flag: omitted → watch read-write, skip read-only. */\n watch?: boolean;\n /** Expert-only: expose the resolved credential to the agent CLI. */\n exposeAccessToken?: boolean;\n /** Optional access-token TTL override (seconds). */\n accessTokenTTL?: number;\n };\n}\n\n// ── Connector handle (returned by adapter.connect) ───────────────────────────\n\n/**\n * Live state of a connected backend, returned by `Connector.connect()` (or the\n * legacy `ConnectorAdapter.connect()`) and held by `ConnectorManager`.\n * @docLink packages/connectors/concepts#connector-handle\n */\nexport interface ConnectorHandle {\n /** Connector declaration ID. */\n readonly id: string;\n /** Driver name. */\n readonly driver: string;\n /** Effective access level. */\n readonly access: \"read-only\" | \"read-write\";\n /** Lifecycle status. Set by every `Connector`. */\n status: \"connecting\" | \"connected\" | \"error\" | \"disconnected\";\n /** Present iff the connector has a filesystem face and is mounted. */\n mountPath?: string;\n /** Adapter-specific state (connection pool, client, etc.). Opaque to callers. */\n state: unknown;\n}\n\n/**\n * Optional capability a filesystem-face connector attaches to its\n * {@link ConnectorHandle.state}, letting the mount read path gate a read\n * against the authoritative remote byte size.\n *\n * rclone's VFS can serve a non-truncated cache item after a remote file is\n * replaced by a *shorter* version — the read returns `[new bytes][leftover\n * tail of the older, longer version]` and `statSync` reports the inflated size,\n * so the on-disk length is not a signal the read path can trust. An\n * implementation returns the true remote size for a mount-relative path by\n * querying the backend directly (bypassing the VFS cache), or `null` when it\n * can't be determined — in which case the read falls back to the on-disk bytes.\n *\n * The read path duck-types `handle.state` for this method; a connector opts in\n * by attaching it. rclone-backed mounts (sharepoint / webdav / googledrive)\n * wire it to `RcloneProcessManager.statSize`.\n */\nexport interface AuthoritativeSizeProvider {\n authoritativeSize(relPath: string): Promise<number | null>;\n}\n\n// ── Connector change event ────────────────────────────────────────────────────\n\n/**\n * Change event emitted by a connector adapter's `watch()` implementation.\n * @docLink packages/connectors/concepts#connector-change-event\n */\nexport interface ConnectorChangeEvent {\n /** Relative path, key, table name, node ID, etc. */\n path: string;\n /** What happened. */\n action: \"create\" | \"edit\" | \"delete\" | \"conflict\";\n /** What caused the change. */\n source: \"filesystem\" | \"operation\" | \"remote\" | \"sync\";\n}\n\n// ── ConnectorManager info ────────────────────────────────────────────────────\n\n/**\n * Summary of a connected connector returned by `ConnectorManager.listConnectors()`.\n * @docLink packages/connectors/concepts#connector-info\n */\nexport interface ConnectorInfo {\n id: string;\n driver: string;\n /** Human-readable connection name; the resource-explorer tab renders this over `id`/`driver` when present. */\n label?: string;\n access: \"read-only\" | \"read-write\";\n /** Operation names this connector exposes as agent tools (via describeOperations). */\n operations: string[];\n}\n\n/**\n * Bulk connect/disconnect result returned by `ConnectorManager.connectAll()` and `disconnectAll()`.\n * @docLink packages/connectors/concepts#connector-report\n */\nexport interface ConnectorReport {\n results: Array<{ id: string; connected: boolean; error?: string }>;\n}\n\n// ── Field spec (connector credential/config declarations) ────────────────────\n\n/**\n * Input types for `ConnectorFieldSpec`. Controls validation rules and the Forge UI affordance.\n * @docLink packages/connectors/concepts#field-type\n */\nexport type FieldType =\n | \"text\" // plain string\n | \"password\" // sensitive; always stored via SecretProvider\n | \"api-key\" // alias for password with specific UI affordance\n | \"url\" // validated URL string\n | \"oauth\" // triggers OAuth flow; oauthService required\n | \"select\" // enum; choices required and non-empty\n | \"boolean\" // default must be \"true\" or \"false\" if provided\n | \"number\"; // default must be a parseable numeric string if provided\n\n/**\n * Declares one credential or configuration field that a connector adapter requires.\n * Used by `ConnectorManager.resolveFields()` and the Forge settings UI.\n * @docLink packages/connectors/concepts#connector-field-spec\n */\nexport interface ConnectorFieldSpec {\n /** Machine name used as the options key in skaile.yaml. */\n key: string;\n /** Human-readable label for the forge settings UI. */\n label: string;\n /** Tooltip / help text. */\n description?: string;\n /** Input type. Controls validation rules and UI affordance in the forge settings panel. */\n type: FieldType;\n /** Whether the adapter refuses to connect when this field is missing. */\n required: boolean;\n /** String fallback used when not provided and not required. */\n default?: string;\n /** Forge UI masks the value; value is never logged. */\n sensitive: boolean;\n /** UI grouping: \"Authentication\", \"Connection\", \"Options\". */\n group?: string;\n /**\n * Required when type === \"select\"; must be non-empty.\n */\n choices?: string[];\n /**\n * Required when type === \"oauth\".\n * Identifies the OAuth service, e.g. \"google\".\n * Used to call OAuthSecretProvider.initiateFlow(oauthService, account).\n * oauth fields must be declared AFTER any field they reference (e.g., \"account\").\n */\n oauthService?: string;\n /** Example value shown as placeholder text in the forge settings UI. */\n example?: string;\n}\n\n/**\n * Thrown by `ConnectorManager.connectAll()` and `resolveFields()` when a required\n * adapter field cannot be resolved through the `SecretProviderChain`. Carries the\n * connector ID, the missing field spec, the ref that was tried, and the available\n * providers for actionable error messages.\n * @docLink packages/connectors/concepts#connector-field-missing-error\n */\nexport class ConnectorFieldMissingError extends Error {\n readonly connectorId: string;\n readonly field: ConnectorFieldSpec;\n readonly triedRef: string;\n readonly availableProviders: string[];\n\n constructor(opts: {\n connectorId: string;\n field: ConnectorFieldSpec;\n triedRef: string;\n availableProviders: string[];\n }) {\n super(\n `Connector \"${opts.connectorId}\" is missing required field \"${opts.field.key}\" ` +\n `(tried: ${opts.triedRef || \"(none)\"}). ` +\n `Available providers: ${opts.availableProviders.join(\", \") || \"(none)\"}`,\n );\n this.name = \"ConnectorFieldMissingError\";\n this.connectorId = opts.connectorId;\n this.field = opts.field;\n this.triedRef = opts.triedRef;\n this.availableProviders = opts.availableProviders;\n }\n}\n\n// ── Runtime skill descriptor ──────────────────────────────────────────────────\n\n/**\n * Instance-specific skill descriptor returned by `ConnectorAdapter.describeSkill()`.\n * Returned by `ConnectorManager.listSkills()` to surface connector capabilities to the agent.\n * @docLink packages/connectors/concepts#runtime-skill-descriptor\n */\nexport interface RuntimeSkillDescriptor {\n /** Connector instance id, e.g. \"gmail-work\". */\n id: string;\n /** Short label: \"Gmail — work@company.com\". */\n name: string;\n /** Instance-specific description: \"Read and write email for work@company.com\". */\n description: string;\n /** Category for grouping in the forge UI. */\n category: string;\n access: \"read-only\" | \"read-write\";\n /** Operation names (without loading full defs) for agent planning. */\n toolNames: string[];\n}\n\n// ── Token mediator (Tier-2 credential mediation) ─────────────────────────────\n\n/**\n * Result of a single `TokenMediator` call. Mirrors\n * `AccessTokenResponseEvent.result` from `@skaile/workspaces/types` so the runner\n * can pass it straight through.\n *\n * @docLink packages/connectors/api-reference#token-mediator\n */\nexport type TokenMediatorResult =\n | {\n ok: true;\n /** Access token to use for the next git operation. */\n token: string;\n /**\n * ISO-8601 expiry, or `null` for indefinite tokens (static PATs). Drives\n * whether the driver schedules a refresh tick.\n */\n expiresAt: string | null;\n /** Optional scope/permissions list, surfaced in audit logs. */\n scope?: string[];\n }\n | {\n ok: false;\n code: \"not-configured\" | \"revoked\" | \"provider-error\" | \"backend-error\" | \"timeout\";\n /** Human-readable detail, never carries secrets. */\n message: string;\n };\n\n/**\n * Function signature mountable connectors use to acquire a fresh access token\n * from the runner-owned backend mediator. Implemented by the runner: emits a\n * `request_access_token` command over the transport and resolves with the\n * matching `access_token_response` payload.\n *\n * Connectors MUST treat this as the only token source when the parsed\n * `MountAuthRef.kind === 'backend'`. Local minting (PAT, OAuth, GitHub App)\n * has been removed from the runner — provider dispatch lives on the platform.\n *\n * @docLink packages/connectors/api-reference#token-mediator\n */\nexport type TokenMediator = (input: {\n connectorId: string;\n reason: \"initial\" | \"refresh\" | \"retry-401\";\n /**\n * Connector driver, used by the runner mediator to pick the platform refresh\n * `kind`; absent on `initial` and for legacy callers.\n */\n driver?: string;\n /**\n * Backend provider link id — the `id` the platform `host.refresh_credential`\n * capability resolves the credential against. Absent on `initial` and for\n * legacy callers.\n */\n providerLinkId?: string;\n}) => Promise<TokenMediatorResult>;\n\n// ── Unified connector types ───────────────────────────────────────────────────\n\n/**\n * Context passed to `Connector.connect()` by `ConnectorManager`.\n * @docLink packages/connectors/concepts#connect-context\n */\nexport interface ConnectContext {\n /** Secret provider for resolving credential references. */\n secrets?: SecretProvider;\n /**\n * Backend token mediator — present for `auth: backend` connectors of either\n * face (filesystem or tool), so mount refresh and tool-face OAuth flows share\n * one path.\n */\n tokenMediator?: TokenMediator;\n /**\n * Absolute directory the manager allocated for the filesystem face.\n * Present iff `connector.filesystem != null`. The connector projects its\n * content here during `connect()` and sets `handle.mountPath`.\n */\n mountTarget?: string;\n /** Resolved credential/config fields (from `describeFields()`). */\n resolvedFields?: Record<string, string>;\n /**\n * Aborted when the owning `ConnectorManager` is disposed. Long-running\n * `connect()` implementations — notably background (deferred) filesystem\n * mounts — should observe this and bail out promptly so session cleanup\n * does not wait on a wedged remote.\n */\n abortSignal?: AbortSignal;\n}\n\n/**\n * Filesystem face — present ⇒ the connector is \"mountable\".\n * @docLink packages/connectors/concepts#filesystem-face\n */\nexport interface FilesystemFace {\n /** Pull latest remote state into the mounted directory. */\n sync(handle: ConnectorHandle, options?: SyncOptions): Promise<SyncResult>;\n /**\n * Marks a slow filesystem mount that `ConnectorManager` brings up in the\n * background instead of awaiting during `connectAll({ deferMounts: true })`.\n * Set by rclone-backed FUSE connectors (sharepoint, webdav, googledrive)\n * whose mount can take longer than the platform's session-init ack budget.\n * Deferring keeps a slow or wedged remote from blocking session bootstrap —\n * it degrades to \"workspace still syncing\" rather than a restart loop.\n */\n readonly deferMount?: boolean;\n}\n\n/**\n * Tool face — present ⇒ the connector exposes agent tools.\n * @docLink packages/connectors/concepts#tool-face\n */\nexport interface ToolFace {\n read?(handle: ConnectorHandle, path: string): Promise<ConnectorContent | null>;\n write?(handle: ConnectorHandle, path: string, content: ConnectorContent): Promise<void>;\n delete?(handle: ConnectorHandle, path: string): Promise<boolean>;\n list?(handle: ConnectorHandle, path?: string, options?: ListOptions): Promise<ConnectorEntry[]>;\n search?(handle: ConnectorHandle, query: string, options?: SearchOptions): Promise<SearchResult[]>;\n describeOperations(handle: ConnectorHandle): OperationDescriptor[];\n executeOp(\n handle: ConnectorHandle,\n operation: string,\n args: Record<string, unknown>,\n ): Promise<string>;\n describeSkill?(\n handle: ConnectorHandle,\n declaration: ConnectorDeclaration,\n ): RuntimeSkillDescriptor;\n}\n\n/**\n * The unified connector contract. A connector should expose at least one face\n * (`filesystem` and/or `tools`); `ConnectorManager` rejects a faceless\n * connector at connect time.\n * @docLink packages/connectors/concepts#connector\n */\nexport interface Connector {\n readonly name: string;\n connect(declaration: ConnectorDeclaration, ctx: ConnectContext): Promise<ConnectorHandle>;\n disconnect(handle: ConnectorHandle): Promise<void>;\n readonly filesystem?: FilesystemFace;\n readonly tools?: ToolFace;\n describeFields?(): ConnectorFieldSpec[];\n setLogger?(logger: Logger): void;\n watch?(\n handle: ConnectorHandle,\n callback: (e: ConnectorChangeEvent) => void,\n options?: WatchOptions,\n ): WatchHandle;\n onHibernate?(handle: ConnectorHandle): Promise<string | undefined>;\n onSessionClose?(handle: ConnectorHandle): Promise<string | undefined>;\n}\n\n/**\n * Factory used by the connector registry.\n * @docLink packages/connectors/api-reference#connector-factory\n */\nexport type ConnectorFactory = () => Connector;\n\n/**\n * Per-connector bulk-connect result returned by `ConnectorManager.connectAll()`.\n * @docLink packages/connectors/concepts#connector-startup-report\n */\nexport interface ConnectorStartupReport {\n results: Array<{\n id: string;\n connected: boolean;\n mountPath?: string;\n error?: string;\n access?: \"read-only\" | \"read-write\";\n }>;\n}\n\n/**\n * Thrown by `connectAll` when a read-write mountable connector fails and\n * `failOnReadWriteError` was set.\n * @docLink packages/connectors/concepts#connector-startup-error\n */\nexport class ConnectorStartupError extends Error {\n readonly report: ConnectorStartupReport;\n readonly failedReadWrite: ReadonlyArray<{ id: string; error: string }>;\n constructor(\n message: string,\n report: ConnectorStartupReport,\n failedReadWrite: ReadonlyArray<{ id: string; error: string }>,\n ) {\n super(message);\n this.name = \"ConnectorStartupError\";\n this.report = report;\n this.failedReadWrite = failedReadWrite;\n }\n}\n","/**\n * FleetHealthGate — health-aware read-only gating for a single fleet-managed mount.\n *\n * Why this exists: a fleet-managed mount is bound live by the host fleet rclone,\n * so it is excluded from the boot-time no-phantom-workspace barrier (the host\n * already put real content at the target — a static barrier would shadow it).\n * That exclusion is only safe while the fleet rclone is healthy. When it wedges —\n * returning `EIO`, or degrading to an empty-but-writable view — the agent cannot\n * tell \"empty because broken\" from \"empty workspace\" and writes a phantom\n * workspace that diverges from the remote (the 2026-06-04 incident, except fleet\n * mounts sit outside the barrier).\n *\n * This gate closes that window. It dynamically drives a `MountPlaceholderBarrier`\n * over the *live* fleet target across THREE surfaces, because read availability\n * and write availability are independent:\n * - open = `remove(target)` — no barrier; live bind exposed read-write.\n * - ro = `exposeReadOnly(target)` — content visible, writes blocked. The\n * mount is live and READABLE but uploads are degraded; masking the\n * visible content would be wrong, so it is left read-only-readable.\n * - masked = `establish(target)` — opaque read-only tmpfs. The mount is not\n * live / unreadable; there is nothing trustworthy to show.\n *\n * Verdict → surface: `healthy` → open, `degraded` → ro, `error` → masked.\n *\n * Invariants:\n * - FAIL-CLOSED: if a barrier op throws, the target is treated as gated read-\n * only (masked). A known-unhealthy fleet mount is never left writable.\n * - HYSTERESIS: a surface change applies only after a verdict repeats\n * `threshold` times — moving toward writable uses `healthyThreshold`, moving\n * away (ro/masked) uses `unhealthyThreshold` — so a single transient blip\n * does not flap surfaces.\n * - IDEMPOTENT: barrier ops fire only on an actual surface change, so steady-\n * state polling does no mount work.\n */\n\nimport type { Logger } from \"@skaile/workspaces/types\";\nimport type { FleetHealthVerdict } from \"./fleet-utils.js\";\nimport type { MountPlaceholderBarrier } from \"./mount-placeholder.js\";\n\n/** The barrier surface currently applied (or being transitioned to) over the target. */\nexport type FleetGateSurface = \"open\" | \"ro\" | \"masked\";\n\nexport interface FleetHealthGateOptions {\n /** Consecutive unhealthy observations required to gate (default 2). */\n unhealthyThreshold?: number;\n /** Consecutive healthy observations required to ungate (default 2). */\n healthyThreshold?: number;\n /**\n * The surface the barrier already holds when the gate is constructed. Defaults\n * to `\"open\"` (no barrier — the normal fleet path). Set to `\"masked\"` when a\n * gate is created lazily over a target that already carries a static boot-time\n * barrier, so the first recovering verdict actually removes it.\n */\n initialSurface?: FleetGateSurface;\n}\n\ntype Surface = FleetGateSurface;\n\nfunction verdictToSurface(verdict: FleetHealthVerdict): Surface {\n if (verdict === \"healthy\") return \"open\";\n if (verdict === \"degraded\") return \"ro\";\n return \"masked\";\n}\n\n/**\n * Per-target health gate. Construct one per fleet-managed mount target; feed it\n * verdicts via `observe()`; tear it down with `dispose()` (removes the gate if\n * any barrier is established, so teardown leaves nothing un-writable that should\n * not be — caller controls ordering relative to connector disconnect).\n */\nexport class FleetHealthGate {\n private readonly unhealthyThreshold: number;\n private readonly healthyThreshold: number;\n\n /** The barrier surface actually applied to the target right now. */\n private surface: Surface;\n /**\n * The surface the most recently *enqueued* transition will settle on.\n * Hysteresis and re-enqueue de-duping are measured against this, not\n * `surface`, so verdicts arriving while a (slow, async) barrier op is still in\n * flight are counted toward the post-transition surface, not the stale one.\n */\n private pendingSurface: Surface;\n /** The surface of the *current* same-verdict run, and its length. */\n private runSurface: Surface;\n private runLength = 0;\n /** Serialises barrier ops so overlapping observe() calls can't race. */\n private transition: Promise<void> = Promise.resolve();\n\n constructor(\n private readonly target: string,\n private readonly barrier: MountPlaceholderBarrier,\n private readonly log?: Logger,\n opts?: FleetHealthGateOptions,\n ) {\n this.unhealthyThreshold = Math.max(1, opts?.unhealthyThreshold ?? 2);\n this.healthyThreshold = Math.max(1, opts?.healthyThreshold ?? 2);\n const initial = opts?.initialSurface ?? \"open\";\n this.surface = initial;\n this.pendingSurface = initial;\n this.runSurface = initial;\n }\n\n /** True while any read-only barrier (ro or masked) is established. */\n get isGated(): boolean {\n return this.surface !== \"open\";\n }\n\n /** The currently-applied surface (test/observability hook). */\n get currentSurface(): Surface {\n return this.surface;\n }\n\n /** The mount target this gate guards (recovery-probe lookup). */\n get mountTarget(): string {\n return this.target;\n }\n\n /**\n * Feed one health verdict. Applies hysteresis, then drives the barrier toward\n * the target surface on a change. Resolves once the (possibly no-op)\n * transition is applied. Never throws — a failed barrier op stays gated\n * (fail-closed).\n */\n observe(verdict: FleetHealthVerdict): Promise<void> {\n const desired = verdictToSurface(verdict);\n if (desired === this.runSurface) {\n this.runLength += 1;\n } else {\n this.runSurface = desired;\n this.runLength = 1;\n }\n // Moving toward writable is the cautious direction (must confirm recovery);\n // moving to a more-restrictive surface trips on the unhealthy threshold.\n const threshold = desired === \"open\" ? this.healthyThreshold : this.unhealthyThreshold;\n if (desired !== this.pendingSurface && this.runLength >= threshold) {\n this.pendingSurface = desired;\n this.runLength = 0;\n return this.enqueue(() => this.apply(desired));\n }\n return this.transition;\n }\n\n /**\n * Tear the gate down. If any barrier is established (or in flight), removes it\n * so a leftover read-only surface is not leaked. Call only after the connector\n * above the target is disconnected (top-down, no leaked mount).\n */\n dispose(): Promise<void> {\n if (this.surface === \"open\" && this.pendingSurface === \"open\") return this.transition;\n this.pendingSurface = \"open\";\n return this.enqueue(() => this.apply(\"open\"));\n }\n\n private enqueue(step: () => Promise<void>): Promise<void> {\n this.transition = this.transition.then(step, step);\n return this.transition;\n }\n\n /** Drive the barrier to `desired`, fail-closed to `masked` on any throw. */\n private async apply(desired: Surface): Promise<void> {\n if (this.surface === desired) {\n this.pendingSurface = desired;\n return;\n }\n try {\n if (desired === \"open\") {\n await this.barrier.remove(this.target, this.log);\n this.surface = \"open\";\n this.log?.info(\"fleet mount recovered — gate lifted, writable again\", {\n target: this.target,\n });\n return;\n }\n if (desired === \"ro\") {\n // Readable-but-write-degraded: expose the live content read-only. Fall\n // back to the opaque mask when the barrier can't do the readable surface.\n if (this.barrier.exposeReadOnly) {\n await this.barrier.exposeReadOnly(this.target, this.log);\n } else {\n await this.barrier.establish(this.target, this.log);\n }\n this.surface = \"ro\";\n this.log?.warn(\"fleet mount upload-degraded — gated read-only (content visible)\", {\n target: this.target,\n });\n return;\n }\n // masked\n await this.barrier.establish(this.target, this.log);\n this.surface = \"masked\";\n this.log?.warn(\"fleet mount unhealthy — gated read-only (masked)\", { target: this.target });\n } catch (err) {\n // Fail-closed: a thrown barrier op means we could not prove the target is\n // safe to leave as `desired`, so bias to `masked` — the most restrictive\n // surface (blocks writes AND hides content we could not confirm). This is\n // correct for every `desired`, including `ro` (a half-applied ro bind is\n // not provably readable). Currently unreachable — `exposeReadOnly` and\n // `establish` swallow their own failures internally — but kept correct in\n // case that changes. Restore `pendingSurface` so a later confirmed verdict\n // re-enqueues the transition.\n const safe: Surface = \"masked\";\n this.surface = safe;\n this.pendingSurface = safe;\n this.log?.error(\n `fleet read-only gate transition to '${desired}' threw — biasing to '${safe}' (fail-closed)`,\n err,\n { target: this.target },\n );\n }\n }\n}\n","/**\n * Shared helpers for filesystem-face connectors that delegate to a host-side\n * fleet supervisor (rclone for sharepoint/webdav/googledrive, git for git).\n *\n * When `SKAILE_FLEET_MANAGED_MOUNTS` lists a connector's id, the host has\n * already prepared the underlying mount (rclone FUSE mountpoint, or a git\n * worktree bind) and exposed it at the driver's target dir. The driver\n * short-circuits its own connect path after verifying the bind is live.\n */\n\nimport { readdir, readFile, stat } from \"node:fs/promises\";\nimport path from \"node:path\";\n\n/**\n * Return `true` when `connectorId` appears in the comma-separated\n * `SKAILE_FLEET_MANAGED_MOUNTS` env var, indicating the host fleet owns this\n * mount.\n */\nexport function isFleetManaged(connectorId: string): boolean {\n const raw = process.env.SKAILE_FLEET_MANAGED_MOUNTS ?? \"\";\n if (raw.length === 0) return false;\n return raw\n .split(\",\")\n .map((segment) => segment.trim())\n .filter((segment) => segment.length > 0)\n .includes(connectorId);\n}\n\n/**\n * Sanity-check the host bind mount before declaring success. The host\n * process should have the FUSE mount live before the container starts, so\n * we just verify the directory exists and is readable. Polls briefly to\n * absorb any startup race between container start and the kernel\n * publishing the mountpoint inside the container.\n *\n * `readdir` surfaces FUSE-side errors that `stat` cannot (e.g. transport\n * endpoint not connected if the host process died after bind).\n */\nexport async function ensureFleetMounted(\n dir: string,\n log: { info: (msg: string, data?: object) => void },\n options?: { timeoutMs?: number; pollIntervalMs?: number },\n): Promise<void> {\n const timeoutMs = options?.timeoutMs ?? 3_000;\n const pollIntervalMs = options?.pollIntervalMs ?? 100;\n const deadline = Date.now() + timeoutMs;\n let lastErr: unknown = null;\n while (Date.now() < deadline) {\n try {\n const st = await stat(dir);\n if (!st.isDirectory()) {\n throw new Error(`fleet mountpoint ${dir} is not a directory`);\n }\n await readdir(dir);\n log.info(\"fleet bind mount verified\", { dir });\n return;\n } catch (err) {\n lastErr = err;\n await new Promise((resolve) => setTimeout(resolve, pollIntervalMs));\n }\n }\n throw new Error(\n `fleet mount ${dir} not ready after ${timeoutMs}ms — check SKAILE_FLEET_MANAGED_MOUNTS env var and host bind: ${\n lastErr instanceof Error ? lastErr.message : String(lastErr)\n }`,\n );\n}\n\n/**\n * Health verdict for a fleet mount target.\n *\n * - `healthy` — live, readable, writes succeed → no barrier (writable).\n * - `degraded` — live and READABLE but writes are failing (e.g. fleet upload\n * errors, `core/stats.errors>0`). Read and write availability are independent,\n * so the content stays visible read-only, not masked. Only the platform signal\n * can detect this; the local probe never returns it.\n * - `error` — not live / unreadable (EIO, dead bind) → opaque read-only mask.\n */\nexport type FleetHealthVerdict = \"healthy\" | \"degraded\" | \"error\";\n\n/**\n * Locally probe a fleet mount target's health without any host signal.\n *\n * `stat` + `readdir` directly surface a wedged FUSE bind: `EIO`, `ENOTCONN`\n * (\"transport endpoint not connected\" — the host rclone died after bind), or a\n * non-directory target all read as `\"error\"`. This catches the directly-\n * detectable degradation (the Getec / EIO case) entirely in-container.\n *\n * It does NOT catch a *silently-empty-but-writable* degraded mount — an empty\n * `readdir` is indistinguishable from a legitimately empty workspace, so that\n * case is left to the platform health signal (`reportFleetHealth`). A `\"healthy\"`\n * verdict here therefore means only \"readable\", not \"has content\".\n */\nexport async function probeFleetHealth(dir: string): Promise<FleetHealthVerdict> {\n try {\n const st = await stat(dir);\n if (!st.isDirectory()) return \"error\";\n await readdir(dir);\n return \"healthy\";\n } catch {\n return \"error\";\n }\n}\n\n/**\n * Detect a live underlying fleet mount at `dir` from the mount table — spots\n * host-mount RECOVERY while an opaque read-only placeholder still masks the target.\n * A stat/readdir reads the 0555 mask and falsely reads healthy, so the recovery\n * edge is a non-tmpfs mount stacked at the mountpoint. `true` = recovered bind\n * present; `false` = only the placeholder tmpfs/nothing, or an unreadable mount\n * table (fail-closed: stay gated).\n * Rationale: `_devlog/notes/2026-06-17-fleet-gate-edge-triggered-recovery.md`.\n */\nexport async function probeFleetMountTablePresent(dir: string): Promise<boolean> {\n try {\n const text = await readFile(\"/proc/self/mounts\", \"utf8\");\n const resolved = path.resolve(dir);\n for (const raw of text.split(\"\\n\")) {\n if (raw.length === 0) continue;\n const fields = raw.split(/\\s+/);\n const mp = fields[1];\n const fstype = fields[2];\n if (!mp || !fstype) continue;\n // /proc/self/mounts encodes spaces as \\040; cheap decode (mirrors _fuseMountPresent).\n if (mp.replace(/\\\\040/g, \" \") !== resolved) continue;\n // The placeholder mounts a tmpfs (source `skaile-not-ready`); any non-tmpfs\n // mount stacked at the same mountpoint is the recovered backing fleet mount.\n if (fstype !== \"tmpfs\") return true;\n }\n return false;\n } catch {\n return false;\n }\n}\n","/**\n * MountPlaceholderBarrier — a read-only barrier at a deferred mount target.\n *\n * Why this exists: `connectAll({ deferMounts: true })` brings rclone-backed\n * filesystem mounts up in the background, after `session_init_ack`. Until the\n * real mount is live, the target would otherwise be a bare, writable local dir.\n * An agent that goes live in that window cannot tell \"empty because unmounted\"\n * from \"empty workspace\" and writes a phantom workspace that diverges from the\n * remote (confirmed in prod 2026-06-04 — see\n * `_devlog/entries/2026-06-04-readonly-deferred-mount-barrier.md`).\n *\n * The guarantee must hold at the filesystem layer, not just as an LLM notice:\n * a plain `chmod` is bypassable because the owning uid can chmod back, whereas\n * a read-only mount cannot. So the default barrier mounts a read-only tmpfs\n * over the target (the container already has CAP_SYS_ADMIN for FUSE). When that\n * is not available it degrades to a `chmod 0o555` — strictly better than a\n * writable dir, with a loud error so the degraded state is observable.\n *\n * Lifecycle, driven by `ConnectorManager`:\n * 1. `establish(target)` — synchronously in the eager phase, before ack.\n * 2. `prepareForStackedMount(target)` — immediately before the deferred\n * connector's in-container rclone mount. Lifts the barrier to read-write\n * (remount rw / chmod 0o755) so `fusermount3` can mount over the target —\n * it requires WRITE access to the mountpoint and a `ro` tmpfs denies it for\n * every uid. The tmpfs stays mounted and is shadowed by the real mount.\n * 3a. `onMountLive(target)` — the real rclone mount stacks on top and provides\n * write access (it physically shadows the placeholder); no fs change is\n * needed. In the degraded chmod mode the sentinel is cleaned up.\n * 3b. `restoreBarrier(target)` — instead of 3a, when the mount FAILED:\n * re-assert read-only so a failed mount never leaves the target writable.\n * 4. `remove(target)` — on teardown, after the rclone mount above it is gone.\n *\n * `exposeReadOnly(target)` is an out-of-band downgrade (driven by the fleet\n * health gate): when the underlying mount is live and readable but writes are\n * degraded, it removes any opaque mask and read-only-binds the live target so\n * the real content stays visible while writes are blocked — read and write\n * availability are independent, so masking visible content would be wrong.\n */\n\nimport { spawn } from \"node:child_process\";\nimport { chmod, mkdir, rm, writeFile } from \"node:fs/promises\";\nimport path from \"node:path\";\nimport type { Logger } from \"@skaile/workspaces/types\";\n\n/** Dropped into the placeholder so a peeking agent/operator sees why it is read-only. */\nexport const NOT_READY_SENTINEL = \".skaile-workspace-not-ready\";\n\n/**\n * Errno codes that mean \"the target is already there / can't be freshly created\n * or stat'd as a plain dir\" — i.e. an existing live-or-broken mountpoint rather\n * than a fresh path we can mkdir. For the fleet gate the target is a live\n * `:rshared` FUSE bind (EEXIST) or a broken FUSE bind (ENOTCONN), so a failed\n * mkdir is expected and must NOT abort establish — we proceed to the protect\n * step instead. EBUSY/ENOTDIR cover adjacent \"already a mount / not a dir\"\n * states a thrashed bind can present.\n */\nconst TARGET_ALREADY_PRESENT_CODES = new Set([\"EEXIST\", \"ENOTCONN\", \"EBUSY\", \"ENOTDIR\"]);\n\nfunction errnoCode(err: unknown): string | undefined {\n return typeof err === \"object\" && err !== null && \"code\" in err\n ? String((err as { code: unknown }).code)\n : undefined;\n}\n\nconst SENTINEL_BODY = [\n \"This workspace is backed by a remote mount that is not live yet.\",\n \"It is mounted read-only on purpose: writing here would create a phantom\",\n \"workspace that diverges from the remote once the mount comes up.\",\n \"Wait for the mount to finish syncing (watch connector_status) before writing.\",\n \"\",\n].join(\"\\n\");\n\n/**\n * A read-only barrier over a deferred mount target. Injected into\n * `ConnectorManager` so tests can substitute a hermetic implementation.\n */\nexport interface MountPlaceholderBarrier {\n /** Make `target` read-only and drop the sentinel. Idempotent per target. */\n establish(target: string, log?: Logger): Promise<void>;\n /**\n * Make `target` writable to the mounting uid so an in-container FUSE mount\n * (rclone) can stack on top. `fusermount3` requires WRITE access to the\n * mountpoint and a `ro` tmpfs / `0o555` dir denies it for *every* uid — so the\n * barrier must be lifted before the real mount spawns, not after. Called by\n * `ConnectorManager` immediately before a deferred connector's mount. The\n * tmpfs stays mounted (shadowed by the real mount once it lands), so the bare\n * underlying dir is never exposed as a writable phantom target. Optional:\n * absent on hermetic test fakes. Idempotent per target.\n */\n prepareForStackedMount?(target: string, log?: Logger): Promise<void>;\n /**\n * Re-assert the read-only barrier after a deferred mount attempt FAILED, so a\n * failed mount never leaves the target writable. The inverse of\n * `prepareForStackedMount`. Optional.\n */\n restoreBarrier?(target: string, log?: Logger): Promise<void>;\n /**\n * Signal that the real mount is now live on top of `target` and provides\n * write access. The placeholder stays tracked so `remove()` still tears it\n * down on teardown.\n */\n onMountLive(target: string, log?: Logger): Promise<void>;\n /**\n * Downgrade the barrier to a READ-ONLY surface that still exposes the live\n * content underneath, instead of the opaque mask `establish` puts up. Used\n * when the underlying mount is live and fully READABLE but writes are degraded\n * (e.g. fleet upload errors): read and write availability are independent, so\n * masking the readable content is wrong — the agent should still see it,\n * read-only. Removes any opaque tmpfs first (revealing the propagated bind),\n * then read-only-binds the live target onto itself so writes fail for every\n * uid while reads succeed. Idempotent per target. Optional: absent on hermetic\n * test fakes (callers fall back to `establish`).\n */\n exposeReadOnly?(target: string, log?: Logger): Promise<void>;\n /** Tear the barrier down. Call only after any mount stacked above it is gone. */\n remove(target: string, log?: Logger): Promise<void>;\n /**\n * True when the barrier currently OPAQUELY masks `target` (an `establish`-mode\n * tmpfs shadows the real content). The recovery probe needs this: over an opaque\n * mask a direct `stat`/`readdir` reads the mask (mode 0555, always \"healthy\") and\n * cannot see a recovered host mount, so the manager falls back to the mount\n * table; non-opaque surfaces (chmod / ro-bind) expose the live inode directly.\n * Optional: absent on hermetic test fakes (the manager treats absent as\n * not-opaque, so the live inode is read directly). Idempotent per target.\n */\n isOpaque?(target: string): boolean;\n}\n\n/**\n * How a target's barrier was realised — drives `onMountLive` / `remove`.\n * `\"unprotected\"` means both mount and chmod failed: the target is tracked (so\n * the sentinel is still cleaned up) but was never actually made read-only.\n * `\"ro-bind\"` is the readable-but-read-only surface from `exposeReadOnly`: the\n * live mount bound onto itself read-only (no opaque tmpfs, content visible).\n */\ntype BarrierMode = \"mount\" | \"chmod\" | \"unprotected\" | \"ro-bind\";\n\n/** Runs an external command, rejecting on non-zero exit or spawn error. */\nexport type CommandRunner = (cmd: string, args: string[]) => Promise<void>;\n\n/**\n * Creates the target directory. Injectable so tests can simulate a live/broken\n * FUSE mountpoint (EEXIST / ENOTCONN) deterministically; defaults to a recursive\n * `mkdir`.\n */\nexport type MkdirFn = (target: string) => Promise<void>;\n\nconst defaultMkdir: MkdirFn = async (target) => {\n await mkdir(target, { recursive: true });\n};\n\nconst defaultRunner: CommandRunner = (cmd, args) =>\n new Promise<void>((resolve, reject) => {\n const proc = spawn(cmd, args, { stdio: \"ignore\" });\n proc.once(\"error\", reject);\n // `close` carries the signal too, so a kill reports \"signal SIGKILL\"\n // instead of the opaque \"exited null\".\n proc.once(\"close\", (code, signal) => {\n if (code === 0) resolve();\n else reject(new Error(`${cmd} ${args.join(\" \")} exited ${code ?? `signal ${signal}`}`));\n });\n });\n\n/**\n * Default barrier: a read-only tmpfs over the target, with a `chmod 0o555`\n * fallback when mounting is unavailable. The tmpfs root is left mode 0o755\n * (owner-traversable, owned by the mounting uid so `fusermount3` can later\n * stack the real mount on top) and made unwritable by the `ro` mount flag, not\n * by stripping mode bits — a `ro` mount blocks writes for every uid.\n */\nexport class RoMountPlaceholderBarrier implements MountPlaceholderBarrier {\n private readonly run: CommandRunner;\n private readonly mkdirFn: MkdirFn;\n private readonly modes = new Map<string, BarrierMode>();\n\n constructor(opts?: { run?: CommandRunner; mkdirFn?: MkdirFn }) {\n this.run = opts?.run ?? defaultRunner;\n this.mkdirFn = opts?.mkdirFn ?? defaultMkdir;\n }\n\n async establish(target: string, log?: Logger): Promise<void> {\n if (this.modes.has(target)) return;\n // The fleet gate establishes over a *live* `:rshared` FUSE bind (the host\n // already put real content there) or a *broken* one. In both cases the\n // target exists as a mountpoint and `mkdir` throws (EEXIST for a live bind,\n // ENOTCONN for \"Transport endpoint is not connected\") — Node can't stat it\n // as a fresh dir. That is exactly the case we must handle, not abort on: the\n // dir is already present, so proceed straight to the protect step. Only a\n // genuinely unexpected mkdir failure (e.g. EACCES on the parent) aborts.\n try {\n await this.mkdirFn(target);\n } catch (err) {\n const code = errnoCode(err);\n if (!code || !TARGET_ALREADY_PRESENT_CODES.has(code)) {\n // Unexpected — degrade rather than throw out of establish(); a\n // gate-establish failure must never surface a raw error or corrupt the\n // mount. chmodFallback ends in a defined, tracked, loudly-logged mode.\n await this.chmodFallback(target, err, log);\n return;\n }\n log?.debug(\"barrier target already present (live/broken mount) — protecting in place\", {\n target,\n code,\n });\n }\n let tmpfsMounted = false;\n try {\n // tmpfs rw → write sentinel → remount ro. Done in this order because a\n // ro filesystem cannot accept the sentinel write.\n await this.run(\"mount\", [\n \"-t\",\n \"tmpfs\",\n \"-o\",\n \"mode=0755,size=1m\",\n \"skaile-not-ready\",\n target,\n ]);\n tmpfsMounted = true;\n await writeFile(path.join(target, NOT_READY_SENTINEL), SENTINEL_BODY);\n await this.run(\"mount\", [\"-o\", \"remount,ro\", target]);\n this.modes.set(target, \"mount\");\n log?.info(\"deferred mount barrier established (read-only tmpfs)\", { target });\n } catch (err) {\n // Undo a partial mount (tmpfs up but remount-ro failed) before the chmod\n // path takes over — otherwise the rw tmpfs leaks under a \"chmod\"-mode entry\n // that remove() never unmounts.\n if (tmpfsMounted) await this.run(\"umount\", [target]).catch(() => {});\n // No CAP_SYS_ADMIN / no `mount` (local dev, restricted sandbox): degrade\n // to chmod. Bypassable by the owning uid, hence the error-level log.\n await this.chmodFallback(target, err, log);\n }\n }\n\n async prepareForStackedMount(target: string, log?: Logger): Promise<void> {\n const mode = this.modes.get(target);\n if (mode === \"mount\") {\n // Remount rw so `fusermount3` can pass its W_OK mountpoint check — a `ro` tmpfs\n // denies write for every uid. The tmpfs stays mounted and is shadowed by the\n // real mount. See _devlog/notes/2026-06-12-fusermount3-mountpoint-write-access.md\n try {\n await this.run(\"mount\", [\"-o\", \"remount,rw\", target]);\n log?.debug(\"deferred mount barrier lifted to read-write for stacked mount\", { target });\n } catch (err) {\n log?.error(\n \"deferred mount barrier: remount read-write before stacked mount failed — the mount may be rejected with EACCES\",\n err instanceof Error ? err : undefined,\n { target },\n );\n }\n return;\n }\n // Degraded modes have no shadowing tmpfs; pre-lifting exposes the real backing dir\n // as writable for the entire mount window — the phantom-workspace hazard this barrier\n // prevents. See _devlog/notes/2026-06-12-fusermount3-mountpoint-write-access.md\n }\n\n async restoreBarrier(target: string, log?: Logger): Promise<void> {\n const mode = this.modes.get(target);\n if (mode === \"mount\") {\n let restored = false;\n await this.run(\"mount\", [\"-o\", \"remount,ro\", target])\n .then(() => {\n restored = true;\n })\n .catch((err) => {\n log?.error(\n \"deferred mount barrier: remount read-only after failed mount failed — target may be writable\",\n err instanceof Error ? err : undefined,\n { target },\n );\n });\n if (restored) log?.debug(\"deferred mount barrier re-asserted read-only after failed mount\", { target });\n }\n // chmod / unprotected modes were never pre-lifted (see prepareForStackedMount),\n // so there is nothing to re-assert.\n }\n\n async onMountLive(target: string, log?: Logger): Promise<void> {\n const mode = this.modes.get(target);\n if (mode === \"mount\") {\n // The real rclone mount is stacked on top and shadows the read-only\n // tmpfs; nothing to do until teardown.\n log?.debug(\"deferred mount live; placeholder shadowed\", { target });\n return;\n }\n if (mode === \"chmod\" || mode === \"unprotected\") {\n // Lift the degraded barrier (no-op in \"unprotected\" mode) so the live\n // mount's ensureDirMode chmod is not fighting a 0o555 dir.\n if (mode === \"chmod\") await chmod(target, 0o755).catch(() => {});\n // Tolerate failure: once the real mount stacks on top, the sentinel is\n // shadowed and removing it is moot anyway.\n await rm(path.join(target, NOT_READY_SENTINEL), { force: true }).catch(() => {});\n log?.debug(\"deferred mount live; degraded barrier lifted\", { target, mode });\n }\n }\n\n async exposeReadOnly(target: string, log?: Logger): Promise<void> {\n const mode = this.modes.get(target);\n if (mode === \"ro-bind\") return;\n // Drop any opaque mask so the live content underneath is revealed. A \"mount\"\n // mode tmpfs shadows the live bind — unmount it. \"chmod\"/\"unprotected\" never\n // shadowed content (they only stripped/failed-to-strip mode bits on the live\n // dir), so there is nothing to unmount; the chmod is restored below by the\n // read-only bind, which blocks writes for every uid regardless.\n if (mode === \"mount\") {\n let unmounted = await this.run(\"umount\", [target]).then(\n () => true,\n () => false,\n );\n if (!unmounted) {\n unmounted = await this.run(\"umount\", [\"-l\", target]).then(\n () => true,\n () => false,\n );\n }\n // If the opaque tmpfs refuses to unmount, do NOT stack the ro bind over it\n // — that would leave a hidden tmpfs the live content never shows through,\n // and `remove` later unmounting only the ro bind would leak it. Stay masked\n // (fail-safe, content hidden but no leak); a later verdict retries.\n if (!unmounted) {\n log?.error(\n \"deferred mount barrier: could not unmount opaque mask to expose read-only surface — staying masked\",\n undefined,\n { target },\n );\n return;\n }\n }\n try {\n // Bind the live mount onto itself, then remount that bind read-only. A\n // ro bind exposes the real content (reads succeed) but denies writes for\n // every uid — the agent (uid 1001) cannot chmod a bit back. This is the\n // readable-but-write-degraded surface (live mount, failing uploads): mask\n // would wrongly hide visible content.\n await this.run(\"mount\", [\"--bind\", target, target]);\n await this.run(\"mount\", [\"-o\", \"remount,ro,bind\", target]);\n // No sentinel here. Unlike the opaque mask (whose sentinel lives on the\n // tmpfs overlay), a ro bind shares the LIVE inode — a sentinel would be\n // written into the user's real workspace and, in this very degraded state,\n // queue yet another failing upload. The ro bind is the signal: writes fail\n // EROFS and the degraded state is surfaced via connector health, not a\n // stray file dropped in the content.\n this.modes.set(target, \"ro-bind\");\n log?.info(\"deferred mount barrier downgraded to read-only (content visible)\", { target });\n } catch (err) {\n // No CAP_SYS_ADMIN / no `mount`: fall back to chmod 0o555 of the live dir.\n // Bypassable by the owning uid (loud error), but still exposes content.\n const chmodOk = await chmod(target, 0o555).then(\n () => true,\n () => false,\n );\n this.modes.set(target, chmodOk ? \"chmod\" : \"unprotected\");\n log?.error(\n chmodOk\n ? \"deferred mount read-only-readable surface degraded to chmod (ro bind unavailable) — a write by the owning uid could bypass it\"\n : \"deferred mount read-only-readable surface FAILED (ro bind and chmod both unavailable) — target may be writable\",\n err instanceof Error ? err : undefined,\n { target },\n );\n }\n }\n\n isOpaque(target: string): boolean {\n // Only the `establish` tmpfs opaquely shadows the target. chmod/unprotected\n // never overlaid content (they only touch mode bits on the live dir) and a\n // ro-bind shares the live inode — all expose the real underlying state.\n return this.modes.get(target) === \"mount\";\n }\n\n async remove(target: string, log?: Logger): Promise<void> {\n const mode = this.modes.get(target);\n if (!mode) return;\n this.modes.delete(target);\n if (mode === \"mount\" || mode === \"ro-bind\") {\n let unmounted = false;\n try {\n await this.run(\"umount\", [target]);\n unmounted = true;\n } catch {\n // Lazy unmount as a last resort so a busy target does not leak the mount.\n await this.run(\"umount\", [\"-l\", target]).then(\n () => {\n unmounted = true;\n },\n () => {},\n );\n }\n if (unmounted) {\n log?.debug(\"deferred mount barrier removed (tmpfs unmounted)\", { target });\n } else {\n log?.error(\n \"deferred mount barrier: umount and umount -l both failed — tmpfs may be leaked\",\n undefined,\n { target },\n );\n }\n // Both \"mount\" and \"ro-bind\" surfaces are mount-only: the sentinel (when\n // present) lived on the tmpfs overlay and vanished with the umount, and a\n // ro bind never wrote one into the live content — so nothing to clean here.\n return;\n }\n // \"chmod\" lifted a real 0o555 restriction; \"unprotected\" never enforced one,\n // so don't claim a restriction was restored that never existed.\n if (mode === \"chmod\") await chmod(target, 0o755).catch(() => {});\n await rm(path.join(target, NOT_READY_SENTINEL), { force: true }).catch(() => {});\n log?.debug(\n mode === \"chmod\"\n ? \"deferred mount barrier removed (chmod restored)\"\n : \"deferred mount barrier removed (was never enforced — target stayed writable)\",\n { target },\n );\n }\n\n private async chmodFallback(target: string, cause: unknown, log?: Logger): Promise<void> {\n await writeFile(path.join(target, NOT_READY_SENTINEL), SENTINEL_BODY).catch(() => {});\n const chmodOk = await chmod(target, 0o555).then(\n () => true,\n () => false,\n );\n this.modes.set(target, chmodOk ? \"chmod\" : \"unprotected\");\n const detail = { target, error: cause instanceof Error ? cause.message : String(cause) };\n if (chmodOk) {\n log?.error(\n \"deferred mount read-only barrier degraded to chmod (mount unavailable) — a write by the owning uid could bypass it\",\n undefined,\n detail,\n );\n } else {\n // Neither mount nor chmod took — the guarantee is not enforced and the\n // target is writable. Surface it loudly rather than claiming success.\n log?.error(\n \"deferred mount read-only barrier FAILED (mount and chmod both unavailable) — target is WRITABLE\",\n undefined,\n detail,\n );\n }\n }\n}\n\n/** Shared default barrier instance used by `ConnectorManager` unless overridden. */\nexport const defaultMountPlaceholderBarrier: MountPlaceholderBarrier =\n new RoMountPlaceholderBarrier();\n","/**\n * ConnectorManager — unified lifecycle & mount-target allocation.\n *\n * Manages the full lifecycle of every connector declared in `skaile.yaml`,\n * whether it exposes a `filesystem` face, a `tools` face, or both.\n *\n * @docLink packages/connectors/concepts#connector-manager\n */\n\nimport { existsSync, mkdirSync } from \"node:fs\";\nimport { dirname, resolve } from \"node:path\";\nimport type { CatalogEntry } from \"@skaile/workspaces/core\";\nimport { createLogger } from \"@skaile/workspaces/core/logging\";\nimport { pluginRegistry } from \"@skaile/workspaces/plugin-registry\";\nimport type { TelemetryProvider, Trace } from \"@skaile/workspaces/telemetry\";\nimport type { ConnectorStatusEvent, Logger } from \"@skaile/workspaces/types\";\nimport * as z from \"zod\";\nimport { tryGetConnector } from \"./connector-registry.js\";\nimport type {\n ConnectContext,\n Connector,\n ConnectorChangeEvent,\n ConnectorDeclaration,\n ConnectorFieldSpec,\n ConnectorHandle,\n ConnectorStartupReport,\n RuntimeSkillDescriptor,\n TokenMediator,\n ToolFace,\n} from \"./connector-types.js\";\nimport { ConnectorFieldMissingError, ConnectorStartupError } from \"./connector-types.js\";\nimport { FleetHealthGate } from \"./fleet-health-gate.js\";\nimport {\n type FleetHealthVerdict,\n isFleetManaged,\n probeFleetHealth,\n probeFleetMountTablePresent,\n} from \"./fleet-utils.js\";\nimport {\n defaultMountPlaceholderBarrier,\n type MountPlaceholderBarrier,\n} from \"./mount-placeholder.js\";\nimport type { PreMintedSecretProvider, SecretProvider, SecretProviderChain } from \"./secrets.js\";\nimport type {\n ConnectorContent,\n ConnectorEntry,\n ListOptions,\n OperationDescriptor,\n SearchOptions,\n SearchResult,\n SyncOptions,\n SyncResult,\n WatchHandle,\n WatchOptions,\n} from \"./shared-types.js\";\n\n// ── Internal state ────────────────────────────────────────────────────────────\n\n/**\n * Internal per-connector tracking record.\n */\ninterface ActiveConnector {\n connector: Connector;\n handle: ConnectorHandle;\n declaration: ConnectorDeclaration;\n watchHandle?: WatchHandle;\n /**\n * Set for a deferred remote mount that has a read-only placeholder barrier at\n * this path. The barrier is removed (after the rclone mount above it is gone)\n * when the connector is disconnected.\n */\n placeholderTarget?: string;\n /**\n * Set for a fleet-managed deferred mount. Unlike `placeholderTarget` (a static\n * boot-time barrier), this gate dynamically establishes/removes the barrier as\n * the fleet mount's health flips — closing the window where a wedged fleet\n * mount stays writable. Removed on teardown after the connector is gone.\n */\n fleetHealthTarget?: string;\n fleetHealthGate?: FleetHealthGate;\n}\n\ninterface LifecycleResult {\n id: string;\n ok: boolean;\n error?: string;\n detail?: string;\n}\n\nexport interface SyncConnectorResult {\n id: string;\n ok: boolean;\n error?: string;\n}\n\n// ── Module-level helpers ──────────────────────────────────────────────────────\n\nconst KNOWN_PREFIXES = [\"env:\", \"forge:\", \"op:\", \"kp:\", \"oauth:\"];\n\nconst DEFAULT_FLEET_HEALTH_POLL_MS = 5000;\n\n/**\n * Resolve the local fleet-health probe interval from `SKAILE_FLEET_HEALTH_POLL_MS`.\n * A finite non-negative number is honoured (`0` disables the probe). Anything\n * unparseable (`Number(\"disabled\") → NaN`) or negative falls back to the default,\n * so an invalid value never produces a `NaN` interval — `setInterval(fn, NaN)` is\n * treated as `setInterval(fn, 0)` and would saturate the event loop.\n */\nexport function parseFleetHealthPollMs(\n raw: string | undefined = process.env.SKAILE_FLEET_HEALTH_POLL_MS,\n): number {\n if (raw === undefined) return DEFAULT_FLEET_HEALTH_POLL_MS;\n const n = Number(raw);\n return Number.isFinite(n) && n >= 0 ? n : DEFAULT_FLEET_HEALTH_POLL_MS;\n}\n\nfunction hasKnownPrefix(ref: string): boolean {\n return KNOWN_PREFIXES.some((p) => ref.startsWith(p));\n}\n\n/**\n * True when `child` is strictly nested under `parent` (not equal). Both paths\n * must already be absolute and normalized (as `resolveMountTarget` returns).\n */\nfunction isStrictlyNested(child: string, parent: string): boolean {\n return child.startsWith(`${parent}/`);\n}\n\n/**\n * Resolve all declared fields for a connector through the secret chain.\n */\nasync function resolveFields(\n declaration: ConnectorDeclaration,\n fields: ConnectorFieldSpec[],\n chain: SecretProviderChain,\n): Promise<Record<string, string>> {\n const resolved: Record<string, string> = {};\n\n for (const field of fields) {\n let value: string | undefined;\n\n if (field.type === \"oauth\") {\n const account = resolved.account ?? \"\";\n const oauthRef = `oauth:${field.oauthService}:${account}`;\n await chain.prepareRef(oauthRef); // may throw OAuthRequiredError\n value = chain.resolve(oauthRef);\n } else {\n const rawValue = declaration.options?.[field.key];\n if (rawValue !== undefined) {\n const raw = String(rawValue);\n value = hasKnownPrefix(raw) ? chain.resolve(raw) : raw;\n } else {\n value = field.default;\n }\n }\n\n if (value === undefined && field.required) {\n throw new ConnectorFieldMissingError({\n connectorId: declaration.id,\n field,\n triedRef: String(declaration.options?.[field.key] ?? \"(none)\"),\n availableProviders: chain.capabilities(),\n });\n }\n\n if (value !== undefined) resolved[field.key] = value;\n }\n\n return resolved;\n}\n\n/**\n * Build a default `RuntimeSkillDescriptor` for a connector that does not implement `describeSkill()`.\n */\nfunction buildDefaultSkillDescriptor(\n connector: Connector,\n declaration: ConnectorDeclaration,\n handle: ConnectorHandle,\n): RuntimeSkillDescriptor {\n const ops = connector.tools?.describeOperations(handle) ?? [];\n return {\n id: declaration.id,\n name: `${connector.name} — ${declaration.id}`,\n description: `${connector.name} connector (${declaration.id})`,\n category: connector.name,\n access: declaration.access,\n toolNames: ops.map((o) => o.name),\n };\n}\n\n/**\n * Render a skill body string from a descriptor and operation list.\n */\nfunction buildSkillBody(\n descriptor: RuntimeSkillDescriptor,\n ops: OperationDescriptor[],\n shellAccess: boolean,\n): string {\n const lines: string[] = [\n `## ${descriptor.name}`,\n \"\",\n descriptor.description,\n `Access: ${descriptor.access}`,\n \"\",\n ];\n\n if (ops.length > 0) {\n lines.push(\"### Operations\", \"\");\n for (const op of ops) {\n const argStr = op.args\n .map((a) =>\n a.required\n ? `--${a.name} ${a.type.toUpperCase()}`\n : `[--${a.name} ${a.type.toUpperCase()}]`,\n )\n .join(\" \");\n if (shellAccess) {\n lines.push(`**${op.name}** — ${op.description}`);\n lines.push(\n ` skaile connector ${descriptor.id} ${op.name}${argStr ? ` ${argStr}` : \"\"}`,\n \"\",\n );\n } else {\n lines.push(`**${op.name}** — ${op.description}`);\n lines.push(` connector_exec connector_id=\"${descriptor.id}\" operation=\"${op.name}\"`, \"\");\n }\n }\n }\n\n lines.push(\"### Base operations\", \"\");\n if (shellAccess) {\n lines.push(\n ` skaile connector ${descriptor.id} read <path>`,\n ` skaile connector ${descriptor.id} list [path]`,\n ` skaile connector ${descriptor.id} search <query>`,\n );\n } else {\n lines.push(\n ` connector_read connector_id=\"${descriptor.id}\" path=<path>`,\n ` connector_list_entries connector_id=\"${descriptor.id}\"`,\n ` connector_search connector_id=\"${descriptor.id}\" query=<query>`,\n );\n }\n\n return lines.join(\"\\n\");\n}\n\n// ── Manager options ───────────────────────────────────────────────────────────\n\n/**\n * Options for the unified `ConnectorManager`. Pass as the second argument to the constructor.\n *\n * Note: constructor signature is `new ConnectorManager(workspaceDir, opts?)` —\n * `workspaceDir` comes first because mountable connectors need it.\n * `secrets` moves into opts (was the first arg in the old `ConnectorManager`).\n */\nexport interface ConnectorManagerOptions {\n /**\n * Secret provider (chain or bare) for resolving credential references in\n * `describeFields()` and for passing to `Connector.connect()`.\n */\n secrets?: SecretProviderChain | SecretProvider;\n\n /**\n * Catalog entries for dynamic connector resolution (registry-first, catalog-fallback).\n */\n catalogEntries?: CatalogEntry[];\n\n /**\n * Backend token mediator — present for `auth: backend` filesystem-face connectors.\n * Wrapped with pre-minted secrets when `preMintedSecrets` is also set.\n */\n tokenMediator?: TokenMediator;\n\n /**\n * Pre-minted credential store from `session_init`. When set, `auth: backend`\n * connectors use this for the initial mint without a platform round-trip.\n */\n preMintedSecrets?: PreMintedSecretProvider;\n\n /**\n * Called whenever a connector's connection state changes.\n *\n * Fired from both the bulk `connectAll()` path and the hot-plug `connect()` path.\n * Status values: `\"connecting\"` → `\"connected\"` | `\"error\"`, and `\"disconnected\"`\n * after `disconnect()` / `disconnectAll()`.\n */\n onStatusChange?: (event: ConnectorStatusEvent) => void;\n\n /** Optional telemetry provider for span instrumentation. */\n telemetry?: TelemetryProvider;\n\n /** Optional active trace to attach connector spans to. */\n trace?: Trace;\n\n /**\n * Read-only barrier applied to a deferred remote mount target until its real\n * mount is live. Defaults to a tmpfs-backed barrier with a chmod fallback;\n * tests inject a hermetic implementation. See `mount-placeholder.ts`.\n */\n placeholderBarrier?: MountPlaceholderBarrier;\n\n /**\n * Local fleet-health poll interval (ms) for the read-only health gate on\n * fleet-managed mounts. `0` disables the local probe (health is then driven\n * solely by `reportFleetHealth` / the platform signal). Defaults to the\n * `SKAILE_FLEET_HEALTH_POLL_MS` env var, else 5000. Tests pass a small value\n * (or 0 + manual `reportFleetHealth`) to stay hermetic.\n */\n fleetHealthPollMs?: number;\n\n /**\n * Detects host-mount RECOVERY under an opaque placeholder so the local poll can\n * lift the gate edge-triggered. Defaults to the `/proc/self/mounts` reader;\n * tests inject a hermetic stub (the real reader can't be faked in a sandbox).\n */\n fleetMountRecoveryProbe?: (target: string) => Promise<boolean>;\n}\n\n// ── Manager ───────────────────────────────────────────────────────────────────\n\n/**\n * `ConnectorManager` — manages the full lifecycle of all connectors declared\n * in `skaile.yaml`, whether they expose a filesystem face, a tool face, or both.\n *\n * For filesystem-face connectors, the manager allocates a mount-target\n * directory and passes it as `ctx.mountTarget`; the connector mounts its\n * content there during `connect()`.\n *\n * @docLink packages/connectors/concepts#connector-manager\n */\nexport class ConnectorManager {\n private active = new Map<string, ActiveConnector>();\n // Allocated absolute mount target → owning connector id; collisions rejected at setup, released on disconnect.\n private readonly mountTargets = new Map<string, string>();\n readonly workspaceDir: string;\n private readonly chain?: SecretProviderChain;\n private readonly secrets?: SecretProvider;\n private readonly catalogEntries: CatalogEntry[];\n private readonly tokenMediator?: TokenMediator;\n private readonly preMintedSecrets?: PreMintedSecretProvider;\n private readonly placeholderBarrier: MountPlaceholderBarrier;\n private readonly mgrLog: Logger;\n\n /** Set once `disconnectAll()` starts, so in-flight deferred mounts bail. */\n private disposed = false;\n /** Aborted on dispose; threaded into every `connect()` via `ctx.abortSignal`. */\n private readonly disposeController = new AbortController();\n /** Tracks the background task driving deferred (rclone-backed) mounts. */\n private deferredConnect?: Promise<void>;\n /** Periodic local fleet-health probe; runs only while a fleet gate is active. */\n private fleetHealthTimer?: ReturnType<typeof setInterval>;\n /** Local fleet-health poll interval (ms). 0 disables the local probe. */\n private readonly fleetHealthPollMs: number;\n /** Host-mount recovery detector under an opaque placeholder (injectable for tests). */\n private readonly fleetMountRecoveryProbe: (target: string) => Promise<boolean>;\n\n /**\n * @param workspaceDir - Absolute (or relative) working directory. Filesystem-face\n * connectors mount into `<workspaceDir>/.mounts/<id>/` by default.\n * @param opts - Optional configuration: secrets, catalogEntries, tokenMediator,\n * preMintedSecrets, onStatusChange, telemetry, trace.\n */\n constructor(\n workspaceDir: string,\n private readonly opts: ConnectorManagerOptions = {},\n ) {\n this.workspaceDir = resolve(workspaceDir);\n this.catalogEntries = opts.catalogEntries ?? [];\n this.tokenMediator = opts.tokenMediator;\n this.preMintedSecrets = opts.preMintedSecrets;\n this.placeholderBarrier = opts.placeholderBarrier ?? defaultMountPlaceholderBarrier;\n this.fleetHealthPollMs = opts.fleetHealthPollMs ?? parseFleetHealthPollMs();\n this.fleetMountRecoveryProbe = opts.fleetMountRecoveryProbe ?? probeFleetMountTablePresent;\n\n // Accept SecretProviderChain (has `prepareRef`) or bare SecretProvider\n const secrets = opts.secrets;\n if (secrets && typeof secrets === \"object\" && \"prepareRef\" in secrets) {\n this.chain = secrets as SecretProviderChain;\n } else {\n this.secrets = secrets as SecretProvider | undefined;\n }\n\n this.mgrLog = createLogger({\n kind: \"connector\",\n subkind: \"manager\",\n instance: this.workspaceDir,\n });\n }\n\n // ── Private helpers ──────────────────────────────────────────────────────────\n\n /**\n * Wrap the user-supplied `TokenMediator` so `reason: 'initial'` calls for an\n * `auth: backend` connector first consult the pre-minted credentials. Falls\n * back to the original mediator for refresh / retry-401 paths. On that\n * fall-through it attaches the connector's `driver` + `providerLinkId` taken\n * from the `declaration` (authoritative routing — a connector cannot override\n * them per call) so the runner mediator can pick the platform refresh `kind`\n * and `id`.\n *\n * Namespace fallback: when no `connector:<id>` pre-mint entry exists, the\n * lookup retries under the legacy `mount:<id>` key. This is a defence-in-depth\n * companion to the platform-side pre-mint namespace alignment — see the\n * 2026-05-19 incident notes and `_devlog/specs/2026-05-07-unified-credential-mediation.md`.\n * When the fallback fires, a `warn` log signals that the platform writer is\n * filing credentials under the pre-unified namespace key.\n */\n private buildWrappedMediator(declaration: ConnectorDeclaration): TokenMediator | undefined {\n const original = this.tokenMediator;\n const preMinted = this.preMintedSecrets;\n const driver = declaration.driver;\n // The runner mediator refreshes against the backend provider link, not the\n // connector id. Prefer the top-level field; fall back to options for wire\n // shapes that nest it there.\n const optionsLink = declaration.options?.providerLinkId;\n const providerLinkId =\n declaration.providerLinkId ?? (typeof optionsLink === \"string\" ? optionsLink : undefined);\n if (!preMinted) return original;\n\n return async ({ connectorId, reason }) => {\n if (reason === \"initial\") {\n let mint = preMinted.mintFor(\"connector\", connectorId);\n if (!mint) {\n const fallback = preMinted.mintFor(\"mount\", connectorId);\n if (fallback) {\n mint = fallback;\n this.mgrLog.warn(\"connector credential resolved via mount-namespace fallback\", {\n connectorId,\n });\n }\n }\n if (mint?.ok) {\n this.mgrLog.debug(\"initial token served from pre-mint\", { connectorId });\n return { ok: true, token: mint.token, expiresAt: mint.expiresAt };\n }\n // Pre-mint exists but failed at the platform mediator — surface the real reason.\n if (mint && !mint.ok) {\n return {\n ok: false,\n code: mint.code ?? \"not-configured\",\n message:\n mint.message ??\n `Connector '${connectorId}' pre-mint failed at the backend mediator (no detail provided).`,\n };\n }\n // No pre-mint entry: fall through to the original mediator.\n }\n if (!original) {\n return {\n ok: false,\n code: \"not-configured\",\n message:\n `Connector '${connectorId}' requested ${reason} token but no pre-mint ` +\n `is available and no runner-side mediator is wired.`,\n };\n }\n return original({ connectorId, reason, driver, providerLinkId });\n };\n }\n\n /**\n * Resolve a connector by driver name: registry first, then catalog.\n */\n private async resolveConnector(driver: string): Promise<Connector> {\n // 1. Check the connector registry.\n const registered = tryGetConnector(driver);\n if (registered) return registered;\n\n // 2. Catalog lookup — for third-party / project-local connectors that have\n // not been published to the registry.\n const entry = this.catalogEntries.find((e) => e.kind === \"connector\" && e.name === driver);\n if (!entry) {\n throw new Error(\n `Unknown connector: \"${driver}\". ` +\n `Run 'skaile search connector' to see available connectors.`,\n );\n }\n\n // 3. Dynamic import from source path (dev-only; does not work in compiled binary)\n const entryPoint = (entry.metadata?.entry as string) ?? \"./connector.ts\";\n const connectorPath = resolve(dirname(entry.source), entryPoint);\n const mod = await import(connectorPath);\n if (typeof mod.createConnector !== \"function\") {\n throw new Error(\n `Connector \"${driver}\" at ${connectorPath} does not export createConnector()`,\n );\n }\n const connector: Connector = mod.createConnector();\n\n // Intentional singleton cache: register a ConnectorTarget whose factory\n // always returns the same resolved instance for catalog-resolved connectors\n // (ported from old ConnectorManager.resolveAdapter). The earlier\n // `tryGetConnector(driver)` returned undefined, so this id is unregistered\n // and the register cannot collide.\n if (!pluginRegistry.get(\"connector\", driver)) {\n pluginRegistry.register(\"connector\", {\n id: driver,\n displayName: driver,\n apiVersion: 1,\n configSchema: z.unknown(),\n create: () => connector,\n });\n }\n return connector;\n }\n\n /**\n * Compute the absolute mount-target directory for a filesystem-face connector.\n *\n * - `local` driver + absolute source + no explicit target → bind directly to source\n * - otherwise → `decl.mount.target ?? .mounts/<id>`, resolved relative to workspaceDir\n */\n private resolveMountTarget(declaration: ConnectorDeclaration): string {\n const mountConf = declaration.mount;\n if (\n declaration.driver === \"local\" &&\n !mountConf?.target &&\n mountConf?.source?.startsWith(\"/\")\n ) {\n return mountConf.source;\n }\n const mountPath = mountConf?.target ?? `.mounts/${declaration.id}`;\n return resolve(this.workspaceDir, mountPath);\n }\n\n // Record absPath → id: same-id is idempotent, an exact-equal collision throws\n // (naming both ids + the path) so a silent shadow fails at setup, nesting warns.\n private reserveMountTarget(id: string, absPath: string): void {\n const owner = this.mountTargets.get(absPath);\n if (owner === id) return;\n if (owner !== undefined) {\n throw new Error(\n `Mount target collision: connectors \"${owner}\" and \"${id}\" both resolve to ` +\n `\"${absPath}\". Each filesystem connector needs a distinct mount.target.`,\n );\n }\n for (const [otherPath, otherId] of this.mountTargets) {\n if (otherId === id) continue;\n if (isStrictlyNested(absPath, otherPath) || isStrictlyNested(otherPath, absPath)) {\n this.mgrLog.warn(\"nested mount target overlap between connectors\", {\n connectorId: id,\n otherConnectorId: otherId,\n target: absPath,\n otherTarget: otherPath,\n });\n }\n }\n this.mountTargets.set(absPath, id);\n }\n\n /** Release every mount target owned by `id` (on disconnect). */\n private releaseMountTarget(id: string): void {\n for (const [path, owner] of [...this.mountTargets]) {\n if (owner === id) this.mountTargets.delete(path);\n }\n }\n\n /**\n * Build a `ConnectContext` for a connector, resolving fields and — for\n * filesystem-face connectors — allocating the mount-target directory.\n */\n private async buildConnectContext(\n declaration: ConnectorDeclaration,\n connector: Connector,\n ): Promise<ConnectContext> {\n const ctx: ConnectContext = {\n secrets: this.chain ?? this.secrets,\n // Both filesystem and tool faces use this for the auth: backend initial-mint path.\n tokenMediator: this.buildWrappedMediator(declaration),\n abortSignal: this.disposeController.signal,\n };\n\n // Backend-auth connectors get their credential from the tokenMediator, not the\n // field chain — skip resolveFields so a required field (e.g. postgres dsn)\n // doesn't throw before connect() can consult the mediator.\n if (this.chain && connector.describeFields && declaration.auth !== \"backend\") {\n const fields = connector.describeFields();\n ctx.resolvedFields = await resolveFields(declaration, fields, this.chain);\n }\n\n // Filesystem face: allocate the mount target. Reserve it first so two\n // connectors resolving to the same path collide loudly here instead of\n // silently shadowing each other once both are mounted.\n if (connector.filesystem != null) {\n const absPath = this.resolveMountTarget(declaration);\n this.reserveMountTarget(declaration.id, absPath);\n if (!existsSync(absPath)) mkdirSync(absPath, { recursive: true });\n ctx.mountTarget = absPath;\n }\n\n return ctx;\n }\n\n /**\n * Span-wrapping helper for connector lifecycle calls.\n */\n private async withSpan<T>(\n name: string,\n attrs: Record<string, string | number | boolean>,\n fn: () => Promise<T>,\n ): Promise<T> {\n const telemetry = this.opts.telemetry;\n const trace = this.opts.trace;\n if (!telemetry || !trace) return fn();\n\n const span = telemetry.startSpan(trace, {\n name,\n kind: \"connector_op\",\n attributes: attrs,\n });\n\n try {\n const result = await fn();\n telemetry.endSpan(span, { status: \"ok\" });\n return result;\n } catch (err) {\n telemetry.endSpan(span, {\n status: \"error\",\n error: (err as Error).message,\n });\n throw err;\n }\n }\n\n // ── Bulk lifecycle ────────────────────────────────────────────────────────────\n\n /**\n * Connect all declared connectors. For each connector:\n * 1. Resolves the `Connector` from the registry (or catalog).\n * 2. Calls `setLogger` when available.\n * 3. Resolves fields via `describeFields()` + secret chain.\n * 4. For filesystem-face connectors: allocates mount-target dir.\n * 5. Calls `connector.connect(decl, ctx)`.\n * 6. Tracks in the active map; emits `onStatusChange`.\n *\n * After the loop, if `options.failOnReadWriteError` is set and any read-write\n * connector with a `mount` config failed → throws `ConnectorStartupError`\n * (fail-fast lifecycle semantics for mountable connectors).\n *\n * When `options.deferMounts` is set, connectors whose filesystem face is\n * marked `deferMount` (rclone-backed FUSE mounts) are NOT awaited here:\n * their target is pre-registered (so the mount path renders in the system\n * prompt immediately) and the actual mount is driven on a background task.\n * The returned report therefore covers only the eagerly-connected set, so a\n * slow remote can never gate whatever the caller does next (e.g. emitting\n * `session_init_ack`). Deferred connectors surface their progress through\n * `onStatusChange` (connecting → connected | error).\n *\n * @param declarations - Connector declarations from `skaile.yaml`.\n * @param options.failOnReadWriteError - Throw `ConnectorStartupError` if any\n * read-write connector fails. Read-only failures are always tolerated.\n * Only the eager set is considered — deferred mounts never throw.\n * @param options.deferMounts - Bring `deferMount` filesystem-face connectors\n * up in the background instead of awaiting them.\n */\n async connectAll(\n declarations: ConnectorDeclaration[],\n options?: { failOnReadWriteError?: boolean; deferMounts?: boolean },\n ): Promise<ConnectorStartupReport> {\n this.mgrLog.info(\"connectAll start\", { count: declarations.length });\n\n // Pre-flight: reserve each mount-bearing declaration's resolved target up\n // front so a duplicate-target misconfig throws here, before any connect\n // attempt swallows it into a per-connector result. Only `mount`-bearing\n // declarations can collide — the no-mount default (`.mounts/<id>`) is unique\n // per id — so the cheap guard avoids resolving every connector just to find\n // its target.\n for (const decl of declarations) {\n if (decl.mount != null) this.reserveMountTarget(decl.id, this.resolveMountTarget(decl));\n }\n\n const results: ConnectorStartupReport[\"results\"] = [];\n\n // Partition into eager (awaited) and deferred (background) sets. A\n // resolution failure leaves the connector in the eager set so the\n // synchronous connect path records its per-connector error exactly as\n // before. Classification is skipped entirely when deferMounts is off so\n // the common path keeps its single per-connector resolve.\n const eager: Array<{ decl: ConnectorDeclaration; connector?: Connector }> = [];\n const deferred: Array<{ decl: ConnectorDeclaration; connector: Connector }> = [];\n if (options?.deferMounts) {\n for (const decl of declarations) {\n let connector: Connector | undefined;\n try {\n connector = await this.resolveConnector(decl.driver);\n } catch {\n // Falls through to the eager path, which re-resolves and records the\n // error in `results` — preserving the existing failure surface.\n }\n if (connector?.filesystem?.deferMount === true) {\n deferred.push({ decl, connector });\n } else {\n eager.push({ decl, connector });\n }\n }\n } else {\n for (const decl of declarations) eager.push({ decl });\n }\n\n for (const { decl, connector } of eager) {\n results.push(await this.attemptConnect(decl, connector));\n }\n\n // Deferred mounts: pre-register each so its deterministic mount path renders\n // immediately, then drive the real mounts on a tracked background task that\n // dispose() can await/cancel.\n if (deferred.length > 0) {\n // Await pre-registration so every deferred remote mount has its read-only\n // barrier in place BEFORE connectAll returns — i.e. before the runner\n // emits session_init_ack. There must be no window where the bare writable\n // target is exposed to the agent.\n for (const { decl, connector } of deferred) {\n await this.preRegisterDeferred(decl, connector);\n }\n // Chain onto any prior batch (a second connectAll) so dispose /\n // whenDeferredMountsSettled await every in-flight mount, not just the last.\n const prior = this.deferredConnect;\n this.deferredConnect = (async () => {\n if (prior) await prior;\n await this.connectDeferred(deferred);\n })();\n }\n\n const report: ConnectorStartupReport = { results };\n this.mgrLog.info(\"connectAll complete\", {\n connected: results.filter((r) => r.connected).length,\n failed: results.filter((r) => !r.connected).length,\n });\n\n // Throw if any read-write mountable connector (with a mount block) failed.\n // Tool-only connectors (no mount block) are never fail-fast — they are\n // reported in the results like any other failure (fail-fast behaviour for\n // read-write connectors only).\n if (options?.failOnReadWriteError) {\n const declById = new Map(declarations.map((d) => [d.id, d]));\n const failedRw = results\n .filter(\n (r) => !r.connected && r.access === \"read-write\" && declById.get(r.id)?.mount != null,\n )\n .map((r) => ({ id: r.id, error: r.error ?? \"unknown error\" }));\n if (failedRw.length > 0) {\n const summary = failedRw.map((f) => `\"${f.id}\": ${f.error}`).join(\"; \");\n this.mgrLog.error(\"connectAll failed: required read-write connector(s) failed\", undefined, {\n summary,\n });\n throw new ConnectorStartupError(\n `Required read-write connector(s) failed to connect: ${summary}`,\n report,\n failedRw,\n );\n }\n }\n\n return report;\n }\n\n /**\n * Connect a single declaration, emitting `connecting` → `connected | error`.\n * Never throws — failures are recorded in the returned result so `connectAll`\n * can keep going. Shared by the eager loop and the deferred background task.\n */\n private async attemptConnect(\n decl: ConnectorDeclaration,\n preResolved?: Connector,\n ): Promise<ConnectorStartupReport[\"results\"][number]> {\n this.opts.onStatusChange?.({\n type: \"connector_status\",\n connectorId: decl.id,\n status: \"connecting\",\n });\n\n try {\n const connector = preResolved ?? (await this.resolveConnector(decl.driver));\n const connectorLog = createLogger({\n kind: \"connector\",\n subkind: connector.name ?? decl.driver,\n instance: decl.id,\n });\n connector.setLogger?.(connectorLog);\n\n const ctx = await this.buildConnectContext(decl, connector);\n\n const handle = await this.withSpan(\n \"connector.connect\",\n {\n \"skaile.connector.id\": decl.id,\n \"skaile.connector.driver\": decl.driver,\n \"skaile.connector.operation\": \"connect\",\n },\n () => connector.connect(decl, ctx),\n );\n\n // A deferred connector pre-registered a provisional entry; close any\n // watcher attached to it before replacing it with the real handle so a\n // mid-flight watchAll() does not leak a dangling watch handle.\n const previous = this.active.get(decl.id);\n if (previous?.watchHandle) {\n try {\n await previous.watchHandle.close();\n } catch {\n // Best-effort\n }\n }\n\n // Carry forward any read-only placeholder / fleet health gate from the\n // provisional entry so a deferred mount's barrier is still torn down on\n // disconnect (the real rclone mount is stacked on top of it) and the fleet\n // gate keeps tracking health after the live handle swaps in.\n this.active.set(decl.id, {\n connector,\n handle,\n declaration: decl,\n placeholderTarget: previous?.placeholderTarget,\n fleetHealthGate: previous?.fleetHealthGate,\n fleetHealthTarget: previous?.fleetHealthTarget,\n });\n this.opts.onStatusChange?.({\n type: \"connector_status\",\n connectorId: decl.id,\n status: \"connected\",\n });\n return {\n id: decl.id,\n connected: true,\n mountPath: handle.mountPath,\n access: decl.access,\n };\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n this.mgrLog.error(\"connect failed\", err, { id: decl.id, driver: decl.driver });\n this.opts.onStatusChange?.({\n type: \"connector_status\",\n connectorId: decl.id,\n status: \"error\",\n error: msg,\n });\n return {\n id: decl.id,\n connected: false,\n error: msg,\n access: decl.access,\n };\n }\n }\n\n /**\n * Register a provisional entry for a deferred filesystem-face connector so\n * its (deterministic) mount path shows up in `listConnectors()` / the system\n * prompt before the background mount completes.\n *\n * Before exposing the target, a read-only barrier is established so the agent\n * cannot write a phantom workspace into a not-yet-mounted remote.\n *\n * Fleet-managed mounts skip the *static* boot-time barrier (the host already\n * bound the live share at the target — a static barrier would shadow real\n * content) but instead get a *dynamic* health gate: while the host fleet rclone\n * is healthy the target stays writable exactly as before; when it wedges, the\n * gate establishes the same read-only barrier until the mount recovers.\n */\n private async preRegisterDeferred(\n decl: ConnectorDeclaration,\n connector: Connector,\n ): Promise<void> {\n const mountTarget = this.resolveMountTarget(decl);\n if (!existsSync(mountTarget)) mkdirSync(mountTarget, { recursive: true });\n\n const fleetManaged = isFleetManaged(decl.id);\n let placeholderTarget: string | undefined;\n let fleetHealthGate: FleetHealthGate | undefined;\n let fleetHealthTarget: string | undefined;\n if (fleetManaged) {\n // Start un-gated (healthy assumption) so a healthy fleet mount is writable\n // exactly as today; the poll / platform signal trips the gate on failure.\n fleetHealthGate = new FleetHealthGate(mountTarget, this.placeholderBarrier, this.mgrLog);\n fleetHealthTarget = mountTarget;\n } else {\n try {\n await this.placeholderBarrier.establish(mountTarget, this.mgrLog);\n placeholderTarget = mountTarget;\n } catch (err) {\n // establish() degrades internally; a throw here is unexpected. Record it\n // and continue — pre-registration must not gate the eager phase.\n this.mgrLog.error(\"deferred mount barrier establish failed\", err, { id: decl.id });\n }\n }\n\n const handle: ConnectorHandle = {\n id: decl.id,\n driver: connector.name ?? decl.driver,\n access: decl.access,\n status: \"connecting\",\n mountPath: mountTarget,\n // Empty (not null) so a best-effort disconnect of a still-provisional\n // entry — e.g. a deferred mount that errored — finds no live handle and\n // returns cleanly instead of dereferencing null state.\n state: {},\n };\n this.active.set(decl.id, {\n connector,\n handle,\n declaration: decl,\n placeholderTarget,\n fleetHealthGate,\n fleetHealthTarget,\n });\n if (fleetHealthGate) this.ensureFleetHealthPoll();\n }\n\n /**\n * Start the periodic local fleet-health probe if it is not already running and\n * the poll interval is enabled. Each tick probes every fleet target and feeds\n * the verdict to its gate (hysteresis lives in the gate). The probe catches both\n * directly-detectable failures (EIO / dead bind) AND host-mount recovery while a\n * placeholder is up; silent degradation is covered by the platform signal via\n * `reportFleetHealth`.\n */\n private ensureFleetHealthPoll(): void {\n if (this.fleetHealthTimer || this.fleetHealthPollMs <= 0 || this.disposed) return;\n this.fleetHealthTimer = setInterval(() => {\n void this.runFleetHealthProbe();\n }, this.fleetHealthPollMs);\n // Do not keep the event loop alive solely for the probe.\n this.fleetHealthTimer.unref?.();\n }\n\n private async runFleetHealthProbe(): Promise<void> {\n if (this.disposed) return;\n const gates = [...this.active.values()].filter(\n (e): e is ActiveConnector & { fleetHealthGate: FleetHealthGate; fleetHealthTarget: string } =>\n e.fleetHealthGate != null && e.fleetHealthTarget != null,\n );\n await Promise.all(\n gates.map(async (e) => {\n const verdict = e.fleetHealthGate.isGated\n ? await this.probeGatedRecovery(e.fleetHealthGate)\n : await probeFleetHealth(e.fleetHealthTarget);\n await e.fleetHealthGate.observe(verdict).catch(() => {});\n }),\n );\n }\n\n /**\n * Detect host-mount RECOVERY for an already-gated target so the placeholder lifts\n * edge-triggered (no restart). Over an opaque mask a stat/readdir reads the 0555\n * mask and falsely reads healthy, so recovery is detected via the mount table;\n * non-opaque surfaces hold their current surface until the platform signal lifts.\n * Rationale: `_devlog/notes/2026-06-17-fleet-gate-edge-triggered-recovery.md`.\n */\n private async probeGatedRecovery(gate: FleetHealthGate): Promise<FleetHealthVerdict> {\n const target = gate.mountTarget;\n if (!(this.placeholderBarrier.isOpaque?.(target) ?? false)) {\n // Keep the current surface (masked→error, ro→degraded); platform-driven lift.\n return gate.currentSurface === \"ro\" ? \"degraded\" : \"error\";\n }\n return (await this.fleetMountRecoveryProbe(target)) ? \"healthy\" : \"error\";\n }\n\n /**\n * Feed an externally-derived fleet-health verdict for a connector into its gate.\n *\n * This is the consume side of the platform fleet-health signal: the host fleet\n * health poll knows `core/stats.errors` and can detect a *silently-empty-but-\n * writable* degraded mount that the local probe cannot. The runner watches the\n * `<workspace>/.skaile/fleet-health/<connectorId>` flag and forwards its verdict\n * here. Unknown / non-fleet ids are ignored.\n *\n * The verdict drives the gate across three surfaces (writable / read-only-\n * readable / masked): `healthy` lifts any barrier, `degraded` downgrades to a\n * read-only surface that keeps the live content visible, `error` keeps the\n * opaque mask.\n *\n * A deferred remote mount may have been brought up with the *static* boot-time\n * barrier (it was not fleet-managed at connect — e.g. the host bind landed\n * late, after `connectAll` placed the not-ready barrier). When a fleet verdict\n * later arrives for such a connector, a gate is created lazily over that same\n * barrier (seeded `masked`, matching the static barrier already in place) so the\n * authoritative platform signal can lift or downgrade it — otherwise a late-\n * arriving live mount stays masked forever even after it goes healthy.\n */\n async reportFleetHealth(connectorId: string, verdict: FleetHealthVerdict): Promise<void> {\n const entry = this.active.get(connectorId);\n if (!entry) return;\n if (!entry.fleetHealthGate) {\n // Only a static boot-time barrier exists; promote it to a gate so the\n // platform signal can drive it. No barrier at all ⇒ nothing to gate.\n if (!entry.placeholderTarget) return;\n entry.fleetHealthTarget = entry.placeholderTarget;\n entry.fleetHealthGate = new FleetHealthGate(\n entry.placeholderTarget,\n this.placeholderBarrier,\n this.mgrLog,\n { initialSurface: \"masked\" },\n );\n }\n await entry.fleetHealthGate.observe(verdict).catch(() => {});\n }\n\n /** Drive all deferred mounts concurrently; resolves when every one settles. */\n private async connectDeferred(\n deferred: Array<{ decl: ConnectorDeclaration; connector: Connector }>,\n ): Promise<void> {\n await Promise.allSettled(\n deferred.map(({ decl, connector }) => this.connectDeferredOne(decl, connector)),\n );\n }\n\n /**\n * Background-connect one deferred mount. On success `attemptConnect` swaps the\n * provisional entry for the real handle; on failure the provisional entry is\n * marked `error` so the mount path keeps rendering as \"still syncing\". If the\n * manager was disposed mid-flight, the connector that came up is torn down\n * immediately so no rclone process leaks.\n */\n private async connectDeferredOne(\n decl: ConnectorDeclaration,\n connector: Connector,\n ): Promise<void> {\n if (this.disposed) return;\n // Lift the barrier rw so `fusermount3` can pass its W_OK mountpoint check.\n // See _devlog/notes/2026-06-12-fusermount3-mountpoint-write-access.md\n const preEntry = this.active.get(decl.id);\n if (preEntry?.placeholderTarget && this.placeholderBarrier.prepareForStackedMount) {\n await this.placeholderBarrier\n .prepareForStackedMount(preEntry.placeholderTarget, this.mgrLog)\n .catch(() => {});\n }\n const result = await this.attemptConnect(decl, connector);\n if (!result.connected) {\n const entry = this.active.get(decl.id);\n if (entry && entry.handle.status === \"connecting\") entry.handle.status = \"error\";\n // Mount failed: re-assert the read-only barrier so the target stays\n // un-writable while it shows as \"failed / still syncing\".\n const failTarget = entry?.placeholderTarget ?? preEntry?.placeholderTarget;\n if (failTarget && this.placeholderBarrier.restoreBarrier) {\n await this.placeholderBarrier.restoreBarrier(failTarget, this.mgrLog).catch(() => {});\n }\n return;\n }\n // Mount is live and stacked over the placeholder — it now provides write\n // access (shadows the barrier).\n const entry = this.active.get(decl.id);\n if (entry?.placeholderTarget) {\n await this.placeholderBarrier\n .onMountLive(entry.placeholderTarget, this.mgrLog)\n .catch(() => {});\n }\n if (this.disposed && this.active.has(decl.id)) {\n await this.disconnect(decl.id).catch(() => {});\n }\n }\n\n /**\n * Resolve once every background (deferred) mount started by `connectAll` has\n * settled. Resolves immediately when none are in flight. Useful for tests and\n * for callers that want to await full readiness.\n */\n async whenDeferredMountsSettled(): Promise<void> {\n if (this.deferredConnect) await this.deferredConnect.catch(() => {});\n }\n\n /** Disconnect all connectors and stop all watchers. Best-effort — ignores disconnect errors. */\n async disconnectAll(): Promise<void> {\n this.mgrLog.info(\"disconnectAll start\", { count: this.active.size });\n // Signal in-flight background mounts to bail, then let the tracked task\n // settle so anything that did come up is captured in `active` (and thus\n // unmounted below). The abort + each connector's own spawn timeout bound\n // this wait; a well-behaved deferred connect() observes ctx.abortSignal.\n this.disposed = true;\n this.disposeController.abort();\n if (this.fleetHealthTimer) {\n clearInterval(this.fleetHealthTimer);\n this.fleetHealthTimer = undefined;\n }\n if (this.deferredConnect) {\n try {\n await this.deferredConnect;\n } catch {\n // The task is Promise.allSettled-backed so this is unreachable today;\n // kept defensive in case the deferred pipeline gains a throwing step.\n }\n this.deferredConnect = undefined;\n }\n await this.unwatchAll();\n for (const [id, entry] of this.active) {\n try {\n await entry.connector.disconnect(entry.handle);\n } catch {\n // Best-effort cleanup\n }\n // Remove the read-only barrier / fleet gate AFTER the connector (and its\n // stacked rclone mount, if any) is gone, so unmount order is top-down with\n // no leak.\n if (entry.placeholderTarget) {\n await this.placeholderBarrier.remove(entry.placeholderTarget, this.mgrLog).catch(() => {});\n }\n if (entry.fleetHealthGate) await entry.fleetHealthGate.dispose().catch(() => {});\n this.opts.onStatusChange?.({\n type: \"connector_status\",\n connectorId: id,\n status: \"disconnected\",\n });\n }\n this.active.clear();\n this.mountTargets.clear();\n this.mgrLog.info(\"disconnectAll complete\");\n }\n\n // ── Hot-plug ──────────────────────────────────────────────────────────────────\n\n /**\n * Connect a single connector (hot-plug). Resolves fields and allocates\n * mount target if the connector has a filesystem face.\n *\n * This path connects immediately and does NOT establish the read-only\n * deferred-mount barrier — bring `deferMount` (rclone-backed) connectors up\n * through `connectAll({ deferMounts: true })` so the not-ready guarantee holds.\n *\n * @returns The `ConnectorHandle` for subsequent operations.\n */\n async connect(declaration: ConnectorDeclaration): Promise<ConnectorHandle> {\n // Emit \"connecting\" before attempting\n this.opts.onStatusChange?.({\n type: \"connector_status\",\n connectorId: declaration.id,\n status: \"connecting\",\n });\n\n const connector = await this.resolveConnector(declaration.driver);\n const connectorLog = createLogger({\n kind: \"connector\",\n subkind: connector.name ?? declaration.driver,\n instance: declaration.id,\n });\n connector.setLogger?.(connectorLog);\n\n const ctx = await this.buildConnectContext(declaration, connector);\n\n try {\n const handle = await this.withSpan(\n \"connector.connect\",\n {\n \"skaile.connector.id\": declaration.id,\n \"skaile.connector.driver\": declaration.driver,\n \"skaile.connector.operation\": \"connect\",\n },\n () => connector.connect(declaration, ctx),\n );\n this.active.set(declaration.id, { connector, handle, declaration });\n this.opts.onStatusChange?.({\n type: \"connector_status\",\n connectorId: declaration.id,\n status: \"connected\",\n });\n return handle;\n } catch (err) {\n // connect() failed after buildConnectContext reserved the target but before\n // the connector entered `active`, so disconnect() can't reach it — release\n // here or the path stays blocked for other ids until disconnectAll().\n this.releaseMountTarget(declaration.id);\n const msg = err instanceof Error ? err.message : String(err);\n this.opts.onStatusChange?.({\n type: \"connector_status\",\n connectorId: declaration.id,\n status: \"error\",\n error: msg,\n });\n throw err;\n }\n }\n\n /**\n * Disconnect a single connector by ID and stop its watcher.\n *\n * @throws {Error} if the connector is not found\n */\n async disconnect(id: string): Promise<void> {\n const entry = this.get(id);\n if (entry.watchHandle) {\n try {\n await entry.watchHandle.close();\n } catch {\n // Best-effort\n }\n }\n await this.withSpan(\n \"connector.disconnect\",\n {\n \"skaile.connector.id\": id,\n \"skaile.connector.driver\": entry.connector.name,\n \"skaile.connector.operation\": \"disconnect\",\n },\n async () => {\n try {\n await entry.connector.disconnect(entry.handle);\n } finally {\n // Remove the read-only barrier / fleet gate after the connector (and any\n // stacked rclone mount) is gone — top-down unmount, no leak.\n if (entry.placeholderTarget) {\n await this.placeholderBarrier\n .remove(entry.placeholderTarget, this.mgrLog)\n .catch(() => {});\n }\n if (entry.fleetHealthGate) await entry.fleetHealthGate.dispose().catch(() => {});\n this.active.delete(id);\n this.releaseMountTarget(id);\n this.opts.onStatusChange?.({\n type: \"connector_status\",\n connectorId: id,\n status: \"disconnected\",\n });\n }\n },\n );\n }\n\n // ── Watch ─────────────────────────────────────────────────────────────────────\n\n /**\n * Start watchers for all connected connectors that expose a `watch()` method.\n * For filesystem-face connectors, nested-mount-path exclusion logic is applied.\n */\n watchAll(\n callback: (connectorId: string, event: ConnectorChangeEvent) => void,\n options?: WatchOptions,\n ): void {\n // Collect all mount paths for nested-path exclusion\n const allMountPaths = [...this.active.values()]\n .map((e) => e.handle.mountPath)\n .filter((p): p is string => p != null);\n\n for (const [id, entry] of this.active) {\n if (!entry.connector.watch) continue;\n\n // Respect explicit watch flag; default: watch read-write, skip read-only.\n // For tool-only connectors (no mount block) this evaluates to\n // `access !== \"read-only\"`.\n const shouldWatch =\n entry.declaration.mount?.watch ?? entry.declaration.access !== \"read-only\";\n if (!shouldWatch) continue;\n\n // For filesystem connectors: build per-connector ignore list excluding\n // mount paths of other connectors nested inside this one.\n let mergedOptions = options;\n const myPath = entry.handle.mountPath;\n if (myPath) {\n const nestedPaths = allMountPaths\n .filter((p) => p !== myPath && p.startsWith(`${myPath}/`))\n .map((p) => `${p}/**`);\n if (nestedPaths.length > 0) {\n mergedOptions = {\n ...options,\n ignored: [...(options?.ignored ?? []), ...nestedPaths],\n };\n }\n }\n\n try {\n entry.watchHandle = entry.connector.watch(\n entry.handle,\n (event) => callback(id, event),\n mergedOptions,\n );\n } catch {\n // Best-effort — connector may not support watching in current state\n }\n }\n }\n\n /** Stop all active watchers. */\n async unwatchAll(): Promise<void> {\n for (const [, entry] of this.active) {\n if (entry.watchHandle) {\n try {\n await entry.watchHandle.close();\n } catch {\n // Best-effort\n }\n entry.watchHandle = undefined;\n }\n }\n }\n\n // ── Session lifecycle ─────────────────────────────────────────────────────────\n\n async hibernateAll(): Promise<LifecycleResult[]> {\n return this.runLifecycleHook(\"onHibernate\");\n }\n\n async closeAll(): Promise<LifecycleResult[]> {\n return this.runLifecycleHook(\"onSessionClose\");\n }\n\n private async runLifecycleHook(\n hook: \"onHibernate\" | \"onSessionClose\",\n ): Promise<LifecycleResult[]> {\n const results: LifecycleResult[] = [];\n for (const [id, entry] of this.active) {\n // A deferred mount that never finished connecting (still \"connecting\", or\n // \"error\") has a provisional handle (empty state); there's nothing to\n // hibernate/close, and running the hook would claim a flush that never\n // happened. Mirror the syncAll guard (skip anything not \"connected\").\n if (entry.handle.status !== \"connected\") {\n results.push({ id, ok: true });\n continue;\n }\n const fn = entry.connector[hook];\n if (!fn) {\n results.push({ id, ok: true });\n continue;\n }\n try {\n const detail = await fn.call(entry.connector, entry.handle);\n results.push({ id, ok: true, detail: detail ?? undefined });\n } catch (err) {\n results.push({\n id,\n ok: false,\n error: err instanceof Error ? err.message : String(err),\n });\n }\n }\n return results;\n }\n\n // ── Discovery ─────────────────────────────────────────────────────────────────\n\n /**\n * Return the internal `ActiveConnector` entry.\n *\n * @throws {Error} if the connector is not found\n */\n get(id: string): ActiveConnector {\n const entry = this.active.get(id);\n if (!entry) throw new Error(`Connector not found: \"${id}\"`);\n return entry;\n }\n\n has(id: string): boolean {\n return this.active.has(id);\n }\n\n /**\n * Return summary info for all currently connected connectors.\n */\n listConnectors(): Array<{\n id: string;\n driver: string;\n label?: string;\n access: \"read-only\" | \"read-write\";\n mountPath?: string;\n status: ConnectorHandle[\"status\"];\n }> {\n return [...this.active.entries()].map(([id, entry]) => ({\n id,\n driver: entry.connector.name,\n label: entry.declaration.label,\n access: entry.declaration.access,\n mountPath: entry.handle.mountPath,\n // Surfaced so wire projections (splitConnectorsForWire) can distinguish a\n // still-connecting deferred mount from a fully-mounted one.\n status: entry.handle.status,\n }));\n }\n\n /**\n * Lists git-backed connectors, surfacing the fields prompt-builders and the\n * runner's wake-mid-401 refresh handler need.\n */\n listGitConnectors(): Array<{\n id: string;\n source: string;\n exposeAccessToken: boolean;\n auth?: string;\n }> {\n const out: Array<{ id: string; source: string; exposeAccessToken: boolean; auth?: string }> =\n [];\n for (const [, entry] of this.active) {\n if (entry.connector.name !== \"git\") continue;\n const mountConf = entry.declaration.mount;\n out.push({\n id: entry.declaration.id,\n source: mountConf?.source ?? \"\",\n exposeAccessToken: mountConf?.exposeAccessToken === true,\n auth: entry.declaration.auth,\n });\n }\n return out;\n }\n\n // ── Sync ──────────────────────────────────────────────────────────────────────\n\n /**\n * Pull the latest remote state for a single filesystem-face connector.\n *\n * @throws {Error} if connector is not found or has no filesystem face.\n */\n async sync(id: string, options?: SyncOptions): Promise<SyncResult> {\n const entry = this.get(id);\n if (!entry.connector.filesystem) {\n throw new Error(`Connector \"${id}\" has no filesystem face`);\n }\n return entry.connector.filesystem.sync(entry.handle, options);\n }\n\n /**\n * Pull the latest remote state for all connected filesystem-face connectors.\n * Errors from individual connectors are captured and returned rather than thrown.\n */\n async syncAll(options?: SyncOptions): Promise<SyncConnectorResult[]> {\n const results: SyncConnectorResult[] = [];\n for (const [id, entry] of this.active) {\n if (!entry.connector.filesystem) continue;\n // Skip a deferred mount that hasn't finished connecting: its handle is\n // provisional (empty state), so sync() would flush against a non-existent\n // rclone handle. A lifecycle flush before the background mount settles is\n // a no-op, not an error.\n if (entry.handle.status !== \"connected\") continue;\n try {\n await entry.connector.filesystem.sync(entry.handle, options);\n results.push({ id, ok: true });\n } catch (err) {\n results.push({ id, ok: false, error: err instanceof Error ? err.message : String(err) });\n }\n }\n return results;\n }\n\n // ── Base CRUD dispatch ────────────────────────────────────────────────────────\n\n /**\n * Throw a consistent error when the tools face is absent.\n */\n private requireToolFace(id: string, entry: ActiveConnector): ToolFace {\n if (!entry.connector.tools) {\n throw new Error(`Connector \"${id}\" has no tool face`);\n }\n return entry.connector.tools;\n }\n\n async read(id: string, path: string): Promise<ConnectorContent | null> {\n const entry = this.get(id);\n const tools = this.requireToolFace(id, entry);\n if (!tools.read) {\n throw new Error(`Connector \"${id}\" tool face does not implement \"read\"`);\n }\n return this.withSpan(\n \"connector.read\",\n {\n \"skaile.connector.id\": id,\n \"skaile.connector.driver\": entry.connector.name,\n \"skaile.connector.operation\": \"read\",\n },\n () => tools.read!(entry.handle, path),\n );\n }\n\n async write(id: string, path: string, content: ConnectorContent): Promise<void> {\n const entry = this.get(id);\n if (entry.declaration.access === \"read-only\") {\n throw new Error(`Connector \"${id}\" is read-only`);\n }\n const tools = this.requireToolFace(id, entry);\n if (!tools.write) {\n throw new Error(`Connector \"${id}\" tool face does not implement \"write\"`);\n }\n return this.withSpan(\n \"connector.write\",\n {\n \"skaile.connector.id\": id,\n \"skaile.connector.driver\": entry.connector.name,\n \"skaile.connector.operation\": \"write\",\n },\n () => tools.write!(entry.handle, path, content),\n );\n }\n\n async delete(id: string, path: string): Promise<boolean> {\n const entry = this.get(id);\n if (entry.declaration.access === \"read-only\") {\n throw new Error(`Connector \"${id}\" is read-only`);\n }\n const tools = this.requireToolFace(id, entry);\n if (!tools.delete) {\n throw new Error(`Connector \"${id}\" tool face does not implement \"delete\"`);\n }\n return this.withSpan(\n \"connector.delete\",\n {\n \"skaile.connector.id\": id,\n \"skaile.connector.driver\": entry.connector.name,\n \"skaile.connector.operation\": \"delete\",\n },\n () => tools.delete!(entry.handle, path),\n );\n }\n\n async list(id: string, path?: string, options?: ListOptions): Promise<ConnectorEntry[]> {\n const entry = this.get(id);\n const tools = this.requireToolFace(id, entry);\n if (!tools.list) {\n throw new Error(`Connector \"${id}\" tool face does not implement \"list\"`);\n }\n return this.withSpan(\n \"connector.list\",\n {\n \"skaile.connector.id\": id,\n \"skaile.connector.driver\": entry.connector.name,\n \"skaile.connector.operation\": \"list\",\n },\n () => tools.list!(entry.handle, path, options),\n );\n }\n\n async search(id: string, query: string, options?: SearchOptions): Promise<SearchResult[]> {\n const entry = this.get(id);\n const tools = this.requireToolFace(id, entry);\n if (!tools.search) {\n throw new Error(`Connector \"${id}\" tool face does not implement \"search\"`);\n }\n return this.withSpan(\n \"connector.search\",\n {\n \"skaile.connector.id\": id,\n \"skaile.connector.driver\": entry.connector.name,\n \"skaile.connector.operation\": \"search\",\n },\n () => tools.search!(entry.handle, query, options),\n );\n }\n\n // ── Custom operations ─────────────────────────────────────────────────────────\n\n /**\n * Execute a custom operation on a connector's tool face.\n *\n * @throws {Error} if connector has no tool face, operation is unknown, or\n * a write operation is called on a read-only connector.\n */\n async executeOp(id: string, operation: string, args: Record<string, unknown>): Promise<string> {\n const entry = this.get(id);\n const tools = this.requireToolFace(id, entry);\n\n const ops = tools.describeOperations(entry.handle);\n const opDesc = ops.find((o) => o.name === operation);\n if (!opDesc) {\n throw new Error(\n `Connector \"${id}\" has no operation \"${operation}\". Available: ${ops.map((o) => o.name).join(\", \")}`,\n );\n }\n if (opDesc.accessLevel === \"write\" && entry.declaration.access === \"read-only\") {\n throw new Error(\n `Operation \"${operation}\" requires write access but connector \"${id}\" is read-only`,\n );\n }\n\n return this.withSpan(\n \"connector.executeOp\",\n {\n \"skaile.connector.id\": id,\n \"skaile.connector.driver\": entry.connector.name,\n \"skaile.connector.operation\": operation,\n },\n () => tools.executeOp(entry.handle, operation, args),\n );\n }\n\n /**\n * Return the list of operations that a connector's tool face exposes.\n * Returns an empty array when the connector has no tool face.\n */\n getOperations(id: string): OperationDescriptor[] {\n const entry = this.get(id);\n return entry.connector.tools?.describeOperations(entry.handle) ?? [];\n }\n\n // ── Skill catalog ─────────────────────────────────────────────────────────────\n\n /**\n * Return `RuntimeSkillDescriptor` for every connected connector.\n * Uses `tools.describeSkill()` when available; falls back to `buildDefaultSkillDescriptor`.\n */\n listSkills(): RuntimeSkillDescriptor[] {\n return [...this.active.values()].map(({ connector, handle, declaration }) => {\n const describeSkill = connector.tools?.describeSkill;\n return describeSkill\n ? describeSkill.call(connector.tools, handle, declaration)\n : buildDefaultSkillDescriptor(connector, declaration, handle);\n });\n }\n\n /**\n * Return the rendered skill body for a single connector.\n *\n * @param id - Connector ID.\n * @param shellAccess - When true (default), CLI-style commands are used;\n * false renders SDK tool-call style.\n * @throws {Error} if the connector is not found.\n */\n loadSkill(id: string, shellAccess = true): string {\n const entry = this.get(id);\n const { connector, handle, declaration } = entry;\n const describeSkill = connector.tools?.describeSkill;\n const descriptor = describeSkill\n ? describeSkill.call(connector.tools, handle, declaration)\n : buildDefaultSkillDescriptor(connector, declaration, handle);\n const ops = connector.tools?.describeOperations(handle) ?? [];\n return buildSkillBody(descriptor, ops, shellAccess);\n }\n}\n","/**\n * Merged prompt/tool-delivery module for the unified ConnectorManager.\n *\n * Combines the responsibilities of:\n * - `mount-prompt.ts` — build a system-prompt section for filesystem-face connectors\n * - `connector-tools.ts` — build an SDK MCP server + system-prompt section for tool-face connectors\n *\n * Two exports:\n * 1. `buildConnectorPromptSection(manager, options?)` — markdown string for the\n * agent's system prompt. Iterates the unified manager's connectors and:\n * - if `connector.filesystem` is present → emits a Mounts table row (ported from mount-prompt.ts)\n * - if `connector.tools` is present → emits a Connectors list entry (ported from connector-tools.ts)\n * - dual-face connectors emit BOTH\n *\n * 2. `buildSdkConnectorTools(manager, options?)` — in-process MCP server config for\n * the Claude Agent SDK. Only tool-face connectors are wired to tools; filesystem-only\n * connectors are silently excluded.\n *\n * @docLink packages/connectors/concepts#connector-prompt\n */\n\n// Static namespace import so bun --compile bundles zod into the binary.\n// Dynamic import(\"zod\") via a string variable evades bun's static analysis\n// and fails at runtime inside /$bunfs/. The unwrap (zNS.z ?? zNS.default\n// ?? zNS) handles both bun's native ESM and vitest's CJS-interop resolver,\n// which return the zod namespace at different keys.\nimport * as zNS from \"zod\";\nimport type { ConnectorManager } from \"./connector-manager.js\";\n\nconst zStatic: any = (zNS as any).z ?? (zNS as any).default ?? zNS;\n\n// ── Options ───────────────────────────────────────────────────────────────────\n\n/**\n * Options for `buildSdkConnectorTools`.\n * @docLink packages/connectors/api-reference#connector-tool-options\n */\nexport interface ConnectorToolOptions {\n /** Pre-loaded `@anthropic-ai/claude-agent-sdk` instance (optional; auto-imported if absent). */\n sdk?: any;\n /** Pre-loaded `zod` namespace (optional; uses static import if absent). */\n z?: any;\n /** Whether the agent has shell access. Defaults to true. When true, `connector_exec` is omitted. */\n shellAccess?: boolean;\n}\n\n/**\n * Options for `buildConnectorPromptSection`.\n * @docLink packages/connectors/api-reference#connector-prompt-options\n */\nexport interface ConnectorPromptOptions {\n /** Whether the agent has shell access. Defaults to true. Affects CLI vs SDK tool examples. */\n shellAccess?: boolean;\n}\n\n// ── SDK tool builder ──────────────────────────────────────────────────────────\n\n/**\n * Build an in-process MCP server exposing connector tools for the Claude Agent SDK.\n * Only connectors with a `tools` face are wired; filesystem-only connectors are excluded.\n * Returns the server config to pass as `mcpServers` in the SDK query options.\n * Returns `null` if `@anthropic-ai/claude-agent-sdk` is not available.\n *\n * @param manager - Connected unified `ConnectorManager`.\n * @param options - Optional SDK/Zod overrides and shell access flag.\n * @returns MCP server config object or `null`.\n * @docLink packages/connectors/api-reference#build-sdk-connector-tools\n */\nexport async function buildSdkConnectorTools(\n manager: ConnectorManager,\n options?: ConnectorToolOptions,\n): Promise<object | null> {\n const shellAccess = options?.shellAccess ?? true;\n\n let sdk: any = options?.sdk;\n if (!sdk) {\n try {\n sdk = await import(\"@anthropic-ai/claude-agent-sdk\");\n } catch {\n return null;\n }\n }\n\n const z: any = options?.z ?? zStatic;\n\n const tools: any[] = [];\n\n // ── Discovery ──\n\n tools.push({\n name: \"connector_list\",\n description:\n \"List all currently registered connectors with their id, driver, access mode, and available operations. Use this to discover connectors that may have been added after session start (e.g. shared-state stores like 'presence' or 'session' pushed by the host).\",\n inputSchema: {},\n handler: async () => {\n try {\n const entries = manager.listConnectors();\n return { content: [{ type: \"text\" as const, text: JSON.stringify(entries, null, 2) }] };\n } catch (err: any) {\n return {\n content: [{ type: \"text\" as const, text: `Error: ${err.message}` }],\n isError: true,\n };\n }\n },\n });\n\n tools.push({\n name: \"connector_load_skill\",\n description:\n \"Load full instructions for a specific connector into context. Returns a markdown document describing the connector and its available CLI commands.\",\n inputSchema: {\n connector_id: z.string().describe(\"Connector ID (use connector_list to enumerate)\"),\n },\n handler: async ({ connector_id }: { connector_id: string }) => {\n try {\n const body = manager.loadSkill(connector_id, shellAccess);\n return { content: [{ type: \"text\" as const, text: body }] };\n } catch (err: any) {\n return {\n content: [{ type: \"text\" as const, text: `Error: ${err.message}` }],\n isError: true,\n };\n }\n },\n });\n\n // ── Base CRUD (tool-face connectors only) ──\n\n tools.push({\n name: \"connector_read\",\n description:\n 'Read content from a connector by path. For KV stores, path is the key. For databases, path is \"table/pk\".',\n inputSchema: {\n connector_id: z.string().describe(\"Connector ID\"),\n path: z.string().describe(\"Path within the connector\"),\n },\n handler: async ({ connector_id, path }: { connector_id: string; path: string }) => {\n try {\n const content = await manager.read(connector_id, path);\n return {\n content: [{ type: \"text\" as const, text: content?.data?.toString() ?? \"(empty)\" }],\n };\n } catch (err: any) {\n return {\n content: [{ type: \"text\" as const, text: `Error: ${err.message}` }],\n isError: true,\n };\n }\n },\n });\n\n tools.push({\n name: \"connector_write\",\n description: \"Write content to a connector at a path.\",\n inputSchema: {\n connector_id: z.string().describe(\"Connector ID\"),\n path: z.string().describe(\"Path within the connector\"),\n content: z.string().describe(\"Content to write\"),\n },\n handler: async ({\n connector_id,\n path,\n content,\n }: {\n connector_id: string;\n path: string;\n content: string;\n }) => {\n try {\n await manager.write(connector_id, path, { data: content });\n return { content: [{ type: \"text\" as const, text: \"Written.\" }] };\n } catch (err: any) {\n return {\n content: [{ type: \"text\" as const, text: `Error: ${err.message}` }],\n isError: true,\n };\n }\n },\n });\n\n tools.push({\n name: \"connector_list_entries\",\n description: \"List entries in a connector (files, keys, rows, etc).\",\n inputSchema: {\n connector_id: z.string().describe(\"Connector ID\"),\n path: z.string().optional().describe(\"Path prefix or directory\"),\n recursive: z.boolean().optional().describe(\"Include nested entries\"),\n },\n handler: async ({\n connector_id,\n path,\n recursive,\n }: {\n connector_id: string;\n path?: string;\n recursive?: boolean;\n }) => {\n try {\n const entries = await manager.list(connector_id, path, { recursive });\n return { content: [{ type: \"text\" as const, text: JSON.stringify(entries, null, 2) }] };\n } catch (err: any) {\n return {\n content: [{ type: \"text\" as const, text: `Error: ${err.message}` }],\n isError: true,\n };\n }\n },\n });\n\n tools.push({\n name: \"connector_search\",\n description: \"Search within a connector for matching content.\",\n inputSchema: {\n connector_id: z.string().describe(\"Connector ID\"),\n query: z.string().describe(\"Search query\"),\n },\n handler: async ({ connector_id, query }: { connector_id: string; query: string }) => {\n try {\n const results = await manager.search(connector_id, query);\n return { content: [{ type: \"text\" as const, text: JSON.stringify(results, null, 2) }] };\n } catch (err: any) {\n return {\n content: [{ type: \"text\" as const, text: `Error: ${err.message}` }],\n isError: true,\n };\n }\n },\n });\n\n tools.push({\n name: \"connector_delete\",\n description: \"Delete an entry from a connector.\",\n inputSchema: {\n connector_id: z.string().describe(\"Connector ID\"),\n path: z.string().describe(\"Path to delete\"),\n },\n handler: async ({ connector_id, path }: { connector_id: string; path: string }) => {\n try {\n const ok = await manager.delete(connector_id, path);\n return { content: [{ type: \"text\" as const, text: ok ? \"Deleted.\" : \"Not found.\" }] };\n } catch (err: any) {\n return {\n content: [{ type: \"text\" as const, text: `Error: ${err.message}` }],\n isError: true,\n };\n }\n },\n });\n\n // ── Fallback: connector_exec (only when no shell access) ──\n\n if (!shellAccess) {\n tools.push({\n name: \"connector_exec\",\n description:\n \"Execute a custom connector operation by name. Use only when shell access is unavailable. Load the connector skill first to see available operations and their arguments.\",\n inputSchema: {\n connector_id: z.string().describe(\"Connector ID\"),\n operation: z.string().describe(\"Operation name (e.g. 'send_message', 'query')\"),\n args: z\n .record(z.unknown())\n .describe(\"Named arguments for the operation (without -- prefix)\"),\n },\n handler: async ({\n connector_id,\n operation,\n args,\n }: {\n connector_id: string;\n operation: string;\n args: Record<string, unknown>;\n }) => {\n try {\n const result = await manager.executeOp(connector_id, operation, args);\n return { content: [{ type: \"text\" as const, text: result }] };\n } catch (err: any) {\n return {\n content: [{ type: \"text\" as const, text: `Error: ${err.message}` }],\n isError: true,\n };\n }\n },\n });\n }\n\n return sdk.createSdkMcpServer({ name: \"skaile-connectors\", tools });\n}\n\n// ── System prompt section builder ─────────────────────────────────────────────\n\n/**\n * Build a markdown section describing all connectors for the agent's system prompt.\n *\n * Iterates the unified `ConnectorManager` and, per connector:\n * - **Filesystem face** (`connector.filesystem != null`) → emits a row in the\n * `## Mounts` table (id, driver, mount path, access level), plus Tier-1/Tier-2\n * git auth guidance for `git` connectors (ported from `mount-prompt.ts`).\n * - **Tool face** (`connector.tools != null`) → emits an entry in the\n * `## Connectors` section (ported from `connector-tools.ts`).\n * - Dual-face connectors appear in BOTH sections.\n *\n * @param manager - Connected unified `ConnectorManager`.\n * @param options - Optional shell access flag.\n * @returns Markdown string to append to the system prompt, or empty string when\n * no connectors are connected.\n * @docLink packages/connectors/api-reference#build-connector-prompt-section\n */\nexport function buildConnectorPromptSection(\n manager: ConnectorManager,\n options?: ConnectorPromptOptions,\n): string {\n const shellAccess = options?.shellAccess ?? true;\n const allConnectors = manager.listConnectors();\n if (allConnectors.length === 0) return \"\";\n\n const sections: string[] = [];\n\n // ── Resolve each connector's faces in a single pass (I-2) ───────────────────\n // Each connector is looked up once; the result is shared by both the filesystem\n // section and the tool section below. A connector with neither face is silently\n // omitted — in the unified Connector model every connector is expected to have\n // at least one face (filesystem or tools). A face-less connector is a\n // misconfiguration, not a normal state, so excluding it from the prompt is\n // correct-by-design (unified-model invariant: every connector has ≥1 face).\n const faces = allConnectors.map((c) => {\n try {\n const e = manager.get(c.id);\n return { c, fs: e.connector.filesystem != null, tools: e.connector.tools != null };\n } catch {\n return { c, fs: false, tools: false };\n }\n });\n\n const fsConnectors = faces.filter((f) => f.fs).map((f) => f.c);\n const toolConnectors = faces.filter((f) => f.tools).map((f) => f.c);\n\n // ── Filesystem-face section (ported from mount-prompt.ts) ────────────────────\n\n if (fsConnectors.length > 0) {\n sections.push(buildFilesystemSection(manager, fsConnectors));\n }\n\n // ── Tool-face section (ported from connector-tools.ts) ───────────────────────\n\n if (toolConnectors.length > 0) {\n sections.push(buildToolSection(manager, toolConnectors, shellAccess));\n }\n\n return sections.join(\"\\n\\n\");\n}\n\n// ── System prompt section helpers ─────────────────────────────────────────────\n\n/** Connector descriptors as returned by `ConnectorManager.listConnectors()`. */\ntype ConnectorEntry = ReturnType<ConnectorManager[\"listConnectors\"]>[number];\n\n/**\n * Build the `## Mounts` filesystem-face section: the mount table, the\n * unavailable-mounts note, and the Tier-1/Tier-2 git auth notes.\n */\nfunction buildFilesystemSection(manager: ConnectorManager, fsConnectors: ConnectorEntry[]): string {\n const lines: string[] = [\n \"## Mounts\",\n \"\",\n \"The following directories are mounted resources. Read and write files normally.\",\n \"\",\n \"| Mount | Driver | Path | Access |\",\n \"|---|---|---|---|\",\n ];\n\n // A mount whose status is not \"connected\" is a deferred remote mount that is\n // still syncing (or failed) — its target is held read-only so the agent\n // cannot write a phantom workspace into it. Surface that instead of a normal\n // writable row; the platform flips it on the connected status event.\n let anyUnavailable = false;\n for (const c of fsConnectors) {\n const mountPath = c.mountPath ?? \"(unmounted)\";\n if (c.status === \"connected\") {\n lines.push(`| ${c.id} | ${c.driver} | \\`${mountPath}/\\` | ${c.access} |`);\n } else {\n anyUnavailable = true;\n const state = c.status === \"error\" ? \"failed\" : \"syncing\";\n lines.push(\n `| ${c.id} | ${c.driver} | \\`${mountPath}/\\` | unavailable (${state}) — read-only, do not write |`,\n );\n }\n }\n\n if (anyUnavailable) {\n lines.push(\"\");\n lines.push(\n \"> **Unavailable mounts are read-only at the filesystem layer.** A mount marked \" +\n \"`unavailable (syncing / failed)` is not live yet — its directory is mounted read-only, \" +\n \"so writes fail. Do not create files there: the contents are not the real workspace, and \" +\n \"anything you write would be a phantom that diverges from the remote once it mounts. Wait \" +\n \"for it to become writable (watch the connector status).\",\n );\n }\n\n appendGitAuthNotes(lines, manager, fsConnectors);\n\n return lines.join(\"\\n\");\n}\n\n/**\n * Append the Tier-2 / Tier-1 git auth notes (spec: 2026-05-05-git-credential-tiers).\n * Intersect listGitConnectors() with the filesystem-face set so the note\n * and the mount table stay coherent: a git connector with only a tools face\n * (no filesystem face) is absent from the table and must not drive a note\n * inside ## Mounts. listGitConnectors() does NOT filter by face — it returns\n * all connected git-driver connectors regardless of which faces they expose.\n */\nfunction appendGitAuthNotes(\n lines: string[],\n manager: ConnectorManager,\n fsConnectors: ConnectorEntry[],\n): void {\n const fsConnectorIds = new Set(fsConnectors.map((c) => c.id));\n const gitConnectors = manager.listGitConnectors().filter((g) => fsConnectorIds.has(g.id));\n if (gitConnectors.length === 0) return;\n\n const tier2 = gitConnectors.filter((m) => m.exposeAccessToken === true);\n const tier1 = gitConnectors.filter((m) => m.exposeAccessToken !== true);\n\n if (tier2.length > 0) {\n const hosts = [...new Set(tier2.map((m) => safeHost(m.source)))].filter(Boolean);\n lines.push(\"\");\n lines.push(\n `> **Git auth (CLI):** the git CLI is authenticated for the duration of this session ` +\n `for ${hosts.map((h) => `\\`${h}\\``).join(\", \")}. Use \\`git push\\` / \\`git pull\\` directly.`,\n );\n }\n if (tier1.length > 0) {\n lines.push(\"\");\n lines.push(\n \"> **Git auth (mount-managed):** `git push` / `git pull` against mount remotes go \" +\n \"through the workspace mount, not the agent. If a network git command fails with \" +\n '\"could not read Username\", do not retry — the credential is intentionally not ' +\n \"exposed to the CLI. Use the workspace's autoPush / autoPull or ask the user to \" +\n 'enable \"Allow agent to use git CLI directly\" on the mount.',\n );\n }\n}\n\n/** Build the `## Connectors` tool-face section. */\nfunction buildToolSection(\n manager: ConnectorManager,\n toolConnectors: ConnectorEntry[],\n shellAccess: boolean,\n): string {\n const lines: string[] = [\"## Connectors\", \"\"];\n\n lines.push(\"Currently registered connectors (id — driver, access):\");\n for (const r of toolConnectors) {\n lines.push(`- \\`${r.id}\\` — ${r.driver}, ${r.access}`);\n }\n lines.push(\"\");\n lines.push(\n \"Additional connectors may be registered mid-session by the host — notably shared-state stores (driver: `xstate-store`, e.g. `session`, `presence`, per-component stores). Re-enumerate with `connector_list` whenever you need the live set.\",\n );\n lines.push(\"\");\n\n // Eager preset instructions — one block per connector that has a body.\n for (const r of toolConnectors) {\n let instructions: string | undefined;\n try {\n instructions = manager.get(r.id).declaration.instructions;\n } catch {\n // connector no longer active — skip\n }\n if (instructions && instructions.trim().length > 0) {\n lines.push(`Guidance for \\`${r.id}\\`:`);\n lines.push(instructions.trim());\n lines.push(\"\");\n }\n }\n\n if (shellAccess) {\n lines.push(\"Discover connectors:\");\n lines.push(\"- `connector_list` tool — returns the live connector set as JSON.\");\n lines.push(\"- `skaile connector list` (CLI) — shell equivalent.\");\n lines.push(\"- `skaile connector <id> --ops` — list a connector's operations.\");\n lines.push(\n \"Call the `connector_load_skill` tool to load a connector's full instructions into context.\",\n );\n lines.push(\n \"Interact with connectors via their CLI commands (see loaded skill body for exact syntax).\",\n );\n } else {\n lines.push(\"Discover connectors with the `connector_list` tool (returns live JSON).\");\n lines.push(\n \"Call the `connector_load_skill` tool to load a connector's full instructions into context.\",\n );\n lines.push(\n \"Use the `connector_exec` tool to execute connector operations — do not use CLI commands.\",\n );\n }\n\n return lines.join(\"\\n\");\n}\n\n// ── Private helpers ───────────────────────────────────────────────────────────\n\nfunction safeHost(source: string): string {\n try {\n return new URL(source).host;\n } catch {\n return source;\n }\n}\n","/**\n * Credential helper script renderer — generates a POSIX `sh` script that git\n * invokes via `credential.<urlPrefix>.helper = !sh <path>` to fetch credentials\n * for a Tier-2 git mount.\n *\n * The script implements the wake-mid-401 hardening described in\n * `_devlog/specs/2026-05-07-unified-credential-mediation.md` § Step 9a:\n *\n * 1. On `op = get`, stat the credentials file and compute its age (mtime).\n * 2. If age > triggerAgeSec, touch the refresh-flag file. The runner watches\n * this path via `fs.watch` and mints a fresh access token + rewrites the\n * credentials file when it sees the change.\n * 3. Poll the credentials file's mtime in 200ms increments until the mtime\n * advances OR waitTimeoutMs elapses.\n * 4. Translate the credentials file (`scheme://user:pass@host <tag>` lines —\n * git's `store --file=` format) into the helper-output format git\n * expects (`username=<value>\\npassword=<value>\\n`). Filters lines by the\n * mount's url-prefix tag so multi-mount workspaces stay isolated.\n *\n * **Cross-platform**: targets POSIX `sh` (Linux + macOS). Avoids bashisms so\n * `dash`, `ash`, and `busybox sh` all work. The two GNU/BSD divergence points\n * are handled inline:\n *\n * - `stat -c %Y <file>` (GNU/Linux) vs `stat -f %m <file>` (BSD/macOS) —\n * try GNU first, fall back to BSD, default to 0.\n * - `sleep 0.2` is non-portable — use `usleep 200000` when present, else\n * fall back to `sleep 1`.\n *\n * The credentials file format is unchanged (Option B in the Step 9a plan):\n * `scheme://user:pass@host <tag>` per mount, written by `writeMountBlock`.\n * The helper script does the translation to `username=<>\\npassword=<>\\n`\n * inline so we don't have to change the on-disk format and break Step 1A\n * back-compat.\n *\n * Spec: `_devlog/specs/2026-05-07-unified-credential-mediation.md`.\n */\n\n/** Required arguments for {@link renderCredentialHelperScript}. */\nexport interface RenderHelperOpts {\n /** Absolute path to the per-mount credentials file. */\n credentialsPath: string;\n /**\n * Absolute path to the workspace-level refresh-request flag file. The\n * runner watches this file via `fs.watch` and triggers a token refresh on\n * `change`.\n */\n refreshFlagPath: string;\n /**\n * Tag emitted by `writeMountBlock` on the credential line for this mount\n * (e.g. `# skaile-mount: workspace`). The helper greps for lines ending in\n * this tag so concurrent mounts in the same credentials file stay isolated.\n */\n credentialTag: string;\n /**\n * Touch the refresh-flag if the credentials file is older than this (in\n * seconds). Default: 300 (5 minutes — comfortably shorter than the typical\n * 1-hour Anthropic OAuth lifetime, well clear of the 5-minute pre-expiry\n * refresh window scheduled by the driver).\n */\n triggerAgeSec?: number;\n /**\n * Maximum time to wait for the credentials file mtime to advance after\n * touching the refresh-flag (in milliseconds). Default: 5000 (5 seconds —\n * long enough for the runner's debounced watcher + token mediator round-\n * trip; short enough that a stuck backend doesn't block git for minutes).\n */\n waitTimeoutMs?: number;\n}\n\n/**\n * Render the credential-helper script body. The returned string should be\n * written to disk with mode `0755` (owner rwx, group/other rx) so git can\n * execute it.\n *\n * `git` invokes credential helpers with one of three operations as `$1`:\n * - `get` — read credentials. We respond with the helper-output format.\n * - `store` — git wants us to remember a credential. We're a one-way\n * read-only helper; ignore.\n * - `erase` — git wants us to forget a credential. Same — ignore.\n *\n * Only `get` triggers the refresh-flag dance. Other ops exit silently with 0\n * so git falls back to the next helper in the chain (or its own prompt).\n *\n * The script also drains stdin on `get` because git always pipes the request\n * envelope (host, protocol, path, etc.) into the helper's stdin. Leaving it\n * unread can wedge git's helper FD.\n */\nexport function renderCredentialHelperScript(opts: RenderHelperOpts): string {\n const triggerAgeSec = opts.triggerAgeSec ?? 300;\n const waitTimeoutMs = opts.waitTimeoutMs ?? 5_000;\n // Round timeout up to whole seconds for the `sleep 1` fallback path.\n const waitTimeoutSec = Math.max(1, Math.ceil(waitTimeoutMs / 1_000));\n\n // Embed paths verbatim. Operators are responsible for not including funky\n // characters in their workspace path; we already control these (they live\n // under `<projectDir>/.skaile/`).\n const credPath = opts.credentialsPath;\n const flagPath = opts.refreshFlagPath;\n const tag = opts.credentialTag;\n\n return `#!/bin/sh\n# Generated by skaile-runner -- do not edit.\n# Tier-2 git credential helper: serves the latest cached token and triggers a\n# wake-mid-401 refresh when the credentials file is older than ${triggerAgeSec}s.\n# Spec: _devlog/specs/2026-05-07-unified-credential-mediation.md\n\nset -u\n\nop=\"\\${1:-}\"\n# 'store' and 'erase' are no-ops -- this is a read-only helper. Other ops\n# (none today) also bail silently so we don't break future git versions.\n[ \"$op\" = \"get\" ] || exit 0\n\nCRED_FILE='${credPath}'\nFLAG_FILE='${flagPath}'\nTAG='${tag}'\n\n# Drain stdin: git always pipes the request envelope. Leaving it unread can\n# wedge git's helper FD. We don't actually need any of it -- the credentials\n# file already keys by URL prefix via the helper's gitconfig block.\ncat > /dev/null 2>&1 || true\n\n# Bail silently if the credentials file is missing or empty: git falls\n# through to the next helper or its own prompt.\n[ -s \"$CRED_FILE\" ] || exit 0\n\n# Cross-platform mtime in epoch seconds: GNU stat -c first (Linux), then BSD\n# stat -f (macOS), then 0 if neither is present (in which case we skip the\n# refresh-flag dance entirely and just serve what we have).\nget_mtime() {\n stat -c %Y \"$1\" 2>/dev/null || stat -f %m \"$1\" 2>/dev/null || echo 0\n}\n\nnow=$(date +%s 2>/dev/null || echo 0)\nmtime=$(get_mtime \"$CRED_FILE\")\nage=$((now - mtime))\n\nif [ \"$age\" -gt ${triggerAgeSec} ]; then\n # Touch the refresh-flag (atomic open+close emits 'change' to fs.watch).\n : > \"$FLAG_FILE\" 2>/dev/null || true\n\n # Poll for the credentials file mtime to advance. usleep gives sub-second\n # resolution where available; sleep 1 is the portable fallback.\n end=$((now + ${waitTimeoutSec}))\n while :; do\n cur=$(date +%s 2>/dev/null || echo 0)\n if [ \"$cur\" -ge \"$end\" ]; then\n break\n fi\n new_mtime=$(get_mtime \"$CRED_FILE\")\n if [ \"$new_mtime\" -gt \"$mtime\" ]; then\n break\n fi\n if command -v usleep >/dev/null 2>&1; then\n usleep 200000\n else\n sleep 1\n fi\n done\nfi\n\n# Find the credential line for THIS mount (matched by the trailing tag) and\n# translate from git's 'store --file=' format ('scheme://user:pass@host <tag>')\n# into the helper-output format ('username=<>\\\\npassword=<>\\\\n'). If there's\n# more than one matching line (shouldn't happen but defence-in-depth), we\n# take the last one (most recently written).\nline=$(grep -F \" $TAG\" \"$CRED_FILE\" 2>/dev/null | tail -n 1)\n[ -n \"$line\" ] || exit 0\n\n# Strip the trailing ' <TAG>' from the URL.\nurl=\\${line% *}\n# Extract user:pass between scheme:// and @host. The token (pass) was\n# percent-encoded at write time (buildCredentialLine), so any literal '@' in it\n# stays encoded here -- the rightmost '@' is unambiguously the host delimiter.\n# scheme://user:pass@host -> user:pass\nuserinfo=\\${url#*://}\nuserinfo=\\${userinfo%@*}\nuser=\\${userinfo%%:*}\npass=\\${userinfo#*:}\n\n# Percent-decode the token (encodeURIComponent inverse). '%XX' -> byte; no '+'\n# handling needed since encodeURIComponent emits '%20' for spaces.\npass=$(printf '%b' \"$(printf '%s' \"$pass\" | sed 's/%/\\\\\\\\x/g')\")\n\n# git wants line-oriented key=value pairs followed by a blank line.\nprintf 'username=%s\\\\n' \"$user\"\nprintf 'password=%s\\\\n' \"$pass\"\nprintf '\\\\n'\n`;\n}\n","/**\n * LogBuffer — fixed-capacity ring buffer for capturing process stdout/stderr lines.\n * When the buffer is full, the oldest lines are evicted (FIFO).\n * @docLink packages/connectors/api-reference#log-buffer\n */\n\nexport class LogBuffer {\n private readonly lines: string[] = [];\n private readonly capacity: number;\n\n constructor(capacity = 500) {\n this.capacity = capacity;\n }\n\n /** Append a single line. */\n push(line: string): void {\n this.lines.push(line);\n if (this.lines.length > this.capacity) {\n this.lines.shift();\n }\n }\n\n /** Split text on newlines and push each line (preserves empty lines). */\n pushLines(text: string): void {\n const lines = text.split(\"\\n\");\n // Avoid pushing a trailing empty string from \"text\\n\".split(\"\\n\")\n for (let i = 0; i < lines.length; i++) {\n if (i === lines.length - 1 && lines[i] === \"\") break;\n this.push(lines[i]!);\n }\n }\n\n /** Return the last `n` lines. */\n tail(n: number): string[] {\n return this.lines.slice(-n);\n }\n\n /** Clear all stored lines. */\n clear(): void {\n this.lines.length = 0;\n }\n\n /** Current number of stored lines. */\n get size(): number {\n return this.lines.length;\n }\n}\n","/**\n * Managed gitconfig writer — runner-managed credential helper config for\n * Tier-2 mount credentials.\n *\n * The runner exposes `<workspace>/.skaile/managed-gitconfig` to the agent\n * process via `GIT_CONFIG_GLOBAL` (with a fallback `[include]` in\n * `~/.gitconfig`). Each Tier-2 mount writes a tagged block into this file\n * pointing `credential.<urlPrefix>.helper` at the shared `git-credentials`\n * store, plus a single line into the credentials store carrying the actual\n * token. Refresh = atomically rewrite the credential line; the helper picks\n * up the new token on the next git network op.\n *\n * Keying is by **URL prefix**, not bare host: two mounts on `github.com`\n * with disjoint org prefixes (`https://github.com/orgA/`,\n * `https://github.com/orgB/`) coexist via narrower\n * `credential.<prefix>.helper` entries. Same prefix declared by two mounts\n * with different tokens is a true collision and throws\n * {@link ManagedGitconfigCollisionError}.\n *\n * Spec: `_devlog/specs/2026-05-05-git-credential-tiers.md`.\n */\n\nimport {\n chmodSync,\n closeSync,\n existsSync,\n mkdirSync,\n openSync,\n readFileSync,\n renameSync,\n writeSync,\n} from \"node:fs\";\nimport { dirname } from \"node:path\";\n\n// ── Public types ─────────────────────────────────────────────────────────────\n\n/**\n * Thrown when two mounts try to register a credential helper for the same\n * URL prefix with different tokens. The operator must either narrow the URL\n * prefixes (per-org paths) or consolidate the mounts.\n */\nexport class ManagedGitconfigCollisionError extends Error {\n readonly urlPrefix: string;\n readonly existingMountId: string;\n readonly newMountId: string;\n\n constructor(urlPrefix: string, existingMountId: string, newMountId: string) {\n super(\n `Mount '${newMountId}' tried to register URL prefix '${urlPrefix}' ` +\n `but mount '${existingMountId}' already owns it with a different credential. ` +\n `Narrow the prefixes (e.g. include the org segment) or consolidate the mounts.`,\n );\n this.name = \"ManagedGitconfigCollisionError\";\n this.urlPrefix = urlPrefix;\n this.existingMountId = existingMountId;\n this.newMountId = newMountId;\n }\n}\n\n/** Required arguments for {@link writeMountBlock}. */\nexport interface WriteMountBlockOptions {\n /** Mount declaration id; used as the block tag. */\n mountId: string;\n /**\n * URL prefix the credential should authenticate, e.g.\n * `https://github.com` or `https://github.com/orgA/`. Trailing slashes are\n * preserved verbatim (git treats them as different scopes).\n */\n urlPrefix: string;\n /**\n * The token to expose. Written to {@link credentialsPath} as\n * `https://x-access-token:<token>@<host>` for the helper to read.\n */\n token: string;\n /** Absolute path to the managed-gitconfig file. */\n gitconfigPath: string;\n /** Absolute path to the git-credentials store. */\n credentialsPath: string;\n /**\n * Optional: when set, the credential block points `helper = !sh <path>` at\n * this script instead of the static `store --file=` form. The script is\n * the wake-mid-401 helper rendered by `renderCredentialHelperScript` —\n * stats the credentials file's mtime, touches a refresh-flag if the cached\n * token is stale, and translates the `store --file=` line format into the\n * helper-output format git expects.\n *\n * Spec: `_devlog/specs/2026-05-07-unified-credential-mediation.md` Step 9a.\n */\n helperScriptPath?: string;\n}\n\n/** Required arguments for {@link removeMountBlock}. */\nexport interface RemoveMountBlockOptions {\n /** Mount declaration id whose block should be removed. */\n mountId: string;\n /** Absolute path to the managed-gitconfig file. */\n gitconfigPath: string;\n /** Absolute path to the git-credentials store. */\n credentialsPath: string;\n}\n\n/** Required arguments for {@link atomicReplaceCredential}. */\nexport interface AtomicReplaceCredentialOptions {\n /** Mount id (used to find the matching credential line). */\n mountId: string;\n /** URL prefix the credential is keyed by. Same value passed to writeMountBlock. */\n urlPrefix: string;\n /** New token to install. */\n token: string;\n /** Absolute path to the git-credentials store. */\n credentialsPath: string;\n}\n\n// ── Block markers ────────────────────────────────────────────────────────────\n\nconst blockStart = (mountId: string) => `# skaile-mount: ${mountId}`;\nconst blockEnd = (mountId: string) => `# skaile-mount: ${mountId} (end)`;\nconst credentialTag = (mountId: string) => `# skaile-mount: ${mountId}`;\n\n// ── Helpers ──────────────────────────────────────────────────────────────────\n\nfunction readFileOrEmpty(path: string): string {\n try {\n return readFileSync(path, \"utf-8\");\n } catch {\n return \"\";\n }\n}\n\n/**\n * Write a string atomically: tmp file in the same dir, then rename. POSIX\n * rename is atomic on the same filesystem, which is the property we need\n * for refresh-time replacement.\n */\nfunction atomicWrite(path: string, content: string, mode: number): void {\n const dir = dirname(path);\n if (!existsSync(dir)) {\n mkdirSync(dir, { recursive: true, mode: 0o700 });\n }\n const tmp = `${path}.tmp.${process.pid}.${Date.now()}.${Math.random().toString(36).slice(2)}`;\n const fd = openSync(tmp, \"w\", mode);\n try {\n writeSync(fd, content);\n } finally {\n closeSync(fd);\n }\n // Some filesystems honor O_CREAT mode but ignore later edits; reassert.\n chmodSync(tmp, mode);\n renameSync(tmp, path);\n}\n\n/**\n * Extract the `[mountId, content]` block list from a managed-gitconfig file.\n * Anything outside a recognized block is returned as a single anonymous\n * `[\"\", content]` entry to preserve unknown lines on rewrite. This keeps the\n * function idempotent against an empty / hand-edited file.\n */\ntype GitconfigBlock = { mountId: string; lines: string[] };\n\n/**\n * Append a foreign (non-block) line: extend the trailing foreign block if the\n * last block is one, otherwise open a new foreign block under the special \"\"\n * id. Keeps foreign content out of any recognized block on rewrite.\n */\nfunction appendForeignLine(blocks: GitconfigBlock[], line: string): void {\n const last = blocks[blocks.length - 1];\n if (last && last.mountId === \"\") {\n last.lines.push(line);\n } else {\n blocks.push({ mountId: \"\", lines: [line] });\n }\n}\n\n/** Drop trailing foreign blocks that contain only blank lines. */\nfunction trimTrailingEmptyForeignBlock(blocks: GitconfigBlock[]): void {\n while (blocks.length > 0) {\n const last = blocks[blocks.length - 1];\n if (last && last.mountId === \"\" && last.lines.every((l) => l.trim() === \"\")) {\n blocks.pop();\n } else {\n break;\n }\n }\n}\n\nfunction parseBlocks(text: string): Array<{ mountId: string; lines: string[] }> {\n const blocks: GitconfigBlock[] = [];\n let current: GitconfigBlock | null = null;\n\n for (const line of text.split(\"\\n\")) {\n const startMatch = line.match(/^# skaile-mount: (\\S+)$/);\n const endMatch = line.match(/^# skaile-mount: (\\S+) \\(end\\)$/);\n\n if (startMatch) {\n if (current) blocks.push(current);\n current = { mountId: startMatch[1] ?? \"\", lines: [line] };\n continue;\n }\n if (endMatch) {\n if (current) {\n current.lines.push(line);\n blocks.push(current);\n current = null;\n }\n continue;\n }\n if (current) {\n current.lines.push(line);\n } else {\n // Foreign content (user edits, leading blank lines). Keep it out of any\n // block by stashing under the special \"\" id.\n appendForeignLine(blocks, line);\n }\n }\n if (current) blocks.push(current);\n\n trimTrailingEmptyForeignBlock(blocks);\n return blocks;\n}\n\nfunction renderBlocks(blocks: Array<{ mountId: string; lines: string[] }>): string {\n if (blocks.length === 0) return \"\";\n // Join lines, preserving the per-block lines structure. Make sure file ends\n // with a single trailing newline so git's parser is happy.\n const out = blocks.map((b) => b.lines.join(\"\\n\")).join(\"\\n\");\n return out.endsWith(\"\\n\") ? out : `${out}\\n`;\n}\n\nfunction buildBlock(\n mountId: string,\n urlPrefix: string,\n credentialsPath: string,\n helperScriptPath?: string,\n): string[] {\n // Step 9a: when a helperScriptPath is provided, point at the dynamic\n // wake-mid-401 helper instead of the static `store --file=` form. The\n // helper handles stale-token detection + refresh-flag dance and translates\n // the on-disk format into git's helper-output format. See\n // `credential-helper-script.ts`.\n const helperLine = helperScriptPath\n ? `\\thelper = !sh ${helperScriptPath}`\n : `\\thelper = store --file=${credentialsPath}`;\n return [blockStart(mountId), `[credential \"${urlPrefix}\"]`, helperLine, blockEnd(mountId)];\n}\n\nfunction buildCredentialLine(urlPrefix: string, token: string, mountId: string): string {\n // Strip a trailing slash so the credential URL matches what git emits when\n // it queries the helper. Git stores credentials as `scheme://user:pass@host`\n // with no path component.\n const u = new URL(urlPrefix);\n const host = u.host;\n const scheme = u.protocol.replace(/:$/, \"\");\n // Percent-encode the token so an `@`/`:`/`%` in it can't break the helper's\n // `scheme://user:pass@host` parsing; the helper script url-decodes it back.\n const encodedToken = encodeURIComponent(token);\n return `${scheme}://x-access-token:${encodedToken}@${host} ${credentialTag(mountId)}`;\n}\n\nfunction readCredentialLines(path: string): string[] {\n return readFileOrEmpty(path)\n .split(\"\\n\")\n .filter((l) => l.length > 0);\n}\n\nfunction writeCredentialLines(path: string, lines: string[]): void {\n const content = lines.length > 0 ? `${lines.join(\"\\n\")}\\n` : \"\";\n // Mode 0640: owner (skaile-runner) read+write, group (skaile) read-only.\n // Under UID separation (Step 4 of git-credential-tiers), the runner runs as\n // skaile-runner with primary group skaile so the agent process (uid skaile)\n // can read the credentials store via group membership while only the runner\n // can rewrite it.\n atomicWrite(path, content, 0o640);\n}\n\nfunction findExistingBlock(\n blocks: Array<{ mountId: string; lines: string[] }>,\n mountId: string,\n): { mountId: string; lines: string[] } | undefined {\n return blocks.find((b) => b.mountId === mountId);\n}\n\nfunction blockUrlPrefix(block: { lines: string[] }): string | undefined {\n for (const line of block.lines) {\n const m = line.match(/^\\[credential \"(.+)\"\\]$/);\n if (m) return m[1];\n }\n return undefined;\n}\n\n// ── Public API ───────────────────────────────────────────────────────────────\n\n/**\n * Write a credential-helper block for `mountId` into the managed-gitconfig\n * file, and (re)write the matching line in the git-credentials store.\n * Idempotent: re-running with the same arguments is a no-op aside from\n * refreshing the on-disk token. Detects collisions where another mount\n * already owns the same `urlPrefix` and throws\n * {@link ManagedGitconfigCollisionError}.\n *\n * Files are created with mode `0640` — owner (skaile-runner) read+write,\n * group (skaile) read-only. See {@link writeCredentialLines} for the\n * UID-separation rationale.\n */\nexport function writeMountBlock(opts: WriteMountBlockOptions): void {\n const { mountId, urlPrefix, token, gitconfigPath, credentialsPath, helperScriptPath } = opts;\n\n // ── Gitconfig: insert/replace the tagged block ──────────────────────────\n const text = readFileOrEmpty(gitconfigPath);\n const blocks = parseBlocks(text);\n\n // Collision check: any *other* mount block declaring the same urlPrefix?\n for (const b of blocks) {\n if (b.mountId === \"\" || b.mountId === mountId) continue;\n const otherPrefix = blockUrlPrefix(b);\n if (otherPrefix === urlPrefix) {\n throw new ManagedGitconfigCollisionError(urlPrefix, b.mountId, mountId);\n }\n }\n\n const newBlock = {\n mountId,\n lines: buildBlock(mountId, urlPrefix, credentialsPath, helperScriptPath),\n };\n const existing = findExistingBlock(blocks, mountId);\n if (existing) {\n existing.lines = newBlock.lines;\n } else {\n blocks.push(newBlock);\n }\n atomicWrite(gitconfigPath, renderBlocks(blocks), 0o640);\n\n // ── Credentials store: insert/replace the tagged line ───────────────────\n const lines = readCredentialLines(credentialsPath);\n const tag = credentialTag(mountId);\n const filtered = lines.filter((l) => !l.endsWith(tag));\n filtered.push(buildCredentialLine(urlPrefix, token, mountId));\n writeCredentialLines(credentialsPath, filtered);\n}\n\n/**\n * Remove the block tagged for `mountId` from the managed-gitconfig file and\n * the matching credential line. Best-effort: missing files / missing block\n * are not errors.\n */\nexport function removeMountBlock(opts: RemoveMountBlockOptions): void {\n const { mountId, gitconfigPath, credentialsPath } = opts;\n\n // ── Gitconfig ──\n const text = readFileOrEmpty(gitconfigPath);\n if (text.length > 0) {\n const blocks = parseBlocks(text).filter((b) => b.mountId !== mountId);\n atomicWrite(gitconfigPath, renderBlocks(blocks), 0o640);\n }\n\n // ── Credentials ──\n const lines = readCredentialLines(credentialsPath);\n const tag = credentialTag(mountId);\n const filtered = lines.filter((l) => !l.endsWith(tag));\n if (filtered.length !== lines.length) {\n writeCredentialLines(credentialsPath, filtered);\n }\n}\n\n/**\n * Write (or refresh) the credential-helper script at `scriptPath` with mode\n * `0755` so git can execute it via `helper = !sh <scriptPath>`. Idempotent —\n * re-rendering with identical opts produces the same script body, so re-runs\n * are safe. Atomic rename so a concurrent git invocation never sees a\n * half-written file.\n *\n * Spec: `_devlog/specs/2026-05-07-unified-credential-mediation.md` Step 9a.\n */\nexport function writeHelperScript(scriptPath: string, body: string): void {\n // Mode 0755: owner rwx, group/other rx — git executes the script as the\n // agent uid which is in the skaile group; rx for group is the safer choice\n // than rx for other.\n atomicWrite(scriptPath, body, 0o755);\n}\n\n/**\n * Replace just the credential line for `mountId` atomically — refresh path.\n * The gitconfig block (which only points at the helper) does not need to\n * change; the helper re-reads the credentials file on every git network op.\n *\n * Throws if no existing line is found for `mountId` — the caller is\n * expected to have written the initial block via {@link writeMountBlock}.\n */\nexport function atomicReplaceCredential(opts: AtomicReplaceCredentialOptions): void {\n const { mountId, urlPrefix, token, credentialsPath } = opts;\n const lines = readCredentialLines(credentialsPath);\n const tag = credentialTag(mountId);\n const without = lines.filter((l) => !l.endsWith(tag));\n if (without.length === lines.length) {\n throw new Error(\n `atomicReplaceCredential: no existing credential line for mount '${mountId}' in ${credentialsPath}`,\n );\n }\n without.push(buildCredentialLine(urlPrefix, token, mountId));\n writeCredentialLines(credentialsPath, without);\n}\n","/**\n * NpmInstaller — wraps `bun add` to install peer dependencies for connectors.\n *\n * Accepts an injectable `spawn` function so tests can verify calls without\n * running a real subprocess.\n */\n\nimport { createRequire } from \"node:module\";\nimport { pathToFileURL } from \"node:url\";\nimport { portableSpawn } from \"@skaile/workspaces/core\";\n\n/**\n * Result returned by the injectable `SpawnFn`.\n * @docLink packages/connectors/api-reference#spawn-result\n */\nexport interface SpawnResult {\n /** Process exit code. Zero means success. */\n exitCode: number;\n /** Combined stdout + stderr output from the subprocess. */\n output: string;\n}\n\n/**\n * Injectable subprocess spawn function used by `installNpmPackages` and test doubles.\n * @docLink packages/connectors/api-reference#spawn-fn\n */\nexport type SpawnFn = (cmd: string[], opts: { cwd: string }) => Promise<SpawnResult>;\n\n/**\n * Options for `installNpmPackages`. Pass a custom `spawn` to test without running real subprocesses.\n * @docLink packages/connectors/api-reference#install-options\n */\nexport interface InstallOptions {\n /** Injectable spawn function. Defaults to the runtime-portable spawn wrapper. */\n spawn?: SpawnFn;\n}\n\n/**\n * Result returned by `installNpmPackages`.\n * @docLink packages/connectors/api-reference#install-result\n */\nexport interface InstallResult {\n /** `true` when the subprocess exited with code 0. */\n success: boolean;\n /** Combined stdout + stderr from the `bun add` invocation. */\n output: string;\n}\n\n/** Default spawn implementation using the runtime-portable subprocess helper. */\nexport async function defaultSpawn(cmd: string[], opts: { cwd: string }): Promise<SpawnResult> {\n const proc = portableSpawn(cmd, { cwd: opts.cwd });\n const [stdout, stderr, exitCode] = await Promise.all([\n new Response(proc.stdout).text(),\n new Response(proc.stderr).text(),\n proc.exited,\n ]);\n return { exitCode, output: stdout + stderr };\n}\n\n/**\n * Install npm packages as optional peer deps using `bun add --optional`.\n *\n * @param packages Package names to install (e.g. [\"pg\", \"@types/pg\"]).\n * @param projectDir Absolute path to the project root (where bun.lock lives).\n * @param opts Injectable options for testing.\n */\nexport async function installNpmPackages(\n packages: string[],\n projectDir: string,\n opts?: InstallOptions,\n): Promise<InstallResult> {\n if (packages.length === 0) {\n return { success: true, output: \"\" };\n }\n\n const spawnFn = opts?.spawn ?? defaultSpawn;\n const result = await spawnFn([\"bun\", \"add\", \"--optional\", ...packages], {\n cwd: projectDir,\n });\n\n return {\n success: result.exitCode === 0,\n output: result.output,\n };\n}\n\n/**\n * Check whether an npm package can be resolved from `projectDir`'s module\n * graph. Returns true when `require.resolve` finds the package, false on any\n * resolution failure (missing, broken, etc.). Does not load the module — only\n * verifies it can be located.\n *\n * Use this to decide whether `installNpmPackages` needs to run before a\n * connector adapter or mount driver tries to `import` its peer dep.\n */\nexport function isPackageResolvable(pkg: string, projectDir: string): boolean {\n try {\n const require = createRequire(pathToFileURL(`${projectDir}/`).href);\n require.resolve(pkg);\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Filter a list of npm packages down to those that cannot be resolved from\n * `projectDir`. Convenience for \"install only what's missing\" call sites.\n */\nexport function findMissingPackages(packages: string[], projectDir: string): string[] {\n return packages.filter((p) => !isPackageResolvable(p, projectDir));\n}\n","/**\n * Proactive + reactive OAuth token refresh for rclone-backed mounts.\n * See `connectors/CLAUDE.md` § Rclone Process Manager → Token refresh.\n */\n\nimport type { TokenMediator } from \"./connector-types.js\";\nimport type { RcloneHandle } from \"./rclone-process-manager.js\";\n\n/**\n * Safety margin between the scheduled refresh and the token's declared expiry.\n * Default 5 minutes: long enough that any in-flight read/write at fire time\n * still has a usable token through the recycle, short enough that a server\n * clock skew of a few seconds does not push the fire-time past expiry. Matches\n * the AI-credential and git-mount refresh leads.\n */\nexport const PROACTIVE_RCLONE_REFRESH_MARGIN_MS = 5 * 60 * 1000;\n\n/** Default cooldown suppressing reactive triggers right after a refresh. */\nexport const DEFAULT_REACTIVE_COOLDOWN_MS = 30 * 1000;\n\n/**\n * `setTimeout` stores its delay in a 32-bit signed int; a larger delay silently\n * wraps to 1ms (fires immediately). A token whose expiry is further out than\n * this is armed in capped chunks, re-arming until the real fire-time arrives.\n */\nconst MAX_TIMER_MS = 2_147_483_647;\n\n/**\n * Minimal slice of `RcloneProcessManager` the refresh controller needs: swap\n * the live mount onto a freshly-rendered INI (`reconfigure`), and stop a\n * process the controller spawned but can no longer own (`stop`, used to clean\n * up when `disconnect()` races a mid-recycle spawn).\n */\nexport interface RcloneReconfigurable {\n reconfigure(handle: RcloneHandle, rcloneConfig: string): Promise<RcloneHandle>;\n stop(handle: RcloneHandle): Promise<void>;\n}\n\n/**\n * Caller-supplied dependencies for {@link createRcloneTokenRefresh}.\n *\n * - `tokenMediator` runs the actual backend mint round-trip.\n * - `renderConfig(token)` re-renders the rclone INI for the freshly-minted\n * access token (driver-specific: onedrive vs webdav backend shape).\n * - `rclone.reconfigure` recycles the process onto the new INI.\n * - `handleRef.current` is the live rclone handle; the controller updates it\n * in place on every successful recycle so the driver's `disconnect()` stops\n * the current process.\n * - `now` / `setTimeoutImpl` / `clearTimeoutImpl` are injected for tests.\n */\nexport interface RcloneTokenRefreshDeps {\n connectorId: string;\n tokenMediator: TokenMediator;\n renderConfig: (token: string) => string | Promise<string>;\n rclone: RcloneReconfigurable;\n handleRef: { current: RcloneHandle | null };\n log: (line: string) => void;\n now?: () => number;\n setTimeoutImpl?: (handler: () => void, ms: number) => { unref?: () => void };\n clearTimeoutImpl?: (handle: { unref?: () => void }) => void;\n marginMs?: number;\n reactiveCooldownMs?: number;\n}\n\nexport interface RcloneTokenRefreshController {\n /**\n * Arm the timer for `expiresAtIso - marginMs`. Cancels any prior pending\n * fire. `null` / `undefined` / unparseable cancels without re-arming\n * (static-credential / standalone semantics). A past fire-time refreshes on\n * the next tick.\n */\n schedule(expiresAtIso: string | null | undefined): void;\n /**\n * Reactive safety net: invoke when rclone reports an auth failure. Triggers\n * an immediate refresh unless one is already in flight or the last refresh\n * was within the cooldown window (prevents a stream of failure lines from\n * spinning the recycle loop).\n */\n onAuthError(): void;\n /** Cancel any pending fire. Idempotent. */\n cancel(): void;\n /** Whether a proactive timer is currently armed. Exposed for tests. */\n isPending(): boolean;\n}\n\n/**\n * Build a refresh controller bound to one rclone mount. One controller per\n * connect — the driver constructs it after the initial spawn and disposes it\n * via `cancel()` in `disconnect()`.\n */\nexport function createRcloneTokenRefresh(\n deps: RcloneTokenRefreshDeps,\n): RcloneTokenRefreshController {\n const now = deps.now ?? (() => Date.now());\n const setTimeoutImpl =\n deps.setTimeoutImpl ??\n ((handler: () => void, ms: number) =>\n setTimeout(handler, ms) as unknown as { unref?: () => void });\n const clearTimeoutImpl =\n deps.clearTimeoutImpl ??\n ((handle: { unref?: () => void }) => {\n clearTimeout(handle as unknown as ReturnType<typeof setTimeout>);\n });\n const marginMs = deps.marginMs ?? PROACTIVE_RCLONE_REFRESH_MARGIN_MS;\n const reactiveCooldownMs = deps.reactiveCooldownMs ?? DEFAULT_REACTIVE_COOLDOWN_MS;\n\n let timer: { unref?: () => void } | null = null;\n let refreshing = false;\n let disposed = false;\n let lastRefreshAt = Number.NEGATIVE_INFINITY;\n\n /** Clear the pending timer only (used internally on every re-arm). */\n function clearTimer(): void {\n if (timer !== null) {\n clearTimeoutImpl(timer);\n timer = null;\n }\n }\n\n /** Public teardown: dispose the controller so no further refresh fires. */\n function cancel(): void {\n disposed = true;\n clearTimer();\n }\n\n /**\n * Run one mint → render → recycle → re-arm pass. Returns nothing; re-arms\n * internally on success. On any failure it logs and stays idle, leaving the\n * reactive path as the safety net (no re-arm = no busy-loop on a dead\n * mediator).\n */\n async function fire(reason: \"refresh\" | \"retry-401\"): Promise<void> {\n if (refreshing || disposed) return;\n refreshing = true;\n try {\n let result: Awaited<ReturnType<TokenMediator>>;\n try {\n result = await deps.tokenMediator({ connectorId: deps.connectorId, reason });\n } catch (err) {\n deps.log(\n `[rclone-token-refresh] mediator threw: ${err instanceof Error ? err.message : String(err)}; reactive auth-error path remains as safety net`,\n );\n return;\n }\n // disconnect() may have run while the mint was in flight — bail before\n // touching the (now-stopped) process so we never recycle into an orphan.\n if (disposed) return;\n if (!result.ok) {\n deps.log(\n `[rclone-token-refresh] mediator refused (${result.code}: ${result.message}); reactive auth-error path remains as safety net`,\n );\n return;\n }\n if (!result.token) {\n deps.log(\n \"[rclone-token-refresh] mediator returned an empty token; reactive auth-error path remains as safety net\",\n );\n return;\n }\n const handle = deps.handleRef.current;\n if (!handle) {\n // Reachable: the reactive onAuthError hook is wired into the rclone\n // spawn config before handleRef is populated, so an auth-failure line\n // emitted during initial mount lands here. Safe no-op — initial-mount\n // auth failures surface via the normal spawn timeout instead.\n deps.log(\"[rclone-token-refresh] no live rclone handle to recycle; skipping refresh\");\n return;\n }\n\n const rcloneConfig = await deps.renderConfig(result.token);\n if (disposed) return;\n let next: RcloneHandle;\n try {\n next = await deps.rclone.reconfigure(handle, rcloneConfig);\n } catch (err) {\n deps.log(\n `[rclone-token-refresh] reconfigure failed: ${err instanceof Error ? err.message : String(err)}; reactive auth-error path remains as safety net`,\n );\n return;\n }\n if (disposed) {\n // disconnect() raced the recycle between reconfigure()'s internal\n // stop() and spawn(): disconnect already stopped the old handle and\n // found nothing, so the freshly-spawned process would leak. Stop it.\n deps.log(\"[rclone-token-refresh] disposed mid-recycle; stopping freshly-spawned process\");\n try {\n await deps.rclone.stop(next);\n } catch {\n // best effort — the process may already be gone\n }\n return;\n }\n deps.handleRef.current = next;\n lastRefreshAt = now();\n deps.log(\n `[rclone-token-refresh] recycled mount with refreshed token (reason=${reason}, expiresAt=${result.expiresAt ?? \"none\"})`,\n );\n\n // Re-arm against the new expiry (null = static credential, no re-arm).\n schedule(result.expiresAt);\n } finally {\n refreshing = false;\n }\n }\n\n /** Arm (or re-arm in a capped chunk) a timer that fires at `fireAtMs`. */\n function armTimer(fireAtMs: number): void {\n const delayMs = Math.min(Math.max(0, fireAtMs - now()), MAX_TIMER_MS);\n timer = setTimeoutImpl(() => {\n timer = null;\n // A clamped wake-up that landed before the real fire-time just re-arms.\n if (now() < fireAtMs) armTimer(fireAtMs);\n else void fire(\"refresh\");\n }, delayMs);\n timer.unref?.();\n }\n\n function schedule(expiresAtIso: string | null | undefined): void {\n clearTimer();\n if (disposed || !expiresAtIso) return;\n const expiresAtMs = Date.parse(expiresAtIso);\n if (!Number.isFinite(expiresAtMs)) return;\n const fireAtMs = expiresAtMs - marginMs;\n if (fireAtMs - now() <= 0) {\n deps.log(`[rclone-token-refresh] token within ${marginMs / 1000}s of expiry; refreshing now`);\n } else {\n deps.log(\n `[rclone-token-refresh] scheduled in ${Math.round((fireAtMs - now()) / 1000)}s (expiresAt=${expiresAtIso})`,\n );\n }\n armTimer(fireAtMs);\n }\n\n function onAuthError(): void {\n if (refreshing || disposed) return;\n if (now() - lastRefreshAt < reactiveCooldownMs) {\n deps.log(\n \"[rclone-token-refresh] auth-error within refresh cooldown; suppressing reactive refresh\",\n );\n return;\n }\n clearTimer();\n void fire(\"retry-401\");\n }\n\n return {\n schedule,\n onAuthError,\n cancel,\n isPending: () => timer !== null,\n };\n}\n","/**\n * Shared git worktree helper for service connectors.\n *\n * Provides create/cleanup with a cross-adapter ownership registry\n * that prevents one adapter from removing a worktree another is using.\n */\n\nimport { execSync } from \"node:child_process\";\nimport { existsSync, mkdirSync } from \"node:fs\";\nimport { resolve } from \"node:path\";\n\n// ── Types ───────────────────────────────────────────────────────────────────\n\n/**\n * Result of a successful `createWorktree` call. The `cleanup` function removes the\n * worktree when no other owners are registered for the same path.\n * @docLink packages/connectors/api-reference#worktree-result\n */\nexport interface WorktreeResult {\n /** Absolute path to the worktree directory. */\n path: string;\n /** Resolved full SHA of the ref. */\n ref: string;\n /** Branch name if ref was a branch. */\n branch?: string;\n /** Remove the worktree. Fails if other owners exist in registry. */\n cleanup: () => Promise<void>;\n}\n\n/**\n * Summary entry returned by `listWorktrees`.\n * @docLink packages/connectors/api-reference#worktree-info\n */\nexport interface WorktreeInfo {\n /** Absolute path to the worktree. */\n path: string;\n /** HEAD commit SHA. */\n head: string;\n /** Branch reference, if a named branch is checked out. */\n branch?: string;\n}\n\n// ── Registry ────────────────────────────────────────────────────────────────\n\nclass WorktreeRegistryImpl {\n private readonly entries = new Map<string, Set<string>>();\n\n register(path: string, owner: string): void {\n let owners = this.entries.get(path);\n if (!owners) {\n owners = new Set();\n this.entries.set(path, owners);\n }\n owners.add(owner);\n }\n\n deregister(path: string, owner: string): void {\n const owners = this.entries.get(path);\n if (!owners) return;\n owners.delete(owner);\n if (owners.size === 0) this.entries.delete(path);\n }\n\n isInUse(path: string): boolean {\n return (this.entries.get(path)?.size ?? 0) > 0;\n }\n\n owners(path: string): string[] {\n return [...(this.entries.get(path) ?? [])];\n }\n}\n\n/**\n * Module-level singleton registry shared across all service-connector adapters in the same process.\n * Prevents one adapter from removing a worktree that another adapter is still using.\n * @docLink packages/connectors/api-reference#worktree-registry\n */\nexport const worktreeRegistry = new WorktreeRegistryImpl();\n\n// ── Helpers ─────────────────────────────────────────────────────────────────\n\nfunction git(args: string, cwd: string): string {\n return execSync(`git ${args}`, { cwd, encoding: \"utf-8\" }).trim();\n}\n\nfunction resolveRef(repoRoot: string, ref: string): string {\n return git(`rev-parse --verify ${ref}`, repoRoot);\n}\n\n/**\n * Walk up from `fromDir` to find the git repository root.\n * @param fromDir - Any directory inside a git repository.\n * @returns Absolute path to the repository root.\n * @throws {Error} when no git repository is found.\n * @docLink packages/connectors/api-reference#find-git-root\n */\nexport function findGitRoot(fromDir: string): string {\n return git(\"rev-parse --show-toplevel\", fromDir);\n}\n\n// ── Public API ──────────────────────────────────────────────────────────────\n\n/**\n * Create a git worktree for `ref` under `baseDir` and register it with `worktreeRegistry`.\n * The returned `WorktreeResult.cleanup()` removes the worktree when no other owners remain.\n * @param opts - Repo root, git ref, base directory, optional label, and owner ID.\n * @returns Path, resolved SHA, branch name, and `cleanup()` function.\n * @throws {Error} if the ref cannot be resolved.\n * @docLink packages/connectors/api-reference#create-worktree\n */\nexport async function createWorktree(opts: {\n repoRoot: string;\n ref: string;\n baseDir: string;\n label?: string;\n owner: string;\n}): Promise<WorktreeResult> {\n const sha = resolveRef(opts.repoRoot, opts.ref);\n const label = opts.label ?? sha.slice(0, 8);\n const wtPath = resolve(opts.baseDir, label);\n\n if (!existsSync(opts.baseDir)) {\n mkdirSync(opts.baseDir, { recursive: true });\n }\n\n git(`worktree add \"${wtPath}\" ${sha} --detach`, opts.repoRoot);\n worktreeRegistry.register(wtPath, opts.owner);\n\n let branch: string | undefined;\n try {\n const refName = git(`rev-parse --abbrev-ref ${opts.ref}`, opts.repoRoot);\n if (refName !== \"HEAD\" && refName !== sha) branch = refName;\n } catch {\n // Not a branch\n }\n\n return {\n path: wtPath,\n ref: sha,\n branch,\n cleanup: async () => {\n worktreeRegistry.deregister(wtPath, opts.owner);\n\n if (worktreeRegistry.isInUse(wtPath)) {\n const remaining = worktreeRegistry.owners(wtPath);\n throw new Error(`worktree in use by: ${remaining.join(\", \")}`);\n }\n\n try {\n git(`worktree remove \"${wtPath}\" --force`, opts.repoRoot);\n } catch {\n // May already be gone\n }\n git(\"worktree prune\", opts.repoRoot);\n },\n };\n}\n\n/**\n * List all git worktrees for a repository.\n * @param repoRoot - Absolute path to the git repository root.\n * @returns Array of `WorktreeInfo` objects parsed from `git worktree list --porcelain`.\n * @docLink packages/connectors/api-reference#list-worktrees\n */\nexport async function listWorktrees(repoRoot: string): Promise<WorktreeInfo[]> {\n const raw = git(\"worktree list --porcelain\", repoRoot);\n const trees: WorktreeInfo[] = [];\n let current: Partial<WorktreeInfo> = {};\n\n for (const line of raw.split(\"\\n\")) {\n if (line.startsWith(\"worktree \")) {\n if (current.path) trees.push(current as WorktreeInfo);\n current = { path: line.slice(\"worktree \".length) };\n } else if (line.startsWith(\"HEAD \")) {\n current.head = line.slice(\"HEAD \".length);\n } else if (line.startsWith(\"branch \")) {\n current.branch = line.slice(\"branch \".length);\n }\n }\n if (current.path) trees.push(current as WorktreeInfo);\n\n return trees;\n}\n","/**\n * FlowAdapter — live flow execution state exposed as a connector resource.\n *\n * Holds the canonical `FlowExecution` snapshot for a single run and bridges\n * three driving parties:\n *\n * - The **agent** drives nodes to completion by calling tools (`start_node`,\n * `request_approval`, `request_input`, `complete_node`, `skip_node`,\n * `fail_node`, plus read-only `get_state` / `get_available` / `build_handoff`).\n * - The **host** (runner → serve.ts → platform) applies out-of-turn\n * mutations (`applyApproval`, `applyInput`, `retryNode`,\n * `setAutonomousMode`, `cancel`, `hydrate`) in response to user actions.\n * - The **runner's FlowOrchestrator** subscribes to `onChange` to forward\n * `state_changed` events and kick new turns after host-driven mutations.\n *\n * Every state mutation runs through a single `mutate()` helper that clones\n * the current snapshot, applies the change, recomputes derived fields via\n * `computeFlowStateFromSnapshots`, and fires the onChange callback with\n * the full FlowExecution shape. Consumers downstream (platform gateway,\n * frontend hook) see latest-wins snapshots — F4 in the decision log.\n *\n * See `docs/flow-execution.md` for the universal model.\n */\n\nimport {\n AbstractConnector,\n type ConnectContext,\n type ConnectorContent,\n type ConnectorDeclaration,\n type ConnectorEntry,\n type ConnectorHandle,\n type ListOptions,\n type OperationDescriptor,\n type SearchOptions,\n type SearchResult,\n type ToolFace,\n} from \"@skaile/workspaces/connectors\";\nimport type {\n Approval,\n ArtifactRef,\n FlowExecution,\n FlowExecutionStatus,\n InputRequest,\n InputSchema,\n NodeError,\n NodeExecution,\n NodeExecutionSnapshot,\n NodeOutput,\n NodeStatus,\n} from \"@skaile/workspaces/types\";\nimport {\n computeFlowStateFromSnapshots,\n type FlowDefinition,\n type FlowNode,\n isBlocking,\n} from \"./engine/index.js\";\nimport { renderStimulusPrompt } from \"./prompt-fragments.js\";\nimport { computeStimulus } from \"./stimulus-driver.js\";\n\n// ── Stimulus bus surface ─────────────────────────────────────────────────────\n\n/**\n * Minimal structural shape of the runner's `SessionStimulusBus`. Declared\n * locally so the adapter doesn't pull in a runtime dep on\n * `@skaile/workspaces/runner` (which would create a circular workspace import).\n *\n * The runner's `SessionStimulusBus` from `runner/src/session-stimulus.ts`\n * satisfies this structurally; mocks in tests can implement it directly.\n *\n * @docLink packages/factory-assets/flow#session-stimulus-bus\n */\nexport interface FlowAdapterStimulusBus {\n signal(\n connectorId: string,\n sig: { promptFragment: string; meta?: Record<string, unknown> },\n ): Promise<void>;\n}\n\n// ── State ───────────────────────────────────────────────────────────────────\n\n/**\n * Internal state stored in the `ConnectorHandle` for the flow adapter.\n * @docLink packages/connectors/concepts#flow-adapter-state\n */\nexport interface FlowAdapterState {\n /** The flow graph definition this adapter is executing. */\n flowDef: FlowDefinition;\n /** Current execution snapshot (authoritative; mutated in place by `mutate()`). */\n execution: FlowExecution;\n /** Callback fired after every state mutation. Set by `FlowOrchestrator` via `onStateChange()`. */\n onChange?: (state: FlowExecution) => void;\n /**\n * Optional `SessionStimulusBus` reference. When provided AND\n * `useBusForStimulus` is true, the adapter computes a `TurnStimulus`\n * after every mutation and fires `bus.signal()` to wake the agent.\n * Phase 3 wiring (2026-05-08): the flag defaults to false everywhere so\n * the legacy orchestrator path remains the only turn driver until Phase 4.\n */\n stimulusBus?: FlowAdapterStimulusBus;\n /**\n * Connector ID used as the `stimulusBus.signal()` queue key. Defaults to\n * the adapter handle's declaration ID (e.g. `flow:<runId>` in serve mode,\n * `flow` in CLI mode).\n */\n connectorId?: string;\n /** Phase 3 feature flag — see {@link FlowAdapterConnectOptions.useBusForStimulus}. */\n useBusForStimulus?: boolean;\n /**\n * Last execution snapshot the adapter signaled to the bus. Used to compute\n * a structural diff in `computeStimulus`, so back-to-back mutations that\n * leave the snapshot unchanged don't fire spurious turn kicks.\n */\n lastSignaledExecution?: FlowExecution;\n}\n\n/**\n * Options the runner passes via `declaration.options` when connecting the `FlowAdapter`.\n * @docLink packages/connectors/concepts#flow-adapter-connect-options\n */\nexport interface FlowAdapterConnectOptions {\n flow: FlowDefinition;\n /**\n * Either a fresh start seed (runId + startedBy) or a full rehydration\n * state. If `execution` is provided, it replaces the default empty\n * state — used on session wake when the host sends the persisted\n * snapshot via `configure.activeFlows`.\n */\n execution?: FlowExecution;\n seed?: {\n runId: string;\n startedBy: string;\n autonomousMode?: boolean;\n };\n /**\n * Optional `SessionStimulusBus` to which this adapter should fire\n * `signal()` calls on every mutation when `useBusForStimulus` is true.\n * Threaded through by the runner's session-construction code (`runFlow`\n * / `serve.ts`). Phase 3 of the flow-connector extraction (2026-05-08)\n * builds the path; Phase 4 flips the flag globally.\n */\n stimulusBus?: FlowAdapterStimulusBus;\n /**\n * Phase 3 feature flag. When `true` AND `stimulusBus` is provided, the\n * adapter computes a turn-kicking stimulus after every mutation and\n * calls `bus.signal()` (fire-and-forget). When `false` (the default),\n * only the legacy `onChange` callback fires — the runner's existing\n * `FlowOrchestrator.onStateChange` subscription remains the only turn\n * driver. Default: `false`.\n */\n useBusForStimulus?: boolean;\n}\n\n// ── Helpers ─────────────────────────────────────────────────────────────────\n\nconst now = () => new Date().toISOString();\n\n/** Produce an empty NodeExecution for a node id. */\nfunction emptyNode(nodeId: string): NodeExecution {\n return {\n id: nodeId,\n status: \"not_started\",\n approvalHistory: [],\n inputHistory: [],\n errorHistory: [],\n };\n}\n\n/**\n * Build the starting FlowExecution snapshot for a flow definition — every\n * skill node begins as `not_started`; engine recompute promotes them.\n */\nfunction buildInitialExecution(\n flowDef: FlowDefinition,\n seed: { runId: string; startedBy: string; autonomousMode?: boolean },\n): FlowExecution {\n const nodes: Record<string, NodeExecution> = {};\n for (const n of flowDef.nodes) {\n if (n.type === \"skill\") {\n nodes[n.id] = emptyNode(n.id);\n }\n }\n return {\n runId: seed.runId,\n flowId: flowDef.id,\n flowVersion: flowDef.version,\n status: \"running\",\n startedAt: now(),\n startedBy: seed.startedBy,\n autonomousMode: seed.autonomousMode ?? false,\n nodes,\n focus: [],\n done: false,\n };\n}\n\nfunction toSnapshot(exec: NodeExecution): NodeExecutionSnapshot {\n return {\n status: exec.status,\n approval: exec.approval,\n input: exec.input,\n output: exec.output,\n error: exec.error,\n };\n}\n\nfunction snapshotMap(execution: FlowExecution): Map<string, NodeExecutionSnapshot> {\n const map = new Map<string, NodeExecutionSnapshot>();\n for (const [id, exec] of Object.entries(execution.nodes)) {\n map.set(id, toSnapshot(exec));\n }\n return map;\n}\n\n/**\n * Fail-fast helper. Throws a string Error so the SDK surfaces the reason\n * back to the agent tool-call log.\n */\nfunction assertLegal(cond: unknown, message: string): asserts cond {\n if (!cond) throw new Error(`FlowAdapter: ${message}`);\n}\n\nfunction findNode(flowDef: FlowDefinition, nodeId: string): FlowNode {\n const node = flowDef.nodes.find((n) => n.id === nodeId);\n if (!node) throw new Error(`FlowAdapter: unknown nodeId ${nodeId}`);\n return node;\n}\n\nfunction isOptional(flowDef: FlowDefinition, nodeId: string): boolean {\n return findNode(flowDef, nodeId).data?.optional === true;\n}\n\n// ── Adapter ─────────────────────────────────────────────────────────────────\n\n/**\n * Connector adapter that holds and drives a live `FlowExecution`. Bridges three parties:\n * the agent (via `executeOp` tools), the host runner (via direct methods like `applyApproval`),\n * and the orchestrator (via `onStateChange`). Every mutation runs through a single `mutate()`\n * pipeline that recomputes derived fields and fires `onChange`.\n * @docLink packages/connectors/concepts#flow-adapter\n */\nexport class FlowAdapter extends AbstractConnector {\n readonly name = \"flow\";\n readonly mountable = false;\n\n tools: ToolFace;\n\n constructor() {\n super();\n this.tools = {\n read: (handle, path) => this.read(handle, path),\n list: (handle, path, options) => this.list(handle, path, options),\n search: (handle, query, options) => this.search(handle, query, options),\n describeOperations: (handle) => this.describeOperations(handle),\n executeOp: (handle, operation, args) => this.executeOp(handle, operation, args),\n };\n }\n\n // ── Lifecycle ──\n\n async connect(declaration: ConnectorDeclaration, _ctx: ConnectContext): Promise<ConnectorHandle> {\n const options = (declaration.options ?? {}) as unknown as FlowAdapterConnectOptions;\n const flowDef = options.flow;\n if (!flowDef) throw new Error(\"FlowAdapter requires options.flow (FlowDefinition)\");\n\n const execution =\n options.execution ??\n buildInitialExecution(\n flowDef,\n options.seed ?? { runId: \"local\", startedBy: \"system\", autonomousMode: false },\n );\n\n const state: FlowAdapterState = {\n flowDef,\n execution,\n stimulusBus: options.stimulusBus,\n connectorId: declaration.id,\n useBusForStimulus: options.useBusForStimulus ?? false,\n };\n // Recompute derived fields (focus, done) once so callers see a\n // consistent shape even if no mutation has happened yet.\n state.execution = this.recompute(state);\n return this.makeHandle(declaration, state);\n }\n\n async disconnect(handle: ConnectorHandle): Promise<void> {\n handle.status = \"disconnected\";\n }\n\n // ── State change subscription ──\n\n onStateChange(handle: ConnectorHandle, cb: (state: FlowExecution) => void): void {\n this.s(handle).onChange = cb;\n }\n\n /**\n * Replace the current execution snapshot with a host-provided one.\n * Used on container rehydration via the extended `configure` command.\n * Does NOT fire `onChange` — the host already has the state; we don't\n * want to loop it back on startup.\n */\n hydrate(handle: ConnectorHandle, execution: FlowExecution): void {\n const s = this.s(handle);\n s.execution = { ...execution };\n s.execution = this.recompute(s);\n }\n\n // ── Base operations (private — wired into tools face in constructor) ──\n\n private async read(handle: ConnectorHandle, path: string): Promise<ConnectorContent | null> {\n const s = this.s(handle);\n\n if (path === \"\" || path === \"state\") {\n return {\n data: JSON.stringify(s.execution, null, 2),\n contentType: \"application/json\",\n };\n }\n\n if (path.startsWith(\"node/\")) {\n const nodeId = path.slice(5);\n const node = s.flowDef.nodes.find((n) => n.id === nodeId);\n if (!node) return null;\n const exec = s.execution.nodes[nodeId];\n return {\n data: JSON.stringify({ ...node, execution: exec ?? null }, null, 2),\n contentType: \"application/json\",\n };\n }\n\n return null;\n }\n\n private async list(\n handle: ConnectorHandle,\n _path?: string,\n _options?: ListOptions,\n ): Promise<ConnectorEntry[]> {\n const s = this.s(handle);\n const nodes: NodeExecution[] = Object.values(s.execution.nodes);\n return nodes.map((n) => ({\n name: n.id,\n path: `node/${n.id}`,\n type: \"key\" as const,\n }));\n }\n\n private async search(\n handle: ConnectorHandle,\n query: string,\n _options?: SearchOptions,\n ): Promise<SearchResult[]> {\n const s = this.s(handle);\n const q = query.toLowerCase();\n const nodes: NodeExecution[] = Object.values(s.execution.nodes);\n return nodes\n .filter((n) => n.id.toLowerCase().includes(q) || n.status.includes(q))\n .map((n) => ({ path: `node/${n.id}`, snippet: `${n.id} [${n.status}]` }));\n }\n\n // ── Custom operations (agent tool surface) ──\n\n private describeOperations(handle: ConnectorHandle): OperationDescriptor[] {\n const ops: OperationDescriptor[] = [\n {\n name: \"get_available\",\n description: \"Get node IDs that are ready to run (all required predecessors complete).\",\n accessLevel: \"read\",\n args: [],\n },\n {\n name: \"get_state\",\n description: \"Get the full flow execution snapshot — nodes, statuses, approvals, inputs.\",\n accessLevel: \"read\",\n args: [],\n },\n {\n name: \"build_handoff\",\n description:\n \"Build curated context for a node from its completed flow-type predecessors (summaries + artifact refs).\",\n accessLevel: \"read\",\n args: [\n {\n name: \"nodeId\",\n description: \"Target node to build handoff context for\",\n type: \"string\",\n required: true,\n },\n ],\n },\n {\n name: \"validate_node\",\n description: \"Check whether a node is currently runnable.\",\n accessLevel: \"read\",\n args: [\n {\n name: \"nodeId\",\n description: \"Node ID to validate\",\n type: \"string\",\n required: true,\n },\n ],\n },\n ];\n\n if (handle.access === \"read-write\") {\n ops.push(\n {\n name: \"start_node\",\n description: \"Mark an available node as running (records startedAt).\",\n accessLevel: \"write\",\n args: [\n { name: \"nodeId\", description: \"Node ID to start\", type: \"string\", required: true },\n ],\n },\n {\n name: \"request_approval\",\n description:\n \"Request human approval for a running node. Ends your turn — the runner yields until the user approves or rejects.\",\n accessLevel: \"write\",\n args: [\n { name: \"nodeId\", description: \"Node ID\", type: \"string\", required: true },\n {\n name: \"summary\",\n description: \"One-paragraph summary of what the user is approving.\",\n type: \"string\",\n required: true,\n },\n {\n name: \"artifacts\",\n description:\n \"JSON array of ArtifactRef objects. Each: { uri, connectorId, kind, lifetime, producedBy }.\",\n type: \"string\",\n required: false,\n },\n ],\n },\n {\n name: \"request_input\",\n description:\n \"Request typed input from the user for a node. Ends your turn. Legal from `available`, `running`, or `awaiting_approval`.\",\n accessLevel: \"write\",\n args: [\n { name: \"nodeId\", description: \"Node ID\", type: \"string\", required: true },\n {\n name: \"prompt\",\n description: \"Prompt shown to the user alongside the input widget.\",\n type: \"string\",\n required: true,\n },\n {\n name: \"schema\",\n description:\n \"JSON InputSchema: one of { kind: 'text' }, { kind: 'choice', options: [...] }, { kind: 'form', fields: [...] }, { kind: 'file' }.\",\n type: \"string\",\n required: true,\n },\n ],\n },\n {\n name: \"complete_node\",\n description:\n \"Mark a node as complete with structured output. Requires `awaiting_approval` with an `approved` decision, OR `running` when autonomous mode is on.\",\n accessLevel: \"write\",\n args: [\n { name: \"nodeId\", description: \"Node ID to complete\", type: \"string\", required: true },\n {\n name: \"summary\",\n description: \"2-3 sentence summary of what the node accomplished.\",\n type: \"string\",\n required: true,\n },\n {\n name: \"artifacts\",\n description: \"JSON array of ArtifactRef objects produced by this node.\",\n type: \"string\",\n required: false,\n },\n {\n name: \"concerns\",\n description: \"JSON array of flagged concerns.\",\n type: \"string\",\n required: false,\n },\n ],\n },\n {\n name: \"skip_node\",\n description: \"Skip an optional node. Only valid when the node has `optional: true`.\",\n accessLevel: \"write\",\n args: [\n { name: \"nodeId\", description: \"Node ID to skip\", type: \"string\", required: true },\n ],\n },\n {\n name: \"fail_node\",\n description:\n \"Mark a node as failed. `recoverable: true` transitions back to `available` so the runner can retry; `recoverable: false` marks the node and flow as failed.\",\n accessLevel: \"write\",\n args: [\n { name: \"nodeId\", description: \"Node ID\", type: \"string\", required: true },\n {\n name: \"message\",\n description: \"Human-readable failure reason.\",\n type: \"string\",\n required: true,\n },\n {\n name: \"recoverable\",\n description: \"true|false — whether the failure is retryable.\",\n type: \"string\",\n required: false,\n },\n ],\n },\n );\n }\n\n // Host-facing operations — invoked by the runner via `connector_mutate`\n // (Phase 2 of flow-connector extraction). These are NOT exposed to the\n // agent's tool surface; they're the same instance methods the typed flow\n // commands call today, dispatched generically through `executeOp`.\n //\n // Visibility: include them only on read-write handles, matching the\n // existing host-vs-agent boundary.\n if (handle.access === \"read-write\") {\n ops.push(\n {\n name: \"applyApproval\",\n description: \"Host: record an approval decision on a node awaiting approval.\",\n accessLevel: \"write\",\n args: [\n { name: \"nodeId\", description: \"Node ID\", type: \"string\", required: true },\n {\n name: \"decision\",\n description: \"approved | rejected\",\n type: \"string\",\n required: true,\n },\n {\n name: \"feedback\",\n description: \"Optional feedback shown alongside the decision.\",\n type: \"string\",\n required: false,\n },\n {\n name: \"decidedBy\",\n description: \"User id of the decider.\",\n type: \"string\",\n required: true,\n },\n ],\n },\n {\n name: \"applyInput\",\n description: \"Host: provide user input for a node awaiting input.\",\n accessLevel: \"write\",\n args: [\n { name: \"nodeId\", description: \"Node ID\", type: \"string\", required: true },\n {\n name: \"response\",\n description: \"Input response (shape matches the InputSchema the agent requested).\",\n type: \"json\",\n required: true,\n },\n {\n name: \"providedBy\",\n description: \"User id of the input provider.\",\n type: \"string\",\n required: true,\n },\n ],\n },\n {\n name: \"cancel\",\n description: \"Host: cancel the active flow run.\",\n accessLevel: \"write\",\n args: [],\n },\n {\n name: \"setAutonomousMode\",\n description: \"Host: toggle autonomous mode on the running flow.\",\n accessLevel: \"write\",\n args: [\n {\n name: \"enabled\",\n description: \"true|false — whether autonomous mode is on.\",\n type: \"boolean\",\n required: true,\n },\n ],\n },\n {\n name: \"retryNode\",\n description: \"Host: transition a recoverable failed node back to available.\",\n accessLevel: \"write\",\n args: [\n { name: \"nodeId\", description: \"Node ID\", type: \"string\", required: true },\n {\n name: \"requestedBy\",\n description: \"User id of the retry requester (informational).\",\n type: \"string\",\n required: true,\n },\n ],\n },\n {\n name: \"hydrate\",\n description: \"Host: replace the current execution snapshot with a host-provided one.\",\n accessLevel: \"write\",\n args: [\n {\n name: \"state\",\n description: \"FlowExecution snapshot to hydrate into the adapter.\",\n type: \"json\",\n required: true,\n },\n ],\n },\n {\n name: \"start\",\n description:\n \"Host: seed a fresh flow execution. Replaces the adapter's current flow + execution state in-place.\",\n accessLevel: \"write\",\n args: [\n {\n name: \"flow\",\n description: \"FlowDefinition to execute.\",\n type: \"json\",\n required: true,\n },\n {\n name: \"seed\",\n description:\n \"Seed object: { runId, startedBy, autonomousMode? } used to construct the initial FlowExecution.\",\n type: \"json\",\n required: true,\n },\n ],\n },\n );\n }\n\n return ops;\n }\n\n async executeOp(\n handle: ConnectorHandle,\n operation: string,\n args: Record<string, unknown>,\n ): Promise<string> {\n const s = this.s(handle);\n\n switch (operation) {\n case \"get_available\":\n return this.opGetAvailable(s);\n case \"get_state\":\n return JSON.stringify(s.execution);\n case \"build_handoff\":\n return this.buildHandoff(s, String(args.nodeId ?? \"\"));\n case \"validate_node\":\n return this.opValidateNode(s, args);\n case \"start_node\":\n return this.opStartNode(handle, args);\n case \"request_approval\":\n return this.opRequestApproval(handle, args);\n case \"request_input\":\n return this.opRequestInput(handle, args);\n case \"complete_node\":\n return this.opCompleteNode(handle, args);\n case \"skip_node\":\n return this.opSkipNode(handle, args);\n case \"fail_node\":\n return this.opFailNode(handle, args);\n\n // ── Host-facing operations (Phase 2 of flow-connector extraction) ──\n // These dispatch to the same instance methods the typed flow commands\n // call today. JSON-stringify the resulting FlowExecution (or `\"\"` for\n // void returns) so the wire surface is uniform across ops.\n\n case \"applyApproval\":\n return this.opApplyApproval(handle, s, args);\n case \"applyInput\":\n return this.opApplyInput(handle, s, args);\n case \"cancel\":\n this.cancel(handle);\n return JSON.stringify(s.execution);\n case \"setAutonomousMode\":\n return this.opSetAutonomousMode(handle, s, args);\n case \"retryNode\":\n return this.opRetryNode(handle, s, args);\n case \"hydrate\":\n return this.opHydrate(handle, s, args);\n case \"start\":\n return this.opStart(handle, s, args);\n\n default:\n throw new Error(`FlowAdapter: Unknown operation: ${operation}`);\n }\n }\n\n // ── executeOp branch handlers (private dispatch helpers) ─────────────────\n\n private opGetAvailable(s: FlowAdapterState): string {\n const nodes: NodeExecution[] = Object.values(s.execution.nodes);\n const available = nodes.filter((n) => n.status === \"available\").map((n) => n.id);\n return JSON.stringify(available);\n }\n\n private opValidateNode(s: FlowAdapterState, args: Record<string, unknown>): string {\n const nodeId = String(args.nodeId ?? \"\");\n const node = s.execution.nodes[nodeId];\n if (!node) return JSON.stringify({ valid: false, reason: \"Node not found\" });\n const predsMet = flowPredecessors(s.flowDef, nodeId).every((pid) => {\n const predStatus = s.execution.nodes[pid]?.status ?? \"not_started\";\n return predStatus === \"complete\" || predStatus === \"skipped\";\n });\n return JSON.stringify({\n valid: node.status === \"available\",\n status: node.status,\n predecessorsReady: predsMet,\n });\n }\n\n private opStartNode(handle: ConnectorHandle, args: Record<string, unknown>): string {\n const nodeId = String(args.nodeId ?? \"\");\n return this.doStartNode(handle, nodeId);\n }\n\n private opRequestApproval(handle: ConnectorHandle, args: Record<string, unknown>): string {\n const nodeId = String(args.nodeId ?? \"\");\n const summary = String(args.summary ?? \"\");\n const artifacts = safeParseArtifacts(args.artifacts);\n return this.doRequestApproval(handle, nodeId, summary, artifacts);\n }\n\n private opRequestInput(handle: ConnectorHandle, args: Record<string, unknown>): string {\n const nodeId = String(args.nodeId ?? \"\");\n const prompt = String(args.prompt ?? \"\");\n const schema = safeParseInputSchema(args.schema);\n return this.doRequestInput(handle, nodeId, prompt, schema);\n }\n\n private opCompleteNode(handle: ConnectorHandle, args: Record<string, unknown>): string {\n const nodeId = String(args.nodeId ?? \"\");\n const output: NodeOutput = {\n summary: String(args.summary ?? \"Completed\"),\n artifacts: safeParseArtifacts(args.artifacts),\n concerns: safeParseStringArray(args.concerns),\n };\n return this.doCompleteNode(handle, nodeId, output);\n }\n\n private opSkipNode(handle: ConnectorHandle, args: Record<string, unknown>): string {\n const nodeId = String(args.nodeId ?? \"\");\n return this.doSkipNode(handle, nodeId);\n }\n\n private opFailNode(handle: ConnectorHandle, args: Record<string, unknown>): string {\n const nodeId = String(args.nodeId ?? \"\");\n const message = String(args.message ?? \"failed\");\n const recoverable =\n args.recoverable === true || args.recoverable === \"true\" || args.recoverable === \"yes\";\n return this.doFailNode(handle, nodeId, message, recoverable);\n }\n\n private opApplyApproval(\n handle: ConnectorHandle,\n s: FlowAdapterState,\n args: Record<string, unknown>,\n ): string {\n const nodeId = String(args.nodeId ?? \"\");\n const decision = args.decision === \"rejected\" ? \"rejected\" : \"approved\";\n const feedback =\n typeof args.feedback === \"string\" && args.feedback.length > 0 ? args.feedback : undefined;\n const decidedBy = String(args.decidedBy ?? \"\");\n this.applyApproval(handle, nodeId, decision, feedback, decidedBy);\n return JSON.stringify(s.execution);\n }\n\n private opApplyInput(\n handle: ConnectorHandle,\n s: FlowAdapterState,\n args: Record<string, unknown>,\n ): string {\n const nodeId = String(args.nodeId ?? \"\");\n const response = args.response;\n const providedBy = String(args.providedBy ?? \"\");\n this.applyInput(handle, nodeId, response, providedBy);\n return JSON.stringify(s.execution);\n }\n\n private opSetAutonomousMode(\n handle: ConnectorHandle,\n s: FlowAdapterState,\n args: Record<string, unknown>,\n ): string {\n const enabled = args.enabled === true || args.enabled === \"true\";\n this.setAutonomousMode(handle, enabled);\n return JSON.stringify(s.execution);\n }\n\n private opRetryNode(\n handle: ConnectorHandle,\n s: FlowAdapterState,\n args: Record<string, unknown>,\n ): string {\n const nodeId = String(args.nodeId ?? \"\");\n // `requestedBy` is informational only — the adapter doesn't record it\n // (consistent with how the typed `retry_flow_node` handler behaves\n // today; the field is logged at the runner, not in the snapshot).\n void String(args.requestedBy ?? \"\");\n this.retryNode(handle, nodeId);\n return JSON.stringify(s.execution);\n }\n\n private opHydrate(\n handle: ConnectorHandle,\n s: FlowAdapterState,\n args: Record<string, unknown>,\n ): string {\n const state = args.state as FlowExecution | undefined;\n if (!state || typeof state !== \"object\") {\n throw new Error(\"FlowAdapter: hydrate requires an args.state FlowExecution snapshot\");\n }\n this.hydrate(handle, state);\n return JSON.stringify(s.execution);\n }\n\n private opStart(\n handle: ConnectorHandle,\n s: FlowAdapterState,\n args: Record<string, unknown>,\n ): string {\n const flow = args.flow as FlowDefinition | undefined;\n if (!flow || typeof flow !== \"object\") {\n throw new Error(\"FlowAdapter: start requires args.flow (FlowDefinition)\");\n }\n const seed = (args.seed ?? {}) as {\n runId?: string;\n startedBy?: string;\n autonomousMode?: boolean;\n };\n if (!seed.runId || !seed.startedBy) {\n throw new Error(\"FlowAdapter: start requires args.seed.runId + args.seed.startedBy\");\n }\n // Seed a fresh execution in-place. Same flow used by `connect()` —\n // we reuse `buildInitialExecution` + `recompute` so the adapter\n // produces an identical initial FlowExecution to a fresh connect.\n s.flowDef = flow;\n s.execution = buildInitialExecution(flow, {\n runId: seed.runId,\n startedBy: seed.startedBy,\n autonomousMode: seed.autonomousMode ?? false,\n });\n s.execution = this.recompute(s);\n if (s.onChange) s.onChange(s.execution);\n return JSON.stringify(s.execution);\n }\n\n // ── Agent-side mutations (tool calls) ─────────────────────────────────────\n\n private doStartNode(handle: ConnectorHandle, nodeId: string): string {\n return this.mutate(handle, (s) => {\n const node = s.execution.nodes[nodeId];\n assertLegal(node, `node not in execution: ${nodeId}`);\n assertLegal(node.status === \"available\", `cannot start ${nodeId}: status is ${node.status}`);\n s.execution.nodes[nodeId] = {\n ...node,\n status: \"running\",\n startedAt: now(),\n };\n return JSON.stringify({ ok: true, status: \"running\" });\n });\n }\n\n private doRequestApproval(\n handle: ConnectorHandle,\n nodeId: string,\n summary: string,\n artifacts: ArtifactRef[],\n ): string {\n return this.mutate(handle, (s) => {\n const node = s.execution.nodes[nodeId];\n assertLegal(node, `node not in execution: ${nodeId}`);\n assertLegal(\n node.status === \"running\",\n `request_approval requires running, got ${node.status}`,\n );\n const approval: Approval = { requestedAt: now(), summary };\n const history = [...node.approvalHistory, approval];\n s.execution.nodes[nodeId] = {\n ...node,\n status: \"awaiting_approval\",\n approval,\n approvalHistory: history,\n // Stash output so the UI can render the approval card with artifacts\n // before the node reaches `complete`.\n output: { summary, artifacts },\n };\n return JSON.stringify({ ok: true, status: \"awaiting_approval\" });\n });\n }\n\n private doRequestInput(\n handle: ConnectorHandle,\n nodeId: string,\n prompt: string,\n schema: InputSchema,\n ): string {\n return this.mutate(handle, (s) => {\n const node = s.execution.nodes[nodeId];\n assertLegal(node, `node not in execution: ${nodeId}`);\n assertLegal(\n node.status === \"available\" ||\n node.status === \"running\" ||\n node.status === \"awaiting_approval\",\n `request_input not legal from ${node.status}`,\n );\n const input: InputRequest = { requestedAt: now(), prompt, schema };\n s.execution.nodes[nodeId] = {\n ...node,\n // Record the prior status so `applyInput` can restore it.\n // We encode this via `inputHistory` — the latest entry's metadata\n // includes the resume status in a convention-only field.\n status: \"awaiting_input\",\n input,\n inputHistory: [\n ...node.inputHistory,\n { ...input, response: { _resumeStatus: node.status } },\n ],\n };\n return JSON.stringify({ ok: true, status: \"awaiting_input\" });\n });\n }\n\n private doCompleteNode(handle: ConnectorHandle, nodeId: string, output: NodeOutput): string {\n return this.mutate(handle, (s) => {\n const node = s.execution.nodes[nodeId];\n assertLegal(node, `node not in execution: ${nodeId}`);\n\n const autonomous = s.execution.autonomousMode;\n const approvedPrior =\n node.status === \"awaiting_approval\" && node.approval?.decision === \"approved\";\n const runningAutonomous = node.status === \"running\" && autonomous;\n\n assertLegal(\n approvedPrior || runningAutonomous,\n `complete_node requires awaiting_approval+approved OR running+autonomous; node is ${node.status}${\n node.approval?.decision ? ` with approval ${node.approval.decision}` : \"\"\n }, autonomous=${autonomous}`,\n );\n\n s.execution.nodes[nodeId] = {\n ...node,\n status: \"complete\",\n completedAt: now(),\n output,\n };\n return JSON.stringify({ ok: true, status: \"complete\" });\n });\n }\n\n private doSkipNode(handle: ConnectorHandle, nodeId: string): string {\n return this.mutate(handle, (s) => {\n const node = s.execution.nodes[nodeId];\n assertLegal(node, `node not in execution: ${nodeId}`);\n assertLegal(isOptional(s.flowDef, nodeId), `cannot skip required node ${nodeId}`);\n s.execution.nodes[nodeId] = {\n ...node,\n status: \"skipped\",\n completedAt: now(),\n };\n return JSON.stringify({ ok: true, status: \"skipped\" });\n });\n }\n\n private doFailNode(\n handle: ConnectorHandle,\n nodeId: string,\n message: string,\n recoverable: boolean,\n ): string {\n return this.mutate(handle, (s) => {\n const node = s.execution.nodes[nodeId];\n assertLegal(node, `node not in execution: ${nodeId}`);\n const error: NodeError = { message, recoverable, at: now() };\n if (recoverable) {\n // Transition back to `available` for the agent to retry within\n // the same turn; keep the failure in history so the next turn\n // sees the prior error context.\n s.execution.nodes[nodeId] = {\n ...node,\n status: \"available\",\n error,\n errorHistory: [...node.errorHistory, error],\n };\n } else {\n s.execution.nodes[nodeId] = {\n ...node,\n status: \"failed\",\n completedAt: now(),\n error,\n errorHistory: [...node.errorHistory, error],\n };\n }\n return JSON.stringify({ ok: true, status: s.execution.nodes[nodeId].status });\n });\n }\n\n // ── Host-side mutations (not exposed as agent tools) ─────────────────────\n\n /**\n * Record an approval decision on a node currently `awaiting_approval`.\n * `approved` leaves the node in `awaiting_approval` — the agent\n * transitions it to `complete` on the next turn. `rejected` drops the\n * node back to `available` so the agent can retry.\n */\n applyApproval(\n handle: ConnectorHandle,\n nodeId: string,\n decision: \"approved\" | \"rejected\",\n feedback: string | undefined,\n decidedBy: string,\n ): void {\n this.mutate(handle, (s) => {\n const node = s.execution.nodes[nodeId];\n assertLegal(node, `applyApproval: unknown node ${nodeId}`);\n assertLegal(\n node.status === \"awaiting_approval\",\n `applyApproval: node ${nodeId} is ${node.status}, not awaiting_approval`,\n );\n const base = node.approval ?? { requestedAt: now(), summary: \"\" };\n const approval: Approval = {\n ...base,\n decidedAt: now(),\n decidedBy,\n decision,\n feedback,\n };\n // Replace the tail of history with the decided version so the\n // pointer and the history element stay in sync.\n const history = [...node.approvalHistory];\n if (history.length > 0) history[history.length - 1] = approval;\n else history.push(approval);\n\n if (decision === \"approved\") {\n s.execution.nodes[nodeId] = { ...node, approval, approvalHistory: history };\n } else {\n s.execution.nodes[nodeId] = {\n ...node,\n status: \"available\",\n approval,\n approvalHistory: history,\n };\n }\n return undefined;\n });\n }\n\n /**\n * Record a user-provided input on a node currently `awaiting_input`.\n * Transitions back to the status the node had before requesting input.\n */\n applyInput(handle: ConnectorHandle, nodeId: string, response: unknown, providedBy: string): void {\n this.mutate(handle, (s) => {\n const node = s.execution.nodes[nodeId];\n assertLegal(node, `applyInput: unknown node ${nodeId}`);\n assertLegal(\n node.status === \"awaiting_input\",\n `applyInput: node ${nodeId} is ${node.status}, not awaiting_input`,\n );\n\n // Recover the pre-input status from the last history entry's\n // `_resumeStatus` marker (see doRequestInput).\n const last = node.inputHistory[node.inputHistory.length - 1];\n const resumeStatus =\n (last?.response as { _resumeStatus?: NodeStatus } | undefined)?._resumeStatus ?? \"running\";\n\n const updated: InputRequest = {\n ...(node.input ?? { requestedAt: now(), prompt: \"\", schema: { kind: \"text\" } }),\n providedAt: now(),\n providedBy,\n response,\n };\n\n const history = [...node.inputHistory];\n if (history.length > 0) history[history.length - 1] = updated;\n else history.push(updated);\n\n s.execution.nodes[nodeId] = {\n ...node,\n status: resumeStatus,\n input: updated,\n inputHistory: history,\n };\n return undefined;\n });\n }\n\n /**\n * Transition a recoverable failed node back to `available` for retry.\n * Preserves the failure in `errorHistory` so the next turn's agent can\n * see the prior failure context.\n */\n retryNode(handle: ConnectorHandle, nodeId: string): void {\n this.mutate(handle, (s) => {\n const node = s.execution.nodes[nodeId];\n assertLegal(node, `retryNode: unknown node ${nodeId}`);\n assertLegal(\n node.status === \"failed\" && node.error?.recoverable === true,\n `retryNode: node ${nodeId} is not a recoverable failure (status=${node.status}, recoverable=${node.error?.recoverable})`,\n );\n s.execution.nodes[nodeId] = {\n ...node,\n status: \"available\",\n error: undefined,\n };\n return undefined;\n });\n }\n\n /** Toggle autonomous mode at the flow-execution level. */\n setAutonomousMode(handle: ConnectorHandle, enabled: boolean): void {\n this.mutate(handle, (s) => {\n s.execution = { ...s.execution, autonomousMode: enabled };\n return undefined;\n });\n }\n\n /** Cancel the flow run. Status transitions to `cancelled`; dependents stay put. */\n cancel(handle: ConnectorHandle): void {\n this.mutate(handle, (s) => {\n s.execution = { ...s.execution, status: \"cancelled\" };\n return undefined;\n });\n }\n\n /** Read-only access to the current FlowExecution snapshot. */\n getExecution(handle: ConnectorHandle): FlowExecution {\n return this.s(handle).execution;\n }\n\n // ── Private helpers ──\n\n private s(handle: ConnectorHandle): FlowAdapterState {\n return handle.state as FlowAdapterState;\n }\n\n /**\n * Central mutation pipeline: runs the mutator, recomputes derived\n * fields, updates the flow-level `status` if the mutation completed\n * or failed the flow, fires `onChange` once, and (Phase 3, 2026-05-08)\n * optionally signals the {@link FlowAdapterStimulusBus} so the runner\n * can kick a turn outside the legacy orchestrator path.\n *\n * The bus signal path is gated by the `useBusForStimulus` flag set at\n * connect time — Phase 3 builds the path; Phase 4 flips the default to\n * true globally and removes the orchestrator's onStateChange\n * subscription.\n */\n private mutate(handle: ConnectorHandle, fn: (s: FlowAdapterState) => unknown): string {\n const s = this.s(handle);\n const previousExecution = s.lastSignaledExecution;\n const result = fn(s);\n s.execution = this.recompute(s);\n if (s.onChange) s.onChange(s.execution);\n\n if (s.useBusForStimulus && s.stimulusBus) {\n const stim = computeStimulus(previousExecution, s.execution);\n if (stim) {\n const fragment = renderStimulusPrompt(stim);\n const connectorId = s.connectorId ?? handle.id;\n // Fire-and-forget — the bus's signal() returns a promise that\n // resolves once the resulting turn drains, but the adapter must\n // not block agent tool-call completion on the next turn settling.\n // Swallow rejections so a downstream turn failure can't propagate\n // back into the synchronous mutate() pipeline.\n s.stimulusBus\n .signal(connectorId, {\n promptFragment: fragment,\n meta: { kind: stim.kind, runId: s.execution.runId },\n })\n .catch(() => {\n /* rejection surfaces via the bus's own logging path */\n });\n s.lastSignaledExecution = s.execution;\n }\n }\n\n return typeof result === \"string\" ? result : JSON.stringify({ ok: true });\n }\n\n /**\n * Recompute derived fields (`focus`, `done`, and the rolled-up flow\n * `status`) from the current node map, without touching per-node\n * state directly.\n */\n private recompute(s: FlowAdapterState): FlowExecution {\n const snapshots = snapshotMap(s.execution);\n const computed = computeFlowStateFromSnapshots(s.flowDef, snapshots);\n\n // Elevate any `not_started` nodes that are now runnable to `available`.\n const nodes = { ...s.execution.nodes };\n for (const ns of computed.nodes) {\n const existing = nodes[ns.nodeId];\n if (!existing) continue;\n if (existing.status === \"not_started\" && ns.status === \"available\") {\n nodes[ns.nodeId] = { ...existing, status: \"available\" };\n }\n }\n\n // Roll up flow-level status when the computation tells us we're done,\n // or when a required node is stuck in `failed`.\n let flowStatus: FlowExecutionStatus = s.execution.status;\n if (flowStatus !== \"cancelled\") {\n const anyRequiredFailed = s.flowDef.nodes\n .filter((n) => n.type === \"skill\" && !(n.data?.optional ?? false))\n .some((n) => nodes[n.id]?.status === \"failed\");\n if (anyRequiredFailed) {\n flowStatus = \"failed\";\n } else if (computed.done) {\n flowStatus = \"complete\";\n } else if (flowStatus !== \"paused\") {\n flowStatus = \"running\";\n }\n }\n\n return {\n ...s.execution,\n status: flowStatus,\n nodes,\n focus: computed.focus,\n done: computed.done && flowStatus === \"complete\",\n };\n }\n\n /**\n * Build curated context for a node by collecting the summaries and\n * artifact refs produced by its upstream flow-type predecessors.\n */\n private buildHandoff(s: FlowAdapterState, nodeId: string): string {\n const deps = flowPredecessors(s.flowDef, nodeId);\n if (deps.length === 0) return \"(no prior context)\";\n\n const sections: string[] = [];\n for (const depId of deps) {\n const exec = s.execution.nodes[depId];\n const output = exec?.output;\n if (!output) continue;\n const artifacts =\n output.artifacts.length > 0\n ? `\\nArtifacts: ${output.artifacts.map((a) => a.uri).join(\", \")}`\n : \"\";\n const concerns =\n output.concerns && output.concerns.length > 0\n ? `\\nConcerns: ${output.concerns.join(\"; \")}`\n : \"\";\n const label = s.flowDef.nodes.find((n) => n.id === depId)?.data?.label ?? depId;\n sections.push(`### ${label} (${exec?.status})\\n${output.summary}${artifacts}${concerns}`);\n }\n\n return sections.length > 0 ? sections.join(\"\\n\\n\") : \"(no prior context)\";\n }\n}\n\n// ── Pure helpers ────────────────────────────────────────────────────────────\n\n/** IDs of nodes connected to `nodeId` via incoming flow-type edges. */\nfunction flowPredecessors(flowDef: FlowDefinition, nodeId: string): string[] {\n return flowDef.edges.filter((e) => e.target === nodeId && e.type === \"flow\").map((e) => e.source);\n}\n\nfunction safeParseStringArray(value: unknown): string[] {\n if (!value) return [];\n if (Array.isArray(value)) return value.map(String);\n if (typeof value === \"string\") {\n try {\n const parsed = JSON.parse(value);\n return Array.isArray(parsed) ? parsed.map(String) : [];\n } catch {\n return [];\n }\n }\n return [];\n}\n\nfunction safeParseArtifacts(value: unknown): ArtifactRef[] {\n if (!value) return [];\n const raw = typeof value === \"string\" ? safeJsonArray(value) : Array.isArray(value) ? value : [];\n return raw\n .filter((r): r is Record<string, unknown> => !!r && typeof r === \"object\")\n .map((r: Record<string, unknown>) => ({\n uri: String(r.uri ?? \"\"),\n connectorId: String(r.connectorId ?? \"workspace\"),\n kind: (r.kind as ArtifactRef[\"kind\"]) ?? \"other\",\n lifetime: (r.lifetime as ArtifactRef[\"lifetime\"]) ?? \"session\",\n producedBy: String(r.producedBy ?? \"\"),\n }));\n}\n\nfunction safeJsonArray(value: string): unknown[] {\n try {\n const parsed = JSON.parse(value);\n return Array.isArray(parsed) ? parsed : [];\n } catch {\n return [];\n }\n}\n\nfunction safeParseInputSchema(value: unknown): InputSchema {\n if (value && typeof value === \"object\") return value as InputSchema;\n if (typeof value === \"string\") {\n try {\n return JSON.parse(value) as InputSchema;\n } catch {\n return { kind: \"text\" };\n }\n }\n return { kind: \"text\" };\n}\n\n// Re-export `isBlocking` for convenience so callers don't need two imports\n// when reasoning about node state blocking semantics.\nexport { isBlocking };\n\n/**\n * Creates a new FlowAdapter instance.\n * @returns Configured FlowAdapter ready to be registered in the connector registry.\n * @docLink packages/factory-assets/api-reference#flow-connector-factory\n */\nexport function createConnector(): FlowAdapter {\n return new FlowAdapter();\n}\n"]}