@geminixiang/mikan 1.0.0-beta.37 → 1.0.0-beta.39

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 (201) hide show
  1. package/CHANGELOG.md +21 -0
  2. package/README.md +1 -1
  3. package/dist/adapter.js +1 -1
  4. package/dist/adapter.js.map +1 -1
  5. package/dist/adapters/discord/bot.d.ts +3 -6
  6. package/dist/adapters/discord/bot.d.ts.map +1 -1
  7. package/dist/adapters/discord/bot.js +16 -39
  8. package/dist/adapters/discord/bot.js.map +1 -1
  9. package/dist/adapters/github/bot.d.ts +2 -0
  10. package/dist/adapters/github/bot.d.ts.map +1 -1
  11. package/dist/adapters/github/bot.js +15 -11
  12. package/dist/adapters/github/bot.js.map +1 -1
  13. package/dist/adapters/github/github-ops.d.ts +1 -1
  14. package/dist/adapters/github/github-ops.d.ts.map +1 -1
  15. package/dist/adapters/github/github-ops.js +2 -1
  16. package/dist/adapters/github/github-ops.js.map +1 -1
  17. package/dist/adapters/github/repo.d.ts +2 -1
  18. package/dist/adapters/github/repo.d.ts.map +1 -1
  19. package/dist/adapters/github/repo.js +2 -3
  20. package/dist/adapters/github/repo.js.map +1 -1
  21. package/dist/adapters/github/types.d.ts +1 -1
  22. package/dist/adapters/github/types.d.ts.map +1 -1
  23. package/dist/adapters/github/types.js.map +1 -1
  24. package/dist/adapters/intake.js +1 -1
  25. package/dist/adapters/intake.js.map +1 -1
  26. package/dist/adapters/shared.d.ts +17 -5
  27. package/dist/adapters/shared.d.ts.map +1 -1
  28. package/dist/adapters/shared.js +44 -8
  29. package/dist/adapters/shared.js.map +1 -1
  30. package/dist/adapters/slack/blocks.d.ts +14 -0
  31. package/dist/adapters/slack/blocks.d.ts.map +1 -1
  32. package/dist/adapters/slack/blocks.js +34 -0
  33. package/dist/adapters/slack/blocks.js.map +1 -1
  34. package/dist/adapters/slack/bot.d.ts +19 -6
  35. package/dist/adapters/slack/bot.d.ts.map +1 -1
  36. package/dist/adapters/slack/bot.js +88 -21
  37. package/dist/adapters/slack/bot.js.map +1 -1
  38. package/dist/adapters/slack/types.d.ts +1 -1
  39. package/dist/adapters/slack/types.js.map +1 -1
  40. package/dist/adapters/telegram/bot.d.ts +5 -6
  41. package/dist/adapters/telegram/bot.d.ts.map +1 -1
  42. package/dist/adapters/telegram/bot.js +29 -51
  43. package/dist/adapters/telegram/bot.js.map +1 -1
  44. package/dist/adapters/types.d.ts +19 -1
  45. package/dist/adapters/types.d.ts.map +1 -1
  46. package/dist/adapters/types.js.map +1 -1
  47. package/dist/agent.d.ts +0 -1
  48. package/dist/agent.d.ts.map +1 -1
  49. package/dist/agent.js +79 -101
  50. package/dist/agent.js.map +1 -1
  51. package/dist/cli/ext-dev.d.ts.map +1 -1
  52. package/dist/cli/ext-dev.js +8 -8
  53. package/dist/cli/ext-dev.js.map +1 -1
  54. package/dist/cli/ext.js +3 -3
  55. package/dist/cli/ext.js.map +1 -1
  56. package/dist/cli/office.js +2 -2
  57. package/dist/cli/office.js.map +1 -1
  58. package/dist/commands/auto-reply.d.ts.map +1 -1
  59. package/dist/commands/auto-reply.js +1 -2
  60. package/dist/commands/auto-reply.js.map +1 -1
  61. package/dist/commands/login.js +1 -1
  62. package/dist/commands/login.js.map +1 -1
  63. package/dist/commands/manifest.d.ts.map +1 -1
  64. package/dist/commands/manifest.js +3 -1
  65. package/dist/commands/manifest.js.map +1 -1
  66. package/dist/commands/model.d.ts.map +1 -1
  67. package/dist/commands/model.js +3 -7
  68. package/dist/commands/model.js.map +1 -1
  69. package/dist/commands/sandbox.d.ts.map +1 -1
  70. package/dist/commands/sandbox.js +7 -7
  71. package/dist/commands/sandbox.js.map +1 -1
  72. package/dist/commands/session-view.d.ts.map +1 -1
  73. package/dist/commands/session-view.js +1 -2
  74. package/dist/commands/session-view.js.map +1 -1
  75. package/dist/commands/types.d.ts +2 -1
  76. package/dist/commands/types.d.ts.map +1 -1
  77. package/dist/commands/types.js.map +1 -1
  78. package/dist/config.d.ts +10 -18
  79. package/dist/config.d.ts.map +1 -1
  80. package/dist/config.js +16 -15
  81. package/dist/config.js.map +1 -1
  82. package/dist/execution-resolver.d.ts +4 -6
  83. package/dist/execution-resolver.d.ts.map +1 -1
  84. package/dist/execution-resolver.js +10 -19
  85. package/dist/execution-resolver.js.map +1 -1
  86. package/dist/harness/extensions/loader.js +1 -1
  87. package/dist/harness/extensions/loader.js.map +1 -1
  88. package/dist/harness/skills.d.ts +8 -0
  89. package/dist/harness/skills.d.ts.map +1 -1
  90. package/dist/harness/skills.js +46 -4
  91. package/dist/harness/skills.js.map +1 -1
  92. package/dist/harness/types.d.ts +2 -0
  93. package/dist/harness/types.d.ts.map +1 -1
  94. package/dist/harness/types.js.map +1 -1
  95. package/dist/index.d.ts +2 -0
  96. package/dist/index.d.ts.map +1 -1
  97. package/dist/index.js +1 -0
  98. package/dist/index.js.map +1 -1
  99. package/dist/main.js +16 -16
  100. package/dist/main.js.map +1 -1
  101. package/dist/{office-address.d.ts → office/address.d.ts} +13 -14
  102. package/dist/office/address.d.ts.map +1 -0
  103. package/dist/{office-address.js → office/address.js} +13 -18
  104. package/dist/office/address.js.map +1 -0
  105. package/dist/office/index.d.ts +11 -0
  106. package/dist/office/index.d.ts.map +1 -0
  107. package/dist/office/index.js +11 -0
  108. package/dist/office/index.js.map +1 -0
  109. package/dist/office/layout.d.ts +20 -0
  110. package/dist/office/layout.d.ts.map +1 -0
  111. package/dist/office/layout.js +88 -0
  112. package/dist/office/layout.js.map +1 -0
  113. package/dist/{office-migration.d.ts → office/migration.d.ts} +3 -3
  114. package/dist/office/migration.d.ts.map +1 -0
  115. package/dist/{office-migration.js → office/migration.js} +8 -12
  116. package/dist/office/migration.js.map +1 -0
  117. package/dist/{office-registry.d.ts → office/registry.d.ts} +18 -24
  118. package/dist/office/registry.d.ts.map +1 -0
  119. package/dist/{office-registry.js → office/registry.js} +22 -83
  120. package/dist/office/registry.js.map +1 -0
  121. package/dist/office/types.d.ts +71 -0
  122. package/dist/office/types.d.ts.map +1 -0
  123. package/dist/office/types.js +2 -0
  124. package/dist/office/types.js.map +1 -0
  125. package/dist/packages/admin.js +5 -5
  126. package/dist/packages/admin.js.map +1 -1
  127. package/dist/packages/inspect.d.ts.map +1 -1
  128. package/dist/packages/inspect.js +3 -8
  129. package/dist/packages/inspect.js.map +1 -1
  130. package/dist/packages/materialize.js +1 -1
  131. package/dist/packages/materialize.js.map +1 -1
  132. package/dist/packages/resolve.js +5 -8
  133. package/dist/packages/resolve.js.map +1 -1
  134. package/dist/packages/types.d.ts +2 -5
  135. package/dist/packages/types.d.ts.map +1 -1
  136. package/dist/packages/types.js.map +1 -1
  137. package/dist/runtime/conversation-runtime.d.ts.map +1 -1
  138. package/dist/runtime/conversation-runtime.js +13 -15
  139. package/dist/runtime/conversation-runtime.js.map +1 -1
  140. package/dist/runtime/session-lifecycle.js +1 -1
  141. package/dist/runtime/session-lifecycle.js.map +1 -1
  142. package/dist/runtime/types.d.ts +3 -2
  143. package/dist/runtime/types.d.ts.map +1 -1
  144. package/dist/runtime/types.js.map +1 -1
  145. package/dist/sandbox/identity.js +1 -1
  146. package/dist/sandbox/identity.js.map +1 -1
  147. package/dist/settings-mutation.d.ts +3 -2
  148. package/dist/settings-mutation.d.ts.map +1 -1
  149. package/dist/settings-mutation.js +6 -7
  150. package/dist/settings-mutation.js.map +1 -1
  151. package/dist/tools/generate-image.d.ts +8 -2
  152. package/dist/tools/generate-image.d.ts.map +1 -1
  153. package/dist/tools/generate-image.js +5 -3
  154. package/dist/tools/generate-image.js.map +1 -1
  155. package/dist/tools/index.d.ts +5 -0
  156. package/dist/tools/index.d.ts.map +1 -1
  157. package/dist/tools/index.js +3 -5
  158. package/dist/tools/index.js.map +1 -1
  159. package/dist/trigger.d.ts +1 -1
  160. package/dist/trigger.d.ts.map +1 -1
  161. package/dist/trigger.js +5 -10
  162. package/dist/trigger.js.map +1 -1
  163. package/dist/types.d.ts +3 -22
  164. package/dist/types.d.ts.map +1 -1
  165. package/dist/types.js.map +1 -1
  166. package/dist/vault/index.js +1 -1
  167. package/dist/vault/index.js.map +1 -1
  168. package/dist/vault/injection.d.ts +3 -1
  169. package/dist/vault/injection.d.ts.map +1 -1
  170. package/dist/vault/injection.js +2 -2
  171. package/dist/vault/injection.js.map +1 -1
  172. package/dist/web/admin/portal.d.ts.map +1 -1
  173. package/dist/web/admin/portal.js +67 -80
  174. package/dist/web/admin/portal.js.map +1 -1
  175. package/dist/web/admin/types.d.ts +2 -1
  176. package/dist/web/admin/types.d.ts.map +1 -1
  177. package/dist/web/admin/types.js.map +1 -1
  178. package/dist/web/server.d.ts +1 -1
  179. package/dist/web/server.d.ts.map +1 -1
  180. package/dist/web/server.js +3 -3
  181. package/dist/web/server.js.map +1 -1
  182. package/dist/web/session-view/portal.js +1 -1
  183. package/dist/web/session-view/portal.js.map +1 -1
  184. package/dist/workspace-projection/index.d.ts +2 -4
  185. package/dist/workspace-projection/index.d.ts.map +1 -1
  186. package/dist/workspace-projection/index.js +21 -56
  187. package/dist/workspace-projection/index.js.map +1 -1
  188. package/dist/workspace-projection/types.d.ts +0 -2
  189. package/dist/workspace-projection/types.d.ts.map +1 -1
  190. package/dist/workspace-projection/types.js.map +1 -1
  191. package/package.json +41 -16
  192. package/dist/office-address.d.ts.map +0 -1
  193. package/dist/office-address.js.map +0 -1
  194. package/dist/office-migration.d.ts.map +0 -1
  195. package/dist/office-migration.js.map +0 -1
  196. package/dist/office-registry.d.ts.map +0 -1
  197. package/dist/office-registry.js.map +0 -1
  198. package/dist/store.d.ts +0 -51
  199. package/dist/store.d.ts.map +0 -1
  200. package/dist/store.js +0 -185
  201. package/dist/store.js.map +0 -1
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.js","sourceRoot":"","sources":["../../src/office/types.ts"],"names":[],"mappings":"","sourcesContent":["import type { OfficeAddress, OfficeKey } from \"../types.js\";\n\n/**\n * One mikan deployment's agent world on the host: the workspace root, the\n * workspace-global surfaces, and the factory for per-conversation offices.\n * Constructed once per process (`createWorkspace`); everything downstream\n * receives the value instead of re-deriving paths from root strings.\n */\nexport interface Workspace {\n /** Host workspace root directory. */\n readonly root: string;\n /**\n * Host-only state root (settings, credentials, extension code/data).\n * Not part of the Workspace projection; carried here so offices can\n * derive their state dirs and the registry knows where its journal lives.\n */\n readonly stateDir: string;\n /** Workspace-global memory file: `<root>/MEMORY.md`. */\n readonly memoryPath: string;\n /** Workspace-global skills directory: `<root>/skills`. */\n readonly skillsDir: string;\n /** The workspace scheduling bus: `<root>/events` (global by design). */\n readonly eventsDir: string;\n /** Subagent profile patches: `<root>/agents`. */\n readonly agentsDir: string;\n /** Workspace-root entries that are shared infrastructure, never office dirs. */\n readonly reservedNames: ReadonlySet<string>;\n /**\n * The Conversation office for an address. Values are memoized per address,\n * so repeated calls on hot paths cost one map lookup, not a hash.\n */\n office(address: OfficeAddress): Office;\n}\n\n/**\n * One Conversation office: canonical identity plus the office's host-side\n * directory layout. A frozen value — every field is precomputed at\n * construction. Fields exist only for paths that more than one module needs;\n * single-consumer subpaths stay `join(office.dir, …)` at their call site.\n */\nexport interface Office {\n /** Canonical identity: platform plus raw platform conversation id. */\n readonly address: OfficeAddress;\n /**\n * The office key — the collision-resistant directory segment, identical on\n * the host and inside sandbox runtimes, and the conversation vault key.\n */\n readonly key: OfficeKey;\n /** The office working directory: `<workspace root>/<key>`. */\n readonly dir: string;\n /** Conversation memory file: `<dir>/MEMORY.md`. */\n readonly memoryPath: string;\n /** Conversation skills directory: `<dir>/skills`. */\n readonly skillsDir: string;\n /** Persisted chat-session files: `<dir>/sessions`. */\n readonly sessionsDir: string;\n /** Downloaded message attachments: `<dir>/attachments`. */\n readonly attachmentsDir: string;\n /** Human-readable message history: `<dir>/log.jsonl`. */\n readonly logPath: string;\n /** Host-only per-office state: `<state dir>/conversations/<key>`. */\n readonly stateDir: string;\n /** The workspace this office belongs to. */\n readonly workspace: Workspace;\n /**\n * Materialize the office working directory: record the office in the\n * registry, then create the directory. Idempotent and safe on hot\n * per-message paths — recording is cached, the mkdir is a guarded check.\n * Returns `dir`.\n */\n ensure(): string;\n}\n"]}
@@ -24,8 +24,8 @@ export function addPackage(scope, rawSource, context) {
24
24
  const source = formatSource(parseSource(rawSource));
25
25
  const materialized = materializeSource(source, {
26
26
  scope,
27
- address: context.address,
28
- stateDir: context.stateDir,
27
+ address: context.office.address,
28
+ stateDir: context.office.workspace.stateDir,
29
29
  mode: "fetch",
30
30
  });
31
31
  const existing = declaredSources(scope, context);
@@ -55,8 +55,8 @@ export function refreshPackage(scope, rawSource, context) {
55
55
  }
56
56
  const materialized = materializeSource(rawSource, {
57
57
  scope,
58
- address: context.address,
59
- stateDir: context.stateDir,
58
+ address: context.office.address,
59
+ stateDir: context.office.workspace.stateDir,
60
60
  mode: "refresh",
61
61
  });
62
62
  return { source: rawSource, dir: materialized.dir };
@@ -89,7 +89,7 @@ function writePackages(scope, packages, context) {
89
89
  applyGlobalSettings(context.runtime, { packages });
90
90
  return;
91
91
  }
92
- const result = applyConversationSettings(context.runtime, context.workingDir, context.address, {
92
+ const result = applyConversationSettings(context.runtime, context.office, {
93
93
  packages,
94
94
  });
95
95
  if (!result.ok)
@@ -1 +1 @@
1
- {"version":3,"file":"admin.js","sourceRoot":"","sources":["../../src/packages/admin.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AACH,OAAO,EAAE,yBAAyB,EAAE,mBAAmB,EAAE,MAAM,yBAAyB,CAAC;AACzF,OAAO,EAAE,YAAY,EAAE,WAAW,EAAE,cAAc,EAAE,MAAM,aAAa,CAAC;AACxE,OAAO,EAAE,iBAAiB,EAAE,MAAM,kBAAkB,CAAC;AACrD,OAAO,EAAE,eAAe,EAAE,MAAM,cAAc,CAAC;AAK/C;;;;GAIG;AACH,MAAM,UAAU,UAAU,CACxB,KAAmB,EACnB,SAAiB,EACjB,OAA4B;IAE5B,MAAM,MAAM,GAAG,YAAY,CAAC,WAAW,CAAC,SAAS,CAAC,CAAC,CAAC;IACpD,M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AuB,KAAK,WAAW,SAAS,EAAE,CAAC,CAAC;IACtE,CAAC;IACD,MAAM,YAAY,GAAG,iBAAiB,CAAC,SAAS,EAAE;QAChD,KAAK;QACL,OAAO,EAAE,OAAO,CAAC,OAAO;QACxB,QAAQ,EAAE,OAAO,CAAC,QAAQ;QAC1B,IAAI,EAAE,SAAS;KAChB,CAAC,CAAC;IACH,OAAO,EAAE,MAAM,EAAE,SAAS,EAAE,GAAG,EAAE,YAAY,CAAC,GAAG,EAAE,CAAC;AACtD,CAAC;AAED,SAAS,kBAAkB,CAAC,MAAc;IACxC,MAAM,MAAM,GAAG,YAAY,CAAC,MAAM,CAAC,CAAC;IACpC,OAAO,CAAC,KAAK,EAAE,EAAE,CAAC,YAAY,CAAC,KAAK,CAAC,KAAK,MAAM,CAAC;AACnD,CAAC;AAED;;;;GAIG;AACH,SAAS,YAAY,CAAC,MAAc;IAClC,IAAI,CAAC;QACH,OAAO,cAAc,CAAC,WAAW,CAAC,MAAM,CAAC,CAAC,CAAC;IAC7C,CAAC;IAAC,MAAM,CAAC;QACP,OAAO,OAAO,MAAM,EAAE,CAAC;IACzB,CAAC;AACH,CAAC;AAED;;;;;GAKG;AACH,SAAS,aAAa,CACpB,KAAmB,EACnB,QAAkB,EAClB,OAA4B;IAE5B,IAAI,KAAK,KAAK,QAAQ,EAAE,CAAC;QACvB,mBAAmB,CAAC,OAAO,CAAC,OAAO,EAAE,EAAE,QAAQ,EAAE,CAAC,CAAC;QACnD,OAAO;IACT,CAAC;IACD,MAAM,MAAM,GAAG,yBAAyB,CAAC,OAAO,CAAC,OAAO,EAAE,OAAO,CAAC,UAAU,EAAE,OAAO,CAAC,OAAO,EAAE;QAC7F,QAAQ;KACT,CAAC,CAAC;IACH,IAAI,CAAC,MAAM,CAAC,EAAE;QAAE,MAAM,IAAI,KAAK,CAAC,2DAA2D,CAAC,CAAC;AAC/F,CAAC","sourcesContent":["/**\n * The write operations behind the admin portal's package panels.\n *\n * The ordering here is the whole point: **materialize first, persist second.**\n * A source is fetched and validated while the person who typed it is still\n * looking at the form, so a typo, a private repo, a bad `#subpath`, or a repo\n * with no extension in it fails in front of them. Persisting first and\n * fetching at load time would turn every one of those into \"the bot just\n * doesn't have the feature\", discovered later and usually by someone else.\n *\n * Activation stays where it was: the next harness instance (`/pi-new`) picks\n * up what is on disk. Only the failure reporting moves earlier.\n */\nimport { applyConversationSettings, applyGlobalSettings } from \"../settings-mutation.js\";\nimport { formatSource, parseSource, sourceIdentity } from \"./source.js\";\nimport { materializeSource } from \"./materialize.js\";\nimport { declaredSources } from \"./inspect.js\";\nimport type { PackageAdminContext, PackageScope, PackageWriteResult } from \"./types.js\";\n\nexport type { PackageAdminContext, PackageWriteResult } from \"./types.js\";\n\n/**\n * Add a source to a scope, or move an existing one to a new ref. Fetches and\n * validates before writing, and is idempotent: adding a source already present\n * re-materializes it and leaves the list unchanged.\n */\nexport function addPackage(\n scope: PackageScope,\n rawSource: string,\n context: PackageAdminContext,\n): PackageWriteResult {\n const source = formatSource(parseSource(rawSource));\n const materialized = materializeSource(source, {\n scope,\n address: context.address,\n stateDir: context.stateDir,\n mode: \"fetch\",\n });\n\n const existing = declaredSources(scope, context);\n // Replace any entry for the same package so re-adding with a new ref moves\n // the pin instead of leaving two conflicting lines in settings.\n const identity = sameIdentityFilter(source);\n writePackages(scope, [...existing.filter((entry) => !identity(entry)), source], context);\n return { source, dir: materialized.dir };\n}\n\n/**\n * Drop a source from a scope's list. The materialized clone is left on disk —\n * removal is a declaration change, and keeping the checkout makes re-adding\n * instant and lets an admin undo a mistake without a network round trip.\n */\nexport function removePackage(\n scope: PackageScope,\n rawSource: string,\n context: PackageAdminContext,\n): boolean {\n const existing = declaredSources(scope, context);\n const remaining = existing.filter((entry) => entry !== rawSource);\n if (remaining.length === existing.length) return false;\n writePackages(scope, remaining, context);\n return true;\n}\n\n/** Re-fetch a package that is already declared, moving it to its ref's current tip. */\nexport function refreshPackage(\n scope: PackageScope,\n rawSource: string,\n context: PackageAdminContext,\n): PackageWriteResult {\n if (!declaredSources(scope, context).includes(rawSource)) {\n throw new Error(`Not declared in the ${scope} scope: ${rawSource}`);\n }\n const materialized = materializeSource(rawSource, {\n scope,\n address: context.address,\n stateDir: context.stateDir,\n mode: \"refresh\",\n });\n return { source: rawSource, dir: materialized.dir };\n}\n\nfunction sameIdentityFilter(source: string): (entry: string) => boolean {\n const target = safeIdentity(source);\n return (entry) => safeIdentity(entry) === target;\n}\n\n/**\n * Identity of a declared entry, falling back to the raw string when it does\n * not parse. A malformed entry must still be matchable so an admin can replace\n * or remove the exact line they typed.\n */\nfunction safeIdentity(source: string): string {\n try {\n return sourceIdentity(parseSource(source));\n } catch {\n return `raw:${source}`;\n }\n}\n\n/**\n * Writes go through the settings-mutation seam rather than touching config\n * directly, so package edits obey the same runner-cache policy as every other\n * portal write. Packages are not a cached-runner key, so this writes and\n * leaves live conversations alone until their next harness instance.\n */\nfunction writePackages(\n scope: PackageScope,\n packages: string[],\n context: PackageAdminContext,\n): void {\n if (scope === \"global\") {\n applyGlobalSettings(context.runtime, { packages });\n return;\n }\n const result = applyConversationSettings(context.runtime, context.workingDir, context.address, {\n packages,\n });\n if (!result.ok) throw new Error(\"Conversation is busy; try again when the current run ends\");\n}\n"]}
1
+ {"version":3,"file":"admin.js","sourceRoot":"","sources":["../../src/packages/admin.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AACH,OAAO,EAAE,yBAAyB,EAAE,mBAAmB,EAAE,MAAM,yBAAyB,CAAC;AACzF,OAAO,EAAE,YAAY,EAAE,WAAW,EAAE,cAAc,EAAE,MAAM,aAAa,CAAC;AACxE,OAAO,EAAE,iBAAiB,EAAE,MAAM,kBAAkB,CAAC;AACrD,OAAO,EAAE,eAAe,EAAE,MAAM,cAAc,CAAC;AAK/C;;;;GAIG;AACH,MAAM,UAAU,UAAU,CACxB,KAAmB,EACnB,SAAiB,EACjB,OAA4B;IAE5B,MAAM,MAAM,GAAG,YAAY,CAAC,WAAW,C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CAAC,CAAC;AAC/F,CAAC","sourcesContent":["/**\n * The write operations behind the admin portal's package panels.\n *\n * The ordering here is the whole point: **materialize first, persist second.**\n * A source is fetched and validated while the person who typed it is still\n * looking at the form, so a typo, a private repo, a bad `#subpath`, or a repo\n * with no extension in it fails in front of them. Persisting first and\n * fetching at load time would turn every one of those into \"the bot just\n * doesn't have the feature\", discovered later and usually by someone else.\n *\n * Activation stays where it was: the next harness instance (`/pi-new`) picks\n * up what is on disk. Only the failure reporting moves earlier.\n */\nimport { applyConversationSettings, applyGlobalSettings } from \"../settings-mutation.js\";\nimport { formatSource, parseSource, sourceIdentity } from \"./source.js\";\nimport { materializeSource } from \"./materialize.js\";\nimport { declaredSources } from \"./inspect.js\";\nimport type { PackageAdminContext, PackageScope, PackageWriteResult } from \"./types.js\";\n\nexport type { PackageAdminContext, PackageWriteResult } from \"./types.js\";\n\n/**\n * Add a source to a scope, or move an existing one to a new ref. Fetches and\n * validates before writing, and is idempotent: adding a source already present\n * re-materializes it and leaves the list unchanged.\n */\nexport function addPackage(\n scope: PackageScope,\n rawSource: string,\n context: PackageAdminContext,\n): PackageWriteResult {\n const source = formatSource(parseSource(rawSource));\n const materialized = materializeSource(source, {\n scope,\n address: context.office.address,\n stateDir: context.office.workspace.stateDir,\n mode: \"fetch\",\n });\n\n const existing = declaredSources(scope, context);\n // Replace any entry for the same package so re-adding with a new ref moves\n // the pin instead of leaving two conflicting lines in settings.\n const identity = sameIdentityFilter(source);\n writePackages(scope, [...existing.filter((entry) => !identity(entry)), source], context);\n return { source, dir: materialized.dir };\n}\n\n/**\n * Drop a source from a scope's list. The materialized clone is left on disk —\n * removal is a declaration change, and keeping the checkout makes re-adding\n * instant and lets an admin undo a mistake without a network round trip.\n */\nexport function removePackage(\n scope: PackageScope,\n rawSource: string,\n context: PackageAdminContext,\n): boolean {\n const existing = declaredSources(scope, context);\n const remaining = existing.filter((entry) => entry !== rawSource);\n if (remaining.length === existing.length) return false;\n writePackages(scope, remaining, context);\n return true;\n}\n\n/** Re-fetch a package that is already declared, moving it to its ref's current tip. */\nexport function refreshPackage(\n scope: PackageScope,\n rawSource: string,\n context: PackageAdminContext,\n): PackageWriteResult {\n if (!declaredSources(scope, context).includes(rawSource)) {\n throw new Error(`Not declared in the ${scope} scope: ${rawSource}`);\n }\n const materialized = materializeSource(rawSource, {\n scope,\n address: context.office.address,\n stateDir: context.office.workspace.stateDir,\n mode: \"refresh\",\n });\n return { source: rawSource, dir: materialized.dir };\n}\n\nfunction sameIdentityFilter(source: string): (entry: string) => boolean {\n const target = safeIdentity(source);\n return (entry) => safeIdentity(entry) === target;\n}\n\n/**\n * Identity of a declared entry, falling back to the raw string when it does\n * not parse. A malformed entry must still be matchable so an admin can replace\n * or remove the exact line they typed.\n */\nfunction safeIdentity(source: string): string {\n try {\n return sourceIdentity(parseSource(source));\n } catch {\n return `raw:${source}`;\n }\n}\n\n/**\n * Writes go through the settings-mutation seam rather than touching config\n * directly, so package edits obey the same runner-cache policy as every other\n * portal write. Packages are not a cached-runner key, so this writes and\n * leaves live conversations alone until their next harness instance.\n */\nfunction writePackages(\n scope: PackageScope,\n packages: string[],\n context: PackageAdminContext,\n): void {\n if (scope === \"global\") {\n applyGlobalSettings(context.runtime, { packages });\n return;\n }\n const result = applyConversationSettings(context.runtime, context.office, {\n packages,\n });\n if (!result.ok) throw new Error(\"Conversation is busy; try again when the current run ends\");\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"inspect.d.ts","sourceRoot":"","sources":["../../src/packages/inspect.ts"],"names":[],"mappings":"AAeA,OAAO,KAAK,EACV,gBAAgB,EAChB,YAAY,EAEZ,sBAAsB,EACvB,MAAM,YAAY,CAAC;AAEpB,YAAY,EAAE,gBAAgB,EAAE,MAAM,YAAY,CAAC;AAEnD;;;;GAIG;AACH,wBAAsB,2BAA2B,CAC/C,OAAO,EAAE,sBAAsB,GAC9B,OAAO,CAAC,gBAAgB,CAAC,CAiB3B;AAED,qFAAqF;AACrF,wBAAgB,eAAe,CAAC,KAAK,EAAE,YAAY,EAAE,OAAO,EAAE,sBAAsB,GAAG,MAAM,EAAE,CAa9F"}
1
+ {"version":3,"file":"inspect.d.ts","sourceRoot":"","sources":["../../src/packages/inspect.ts"],"names":[],"mappings":"AAeA,OAAO,KAAK,EACV,gBAAgB,EAChB,YAAY,EAEZ,sBAAsB,EACvB,MAAM,YAAY,CAAC;AAEpB,YAAY,EAAE,gBAAgB,EAAE,MAAM,YAAY,CAAC;AAEnD;;;;GAIG;AACH,wBAAsB,2BAA2B,CAC/C,OAAO,EAAE,sBAAsB,GAC9B,OAAO,CAAC,gBAAgB,CAAC,CAiB3B;AAED,qFAAqF;AACrF,wBAAgB,eAAe,CAAC,KAAK,EAAE,YAAY,EAAE,OAAO,EAAE,sBAAsB,GAAG,MAAM,EAAE,CAQ9F"}
@@ -28,12 +28,7 @@ export async function inspectConversationPackages(options) {
28
28
  /** Sources one scope declares, or an empty list when its settings are unreadable. */
29
29
  export function declaredSources(scope, options) {
30
30
  try {
31
- const settings = scope === "global"
32
- ? loadGlobalSettings()
33
- : resolveConversationSettings({
34
- address: options.address,
35
- conversationDir: options.conversationDir,
36
- });
31
+ const settings = scope === "global" ? loadGlobalSettings() : resolveConversationSettings(options.office);
37
32
  return settings.packages ?? [];
38
33
  }
39
34
  catch {
@@ -61,8 +56,8 @@ async function describe(source, scope, options, shadowedBy) {
61
56
  try {
62
57
  dir = materializeSource(source, {
63
58
  scope,
64
- address: options.address,
65
- stateDir: options.stateDir,
59
+ address: options.office.address,
60
+ stateDir: options.office.workspace.stateDir,
66
61
  mode: "offline",
67
62
  }).dir;
68
63
  }
@@ -1 +1 @@
1
- {"version":3,"file":"inspect.js","sourceRoot":"","sources":["../../src/packages/inspect.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AACH,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AACjC,OAAO,EAAE,uBAAuB,EAAE,iBAAiB,EAAE,iBAAiB,EAAE,MAAM,qBAA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,CAAC,EAAE,CAAC;QACvD,UAAU,EAAE,MAAM,qBAAqB,CAAC,GAAG,CAAC;QAC5C,MAAM,EAAE,iBAAiB,CAAC,GAAG,CAAC;KAC/B,CAAC;AACJ,CAAC;AAED;;;;;GAKG;AACH,KAAK,UAAU,qBAAqB,CAAC,GAAW;IAC9C,MAAM,UAAU,GAAG,uBAAuB,CAAC,CAAC,IAAI,CAAC,GAAG,EAAE,YAAY,CAAC,CAAC,CAAC,CAAC;IACtE,IAAI,UAAU,CAAC,MAAM,GAAG,CAAC;QAAE,OAAO,UAAU,CAAC,GAAG,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;IACtE,6EAA6E;IAC7E,iDAAiD;IACjD,MAAM,SAAS,GAAG,MAAM,iBAAiB,CAAC,GAAG,CAAC,CAAC;IAC/C,OAAO,SAAS,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC;AAC9C,CAAC;AAED,SAAS,iBAAiB,CAAC,GAAW;IACpC,MAAM,SAAS,GAAG,IAAI,CAAC,GAAG,EAAE,QAAQ,CAAC,CAAC;IACtC,OAAO,iBAAiB,CAAC,EAAE,GAAG,EAAE,SAAS,EAAE,MAAM,EAAE,SAAS,EAAE,CAAC,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC;AACpG,CAAC;AAED,SAAS,SAAS,CAAC,GAAY;IAC7B,OAAO,GAAG,YAAY,KAAK,CAAC,CAAC,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC;AAC1D,CAAC","sourcesContent":["/**\n * The administrator's view of a conversation's packages: what each scope\n * declares, whether it is actually on disk, and what it contributes.\n *\n * Resolution answers \"what loads\"; inspection answers \"why is this not\n * loading\", which is the question someone staring at the portal has. A source\n * that failed to fetch, or one shadowed by the conversation's own copy, is\n * absent from the resolved set — reporting only the survivors would leave the\n * admin with a silently short list and nothing to act on.\n */\nimport { join } from \"node:path\";\nimport { listInstalledExtensions, loadSkillsFromDir, validateExtension } from \"../harness/index.js\";\nimport { loadGlobalSettings, resolveConversationSettings } from \"../config.js\";\nimport { parseSource, sourceIdentity } from \"./source.js\";\nimport { materializeSource } from \"./materialize.js\";\nimport type {\n PackageInventory,\n PackageScope,\n PackageStatus,\n ResolvePackagesOptions,\n} from \"./types.js\";\n\nexport type { PackageInventory } from \"./types.js\";\n\n/**\n * Inventory both scopes for one conversation. Never throws and never fetches:\n * the portal renders this on page load, so it reports the current on-disk\n * truth rather than going to the network behind the admin's back.\n */\nexport async function inspectConversationPackages(\n options: ResolvePackagesOptions,\n): Promise<PackageInventory> {\n const conversationIdentities = new Set(\n declaredSources(\"conversation\", options).map(safeIdentity).filter(Boolean),\n );\n\n return {\n global: await Promise.all(\n declaredSources(\"global\", options).map((source) =>\n describe(source, \"global\", options, conversationIdentities),\n ),\n ),\n conversation: await Promise.all(\n declaredSources(\"conversation\", options).map((source) =>\n describe(source, \"conversation\", options, new Set()),\n ),\n ),\n };\n}\n\n/** Sources one scope declares, or an empty list when its settings are unreadable. */\nexport function declaredSources(scope: PackageScope, options: ResolvePackagesOptions): string[] {\n try {\n const settings =\n scope === \"global\"\n ? loadGlobalSettings()\n : resolveConversationSettings({\n address: options.address,\n conversationDir: options.conversationDir,\n });\n return settings.packages ?? [];\n } catch {\n return [];\n }\n}\n\nfunction safeIdentity(source: string): string {\n try {\n return sourceIdentity(parseSource(source));\n } catch {\n return \"\";\n }\n}\n\nasync function describe(\n source: string,\n scope: PackageScope,\n options: ResolvePackagesOptions,\n shadowedBy: Set<string>,\n): Promise<PackageStatus> {\n const base: PackageStatus = { source, scope, ready: false, extensions: [], skills: [] };\n\n let identity: string;\n try {\n identity = sourceIdentity(parseSource(source));\n } catch (err) {\n return { ...base, error: messageOf(err) };\n }\n\n let dir: string;\n try {\n dir = materializeSource(source, {\n scope,\n address: options.address,\n stateDir: options.stateDir,\n mode: \"offline\",\n }).dir;\n } catch (err) {\n return { ...base, error: messageOf(err) };\n }\n\n return {\n ...base,\n ready: true,\n dir,\n ...(shadowedBy.has(identity) ? { shadowed: true } : {}),\n extensions: await contributedExtensions(dir),\n skills: contributedSkills(dir),\n };\n}\n\n/**\n * Mirrors the loader's two accepted layouts (an `extensions/` collection, or a\n * package that is itself one extension) so the portal reports exactly what\n * would activate — including the slug, which is the name the extension's data\n * dir, secrets, and schedules are keyed by.\n */\nasync function contributedExtensions(dir: string): Promise<string[]> {\n const collection = listInstalledExtensions([join(dir, \"extensions\")]);\n if (collection.length > 0) return collection.map((info) => info.slug);\n // Single-extension layout: validate the root itself rather than scanning its\n // parent, which would report unrelated siblings.\n const validated = await validateExtension(dir);\n return validated.ok ? [validated.slug] : [];\n}\n\nfunction contributedSkills(dir: string): string[] {\n const skillsDir = join(dir, \"skills\");\n return loadSkillsFromDir({ dir: skillsDir, source: \"package\" }).skills.map((skill) => skill.name);\n}\n\nfunction messageOf(err: unknown): string {\n return err instanceof Error ? err.message : String(err);\n}\n"]}
1
+ {"version":3,"file":"inspect.js","sourceRoot":"","sources":["../../src/packages/inspect.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AACH,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AACjC,OAAO,EAAE,uBAAuB,EAAE,iBAAiB,EAAE,iBAAiB,EAAE,MAAM,qBAAqB,CAAC;AACpG,OAAO,EAAE,kBAAkB,EAAE,2BAA2B,EAAE,MAAM,cAAc,CAAC;AAC/E,OAAO,EAAE,WAAW,EAAE,cAAc,EAAE,MAAM,aAAa,CAAC;AAC1D,OAAO,EAAE,iBAAiB,EAAE,MAAM,kBAAkB,CAAC;AAUrD;;;;GAIG;AACH,MAAM,CAAC,KAAK,UAAU,2BAA2B,CAC/C,OAA+B;IAE/B,MAAM,sBAAsB,GAAG,IAAI,GAAG,CACpC,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,CAAC;QAAE,OAAO,UAAU,CAAC,GAAG,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;IACtE,6EAA6E;IAC7E,iDAAiD;IACjD,MAAM,SAAS,GAAG,MAAM,iBAAiB,CAAC,GAAG,CAAC,CAAC;IAC/C,OAAO,SAAS,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC;AAC9C,CAAC;AAED,SAAS,iBAAiB,CAAC,GAAW;IACpC,MAAM,SAAS,GAAG,IAAI,CAAC,GAAG,EAAE,QAAQ,CAAC,CAAC;IACtC,OAAO,iBAAiB,CAAC,EAAE,GAAG,EAAE,SAAS,EAAE,MAAM,EAAE,SAAS,EAAE,CAAC,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC;AACpG,CAAC;AAED,SAAS,SAAS,CAAC,GAAY;IAC7B,OAAO,GAAG,YAAY,KAAK,CAAC,CAAC,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC;AAC1D,CAAC","sourcesContent":["/**\n * The administrator's view of a conversation's packages: what each scope\n * declares, whether it is actually on disk, and what it contributes.\n *\n * Resolution answers \"what loads\"; inspection answers \"why is this not\n * loading\", which is the question someone staring at the portal has. A source\n * that failed to fetch, or one shadowed by the conversation's own copy, is\n * absent from the resolved set — reporting only the survivors would leave the\n * admin with a silently short list and nothing to act on.\n */\nimport { join } from \"node:path\";\nimport { listInstalledExtensions, loadSkillsFromDir, validateExtension } from \"../harness/index.js\";\nimport { loadGlobalSettings, resolveConversationSettings } from \"../config.js\";\nimport { parseSource, sourceIdentity } from \"./source.js\";\nimport { materializeSource } from \"./materialize.js\";\nimport type {\n PackageInventory,\n PackageScope,\n PackageStatus,\n ResolvePackagesOptions,\n} from \"./types.js\";\n\nexport type { PackageInventory } from \"./types.js\";\n\n/**\n * Inventory both scopes for one conversation. Never throws and never fetches:\n * the portal renders this on page load, so it reports the current on-disk\n * truth rather than going to the network behind the admin's back.\n */\nexport async function inspectConversationPackages(\n options: ResolvePackagesOptions,\n): Promise<PackageInventory> {\n const conversationIdentities = new Set(\n declaredSources(\"conversation\", options).map(safeIdentity).filter(Boolean),\n );\n\n return {\n global: await Promise.all(\n declaredSources(\"global\", options).map((source) =>\n describe(source, \"global\", options, conversationIdentities),\n ),\n ),\n conversation: await Promise.all(\n declaredSources(\"conversation\", options).map((source) =>\n describe(source, \"conversation\", options, new Set()),\n ),\n ),\n };\n}\n\n/** Sources one scope declares, or an empty list when its settings are unreadable. */\nexport function declaredSources(scope: PackageScope, options: ResolvePackagesOptions): string[] {\n try {\n const settings =\n scope === \"global\" ? loadGlobalSettings() : resolveConversationSettings(options.office);\n return settings.packages ?? [];\n } catch {\n return [];\n }\n}\n\nfunction safeIdentity(source: string): string {\n try {\n return sourceIdentity(parseSource(source));\n } catch {\n return \"\";\n }\n}\n\nasync function describe(\n source: string,\n scope: PackageScope,\n options: ResolvePackagesOptions,\n shadowedBy: Set<string>,\n): Promise<PackageStatus> {\n const base: PackageStatus = { source, scope, ready: false, extensions: [], skills: [] };\n\n let identity: string;\n try {\n identity = sourceIdentity(parseSource(source));\n } catch (err) {\n return { ...base, error: messageOf(err) };\n }\n\n let dir: string;\n try {\n dir = materializeSource(source, {\n scope,\n address: options.office.address,\n stateDir: options.office.workspace.stateDir,\n mode: \"offline\",\n }).dir;\n } catch (err) {\n return { ...base, error: messageOf(err) };\n }\n\n return {\n ...base,\n ready: true,\n dir,\n ...(shadowedBy.has(identity) ? { shadowed: true } : {}),\n extensions: await contributedExtensions(dir),\n skills: contributedSkills(dir),\n };\n}\n\n/**\n * Mirrors the loader's two accepted layouts (an `extensions/` collection, or a\n * package that is itself one extension) so the portal reports exactly what\n * would activate — including the slug, which is the name the extension's data\n * dir, secrets, and schedules are keyed by.\n */\nasync function contributedExtensions(dir: string): Promise<string[]> {\n const collection = listInstalledExtensions([join(dir, \"extensions\")]);\n if (collection.length > 0) return collection.map((info) => info.slug);\n // Single-extension layout: validate the root itself rather than scanning its\n // parent, which would report unrelated siblings.\n const validated = await validateExtension(dir);\n return validated.ok ? [validated.slug] : [];\n}\n\nfunction contributedSkills(dir: string): string[] {\n const skillsDir = join(dir, \"skills\");\n return loadSkillsFromDir({ dir: skillsDir, source: \"package\" }).skills.map((skill) => skill.name);\n}\n\nfunction messageOf(err: unknown): string {\n return err instanceof Error ? err.message : String(err);\n}\n"]}
@@ -18,7 +18,7 @@ import { dirname, join } from "node:path";
18
18
  import { ensureDirExists, readTextFileIfExists } from "../utils/file-guards.js";
19
19
  import * as log from "../log.js";
20
20
  import { gitRepoPath, parseSource, sourceIdentity } from "./source.js";
21
- import { officeStateDir } from "../office-address.js";
21
+ import { officeStateDir } from "../office/index.js";
22
22
  /** Git operations get a bounded wall clock so a hung remote cannot wedge a save. */
23
23
  const GIT_TIMEOUT_MS = 120_000;
24
24
  const NPM_TIMEOUT_MS = 300_000;
@@ -1 +1 @@
1
- {"version":3,"file":"materialize.js","sourceRoot":"","sources":["../../src/packages/materialize.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AACH,OAAO,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAC;AAClD,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACzC,OAAO,EAAE,MAAM,EAAE,UAAU,EAAE,MAAM,EAAE,QAAQ,EAAE,aAAa,EAAE,MAAM,SAAS,CAAC;AAC9E,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AAC1C,OAAO,EAAE,eAAe,EAAE,oBAAoB,EAAE,MAAM,yBAAyB,CAAC;AAChF,OAAO,KAAK,GAAG,MAAM,WAAW,CAAC;AACjC,OAAO,EAAE,WAAW,EAAE,WAAW,EAAE,cAAc,EAAE,MAAM,aAAa,CAAC;AACvE,OA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;QAC/B,GAAG;QACH,OAAO,EAAE,cAAc;QACvB,QAAQ,EAAE,OAAO;QACjB,KAAK,EAAE,CAAC,QAAQ,EAAE,MAAM,EAAE,MAAM,CAAC;QACjC,GAAG,EAAE;YACH,GAAG,OAAO,CAAC,GAAG;YACd,iEAAiE;YACjE,mBAAmB,EAAE,GAAG;YACxB,eAAe,EAAE,OAAO,CAAC,GAAG,CAAC,eAAe,IAAI,2CAA2C;SAC5F;KACF,CAAC,CAAC;AACL,CAAC;AAED,SAAS,WAAW,CAAC,MAA8C;IACjE,OAAO,MAAM,CAAC,GAAG,CAAC,CAAC,CAAC,GAAG,MAAM,CAAC,GAAG,OAAO,MAAM,CAAC,GAAG,EAAE,CAAC,CAAC,CAAC,MAAM,CAAC,GAAG,CAAC;AACpE,CAAC;AAED,qEAAqE;AACrE,SAAS,YAAY,CAAC,GAAY;IAChC,IAAI,GAAG,IAAI,OAAO,GAAG,KAAK,QAAQ,IAAI,QAAQ,IAAI,GAAG,EAAE,CAAC;QACtD,MAAM,MAAM,GAAI,GAA4B,CAAC,MAAM,CAAC;QACpD,MAAM,IAAI,GAAG,OAAO,MAAM,KAAK,QAAQ,CAAC,CAAC,CAAC,MAAM,CAAC,IAAI,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;QAC7D,IAAI,IAAI;YAAE,OAAO,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;IACxD,CAAC;IACD,OAAO,GAAG,YAAY,KAAK,CAAC,CAAC,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC;AAC1D,CAAC","sourcesContent":["/**\n * Turning a parsed source into a directory on the host.\n *\n * Materialization is an explicit, reported step — it happens when a human adds\n * or updates a package, not lazily while a conversation is waiting for a\n * reply. Failures (bad URL, missing ref, no such subpath) therefore surface in\n * front of the person who typed the source instead of as a silently absent\n * feature in a chat.\n *\n * Everything lands under the host-only state dir, never the workspace: this\n * code is imported into the mikan process, so a mounted location would let\n * sandboxed code write what the host executes.\n */\nimport { execFileSync } from \"node:child_process\";\nimport { createHash } from \"node:crypto\";\nimport { cpSync, existsSync, rmSync, statSync, writeFileSync } from \"node:fs\";\nimport { dirname, join } from \"node:path\";\nimport { ensureDirExists, readTextFileIfExists } from \"../utils/file-guards.js\";\nimport * as log from \"../log.js\";\nimport { gitRepoPath, parseSource, sourceIdentity } from \"./source.js\";\nimport { officeStateDir } from \"../office-address.js\";\nimport type { OfficeAddress } from \"../types.js\";\nimport type {\n MaterializeMode,\n MaterializeOptions,\n MaterializedPackage,\n PackageScope,\n PackageSourceString,\n ParsedSource,\n} from \"./types.js\";\n\nexport type { MaterializeOptions } from \"./types.js\";\n\n/** Git operations get a bounded wall clock so a hung remote cannot wedge a save. */\nconst GIT_TIMEOUT_MS = 120_000;\nconst NPM_TIMEOUT_MS = 300_000;\nconst MATERIALIZED_REF_FILE = \"mikan-ref\";\n\n/**\n * How far materialization may go to produce the package's files.\n *\n * - `offline`: use what is already on disk; never touch the network. This is\n * what a conversation load uses, so no chat reply can ever wait on a remote.\n * - `fetch`: clone a package that is not on disk yet, reuse an existing clone\n * when it already has the requested ref, or switch it to a new ref. What the\n * portal uses when a source is added.\n * - `refresh`: additionally re-fetch an existing clone, resetting and cleaning\n * it first. What the portal's Update action uses.\n *\n * One mode rather than two booleans: \"re-fetch an existing clone but refuse to\n * create a missing one\" is not a state any caller wants, and expressing it\n * should not be possible.\n */\n/**\n * Root of a scope's host-only assets: `<stateDir>/global` or\n * `<stateDir>/conversations/<id>`. The two are isomorphic by design — both\n * hold `extensions/`, `extension-data/`, and now `git/`. See\n * `src/harness/extensions/LAYOUT.md`.\n */\nexport function packageScopeDir(\n scope: PackageScope,\n address: OfficeAddress | undefined,\n stateDir: string,\n): string {\n if (scope === \"global\") return join(stateDir, \"global\");\n if (!address) throw new Error(\"A conversation-scoped package needs an office address\");\n return officeStateDir(stateDir, address);\n}\n\n/**\n * Where a git checkout lives.\n *\n * The unpinned checkout keeps the original path for compatibility. Explicit\n * refs get a sibling keyed by the ref, so two refs can never reset each\n * other's working tree; subpaths of one ref therefore still share a checkout.\n */\nexport function gitCloneDir(url: string, scopeDir: string, ref?: string): string {\n const repoPath = gitRepoPath(url).split(\"/\");\n const repoName = repoPath[repoPath.length - 1];\n const parent = repoPath.slice(0, -1);\n const checkoutName =\n ref === undefined || ref === \"HEAD\"\n ? repoName\n : `${repoName}.mikan-${createHash(\"sha256\").update(ref).digest(\"hex\")}`;\n return join(scopeDir, \"git\", ...parent, checkoutName);\n}\n\n/**\n * Materialize one source and return where its files ended up. Throws with a\n * message meant to be shown to a human — callers render it next to the input\n * that produced it.\n */\nexport function materializeSource(\n source: PackageSourceString,\n options: MaterializeOptions,\n): MaterializedPackage {\n const parsed = parseSource(source);\n const scopeDir = packageScopeDir(options.scope, options.address, options.stateDir);\n const dir =\n parsed.type === \"local\"\n ? materializeLocal(parsed)\n : materializeGit(parsed, scopeDir, options.mode ?? \"fetch\");\n\n return {\n source,\n parsed,\n identity: sourceIdentity(parsed),\n dir,\n scope: options.scope,\n };\n}\n\nfunction materializeLocal(parsed: Extract<ParsedSource, { type: \"local\" }>): string {\n if (!existsSync(parsed.path)) {\n throw new Error(`Path does not exist on the mikan host: ${parsed.path}`);\n }\n if (!statSync(parsed.path).isDirectory()) {\n throw new Error(`Package path must be a directory: ${parsed.path}`);\n }\n return parsed.path;\n}\n\nfunction materializeGit(\n parsed: Extract<ParsedSource, { type: \"git\" }>,\n scopeDir: string,\n mode: MaterializeMode,\n): string {\n const requestedRef = parsed.ref ?? \"HEAD\";\n const cloneDir = gitCloneDir(parsed.url, scopeDir, requestedRef);\n migrateLegacyCheckout(parsed.url, scopeDir, cloneDir, requestedRef);\n const alreadyCloned = existsSync(join(cloneDir, \".git\"));\n const markerPath = join(cloneDir, \".git\", MATERIALIZED_REF_FILE);\n const recordedRef = alreadyCloned ? readTextFileIfExists(markerPath)?.trim() : undefined;\n const canReuse =\n alreadyCloned &&\n mode !== \"refresh\" &&\n (recordedRef === requestedRef ||\n (mode === \"offline\" &&\n recordedRef === undefined &&\n markerlessCheckoutMatchesRef(cloneDir, requestedRef)));\n\n if (canReuse) {\n return resolveSubpath(cloneDir, parsed);\n }\n if (mode === \"offline\") {\n throw new Error(`Not fetched on this host yet: ${describeRef(parsed)}`);\n }\n\n // An incomplete checkout must not retain a marker from an earlier attempt:\n // otherwise a retry could mistake a failed dependency install for success.\n if (alreadyCloned) rmSync(markerPath, { force: true });\n\n if (!alreadyCloned) {\n // A leftover directory without .git means a previous attempt died partway.\n if (existsSync(cloneDir)) rmSync(cloneDir, { recursive: true, force: true });\n ensureDirExists(cloneDir);\n git(cloneDir, [\"init\", \"-q\"]);\n git(cloneDir, [\"remote\", \"add\", \"origin\", parsed.url]);\n } else {\n // Reconcile: drop anything a previous checkout left behind so the new ref\n // lands on a clean tree.\n git(cloneDir, [\"remote\", \"set-url\", \"origin\", parsed.url]);\n git(cloneDir, [\"reset\", \"--hard\", \"-q\"]);\n git(cloneDir, [\"clean\", \"-qfd\"]);\n }\n\n // One fetch shape for every kind of ref — tag, branch, or commit sha — and\n // `HEAD` for \"whatever the remote's default branch is now\".\n try {\n git(cloneDir, [\"fetch\", \"--depth\", \"1\", \"origin\", requestedRef]);\n } catch (err) {\n if (!alreadyCloned) rmSync(cloneDir, { recursive: true, force: true });\n throw new Error(`Could not fetch ${describeRef(parsed)}: ${gitErrorText(err)}`, { cause: err });\n }\n git(cloneDir, [\"checkout\", \"-q\", \"--detach\", \"FETCH_HEAD\"]);\n\n const dir = resolveSubpath(cloneDir, parsed);\n installDependencies(dir);\n // This is the completion marker, not merely a fetched-ref marker. Write it\n // last so a failed npm install is retried by the next materialization.\n writeFileSync(markerPath, `${requestedRef}\\n`);\n return dir;\n}\n\n/**\n * Before keyed checkout paths existed, every ref used the legacy repo path.\n * Copy a matching complete checkout on first use of its keyed path so offline\n * loads keep working. Markerless legacy checkouts are accepted only when git\n * can prove the requested ref is the checked-out commit; a different or\n * unprovable pinned ref is rebuilt by fetch/refresh instead.\n */\nfunction migrateLegacyCheckout(\n url: string,\n scopeDir: string,\n cloneDir: string,\n requestedRef: string,\n): void {\n const legacyDir = gitCloneDir(url, scopeDir);\n if (cloneDir === legacyDir || existsSync(cloneDir)) return;\n const legacyMarker = join(legacyDir, \".git\", MATERIALIZED_REF_FILE);\n if (!existsSync(join(legacyDir, \".git\"))) return;\n const recordedRef = readTextFileIfExists(legacyMarker)?.trim();\n if (recordedRef !== requestedRef) {\n if (recordedRef !== undefined || !markerlessCheckoutMatchesRef(legacyDir, requestedRef)) {\n return;\n }\n }\n\n ensureDirExists(dirname(cloneDir));\n cpSync(legacyDir, cloneDir, { recursive: true });\n}\n\n/**\n * Legacy checkouts have no completion marker. Accept them offline only when\n * the checkout is clean and the local git metadata identifies the requested\n * commit/ref; never infer a pinned ref from HEAD alone.\n */\nfunction markerlessCheckoutMatchesRef(cloneDir: string, requestedRef: string): boolean {\n let head: string;\n try {\n head = git(cloneDir, [\"rev-parse\", \"--verify\", \"HEAD\"]).trim();\n if (!head || git(cloneDir, [\"status\", \"--porcelain\", \"--untracked-files=no\"]).trim()) {\n return false;\n }\n } catch {\n return false;\n }\n\n if (requestedRef === \"HEAD\") return true;\n\n try {\n if (git(cloneDir, [\"rev-parse\", \"--verify\", `${requestedRef}^{commit}`]).trim() === head) {\n return true;\n }\n } catch {\n // A shallow legacy fetch may retain only FETCH_HEAD, not a local ref.\n }\n\n try {\n if (git(cloneDir, [\"symbolic-ref\", \"--quiet\", \"--short\", \"HEAD\"]).trim() === requestedRef) {\n return true;\n }\n } catch {\n // Detached checkouts do not have a symbolic branch.\n }\n\n const fetchHead = readTextFileIfExists(join(cloneDir, \".git\", \"FETCH_HEAD\"));\n if (!fetchHead) return false;\n return fetchHead.split(\"\\n\").some((line) => {\n const match = /^(\\w+)\\s+.*(?:branch|tag) '([^']+)'/.exec(line);\n return match?.[1] === head && match[2] === requestedRef;\n });\n}\n\nfunction resolveSubpath(cloneDir: string, parsed: Extract<ParsedSource, { type: \"git\" }>): string {\n if (!parsed.subpath) return cloneDir;\n const dir = join(cloneDir, parsed.subpath);\n if (!existsSync(dir)) {\n throw new Error(`Subpath not found in repository: ${parsed.subpath}`);\n }\n return dir;\n}\n\n/**\n * Install runtime dependencies when the package declares any. This runs npm\n * on the host against code that was just fetched from a remote, which is the\n * same trust level as importing the package itself — but it is worth being\n * explicit that it happens, because it also runs the dependencies' install\n * scripts.\n */\nfunction installDependencies(dir: string): void {\n if (!hasDependencies(dir)) return;\n log.logInfo(`Installing package dependencies in ${dir}`);\n try {\n execFileSync(\"npm\", [\"install\", \"--omit=dev\", \"--no-audit\", \"--no-fund\"], {\n cwd: dir,\n timeout: NPM_TIMEOUT_MS,\n encoding: \"utf-8\",\n stdio: [\"ignore\", \"pipe\", \"pipe\"],\n });\n } catch (err) {\n throw new Error(`npm install failed for the package: ${gitErrorText(err)}`, { cause: err });\n }\n}\n\nfunction hasDependencies(dir: string): boolean {\n const raw = readTextFileIfExists(join(dir, \"package.json\"));\n if (raw === undefined) return false;\n try {\n const pkg = JSON.parse(raw) as { dependencies?: Record<string, string> };\n return Boolean(pkg.dependencies && Object.keys(pkg.dependencies).length > 0);\n } catch {\n return false;\n }\n}\n\nfunction git(cwd: string, args: string[]): string {\n return execFileSync(\"git\", args, {\n cwd,\n timeout: GIT_TIMEOUT_MS,\n encoding: \"utf-8\",\n stdio: [\"ignore\", \"pipe\", \"pipe\"],\n env: {\n ...process.env,\n // Never block a portal save on an interactive credential prompt.\n GIT_TERMINAL_PROMPT: \"0\",\n GIT_SSH_COMMAND: process.env.GIT_SSH_COMMAND ?? \"ssh -o BatchMode=yes -o ConnectTimeout=10\",\n },\n });\n}\n\nfunction describeRef(parsed: Extract<ParsedSource, { type: \"git\" }>): string {\n return parsed.ref ? `${parsed.url} at ${parsed.ref}` : parsed.url;\n}\n\n/** Prefer git's stderr over the generic \"Command failed\" wrapper. */\nfunction gitErrorText(err: unknown): string {\n if (err && typeof err === \"object\" && \"stderr\" in err) {\n const stderr = (err as { stderr?: unknown }).stderr;\n const text = typeof stderr === \"string\" ? stderr.trim() : \"\";\n if (text) return text.split(\"\\n\").slice(-3).join(\" \");\n }\n return err instanceof Error ? err.message : String(err);\n}\n"]}
1
+ {"version":3,"file":"materialize.js","sourceRoot":"","sources":["../../src/packages/materialize.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AACH,OAAO,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAC;AAClD,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACzC,OAAO,EAAE,MAAM,EAAE,UAAU,EAAE,MAAM,EAAE,QAAQ,EAAE,aAAa,EAAE,MAAM,SAAS,CAAC;AAC9E,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AAC1C,OAAO,EAAE,eAAe,EAAE,oBAAoB,EAAE,MAAM,yBAAyB,CAAC;AAChF,OAAO,KAAK,GAAG,MAAM,WAAW,CAAC;AACjC,OAAO,EAAE,WAAW,EAAE,WAAW,EAAE,cAAc,EAAE,MAAM,aAAa,CAAC;AACvE,OAAO,EAAE,cAAc,EAAE,MAAM,oBAAoB,CAAC;AAapD,oFAAoF;AACpF,MAAM,cAAc,GAAG,OAAO,CAAC;AAC/B,MAAM,cAAc,GAAG,OAAO,CAAC;AAC/B,MAAM,qBAAqB,GAAG,WAAW,CAAC;AAE1C;;;;;;;;;;;;;;GAcG;AACH;;;;;GAKG;AACH,MAAM,UAAU,eAAe,CAC7B,KAAmB,EACnB,OAAkC,EAClC,QAAgB;IAEhB,IAAI,KAAK,KAAK,QAAQ;QAAE,OAAO,IAAI,CAAC,QAAQ,EAAE,QAAQ,CAAC,CAAC;IACxD,IAAI,CAAC,OAAO;QAAE,MAAM,IAAI,KAAK,CAAC,uDAAuD,CAAC,CAAC;IACvF,OAAO,cAAc,C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AM,CAAC,GAAG,CAAC;AACpE,CAAC;AAED,qEAAqE;AACrE,SAAS,YAAY,CAAC,GAAY;IAChC,IAAI,GAAG,IAAI,OAAO,GAAG,KAAK,QAAQ,IAAI,QAAQ,IAAI,GAAG,EAAE,CAAC;QACtD,MAAM,MAAM,GAAI,GAA4B,CAAC,MAAM,CAAC;QACpD,MAAM,IAAI,GAAG,OAAO,MAAM,KAAK,QAAQ,CAAC,CAAC,CAAC,MAAM,CAAC,IAAI,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;QAC7D,IAAI,IAAI;YAAE,OAAO,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;IACxD,CAAC;IACD,OAAO,GAAG,YAAY,KAAK,CAAC,CAAC,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC;AAC1D,CAAC","sourcesContent":["/**\n * Turning a parsed source into a directory on the host.\n *\n * Materialization is an explicit, reported step — it happens when a human adds\n * or updates a package, not lazily while a conversation is waiting for a\n * reply. Failures (bad URL, missing ref, no such subpath) therefore surface in\n * front of the person who typed the source instead of as a silently absent\n * feature in a chat.\n *\n * Everything lands under the host-only state dir, never the workspace: this\n * code is imported into the mikan process, so a mounted location would let\n * sandboxed code write what the host executes.\n */\nimport { execFileSync } from \"node:child_process\";\nimport { createHash } from \"node:crypto\";\nimport { cpSync, existsSync, rmSync, statSync, writeFileSync } from \"node:fs\";\nimport { dirname, join } from \"node:path\";\nimport { ensureDirExists, readTextFileIfExists } from \"../utils/file-guards.js\";\nimport * as log from \"../log.js\";\nimport { gitRepoPath, parseSource, sourceIdentity } from \"./source.js\";\nimport { officeStateDir } from \"../office/index.js\";\nimport type { OfficeAddress } from \"../types.js\";\nimport type {\n MaterializeMode,\n MaterializeOptions,\n MaterializedPackage,\n PackageScope,\n PackageSourceString,\n ParsedSource,\n} from \"./types.js\";\n\nexport type { MaterializeOptions } from \"./types.js\";\n\n/** Git operations get a bounded wall clock so a hung remote cannot wedge a save. */\nconst GIT_TIMEOUT_MS = 120_000;\nconst NPM_TIMEOUT_MS = 300_000;\nconst MATERIALIZED_REF_FILE = \"mikan-ref\";\n\n/**\n * How far materialization may go to produce the package's files.\n *\n * - `offline`: use what is already on disk; never touch the network. This is\n * what a conversation load uses, so no chat reply can ever wait on a remote.\n * - `fetch`: clone a package that is not on disk yet, reuse an existing clone\n * when it already has the requested ref, or switch it to a new ref. What the\n * portal uses when a source is added.\n * - `refresh`: additionally re-fetch an existing clone, resetting and cleaning\n * it first. What the portal's Update action uses.\n *\n * One mode rather than two booleans: \"re-fetch an existing clone but refuse to\n * create a missing one\" is not a state any caller wants, and expressing it\n * should not be possible.\n */\n/**\n * Root of a scope's host-only assets: `<stateDir>/global` or\n * `<stateDir>/conversations/<id>`. The two are isomorphic by design — both\n * hold `extensions/`, `extension-data/`, and now `git/`. See\n * `src/harness/extensions/LAYOUT.md`.\n */\nexport function packageScopeDir(\n scope: PackageScope,\n address: OfficeAddress | undefined,\n stateDir: string,\n): string {\n if (scope === \"global\") return join(stateDir, \"global\");\n if (!address) throw new Error(\"A conversation-scoped package needs an office address\");\n return officeStateDir(stateDir, address);\n}\n\n/**\n * Where a git checkout lives.\n *\n * The unpinned checkout keeps the original path for compatibility. Explicit\n * refs get a sibling keyed by the ref, so two refs can never reset each\n * other's working tree; subpaths of one ref therefore still share a checkout.\n */\nexport function gitCloneDir(url: string, scopeDir: string, ref?: string): string {\n const repoPath = gitRepoPath(url).split(\"/\");\n const repoName = repoPath[repoPath.length - 1];\n const parent = repoPath.slice(0, -1);\n const checkoutName =\n ref === undefined || ref === \"HEAD\"\n ? repoName\n : `${repoName}.mikan-${createHash(\"sha256\").update(ref).digest(\"hex\")}`;\n return join(scopeDir, \"git\", ...parent, checkoutName);\n}\n\n/**\n * Materialize one source and return where its files ended up. Throws with a\n * message meant to be shown to a human — callers render it next to the input\n * that produced it.\n */\nexport function materializeSource(\n source: PackageSourceString,\n options: MaterializeOptions,\n): MaterializedPackage {\n const parsed = parseSource(source);\n const scopeDir = packageScopeDir(options.scope, options.address, options.stateDir);\n const dir =\n parsed.type === \"local\"\n ? materializeLocal(parsed)\n : materializeGit(parsed, scopeDir, options.mode ?? \"fetch\");\n\n return {\n source,\n parsed,\n identity: sourceIdentity(parsed),\n dir,\n scope: options.scope,\n };\n}\n\nfunction materializeLocal(parsed: Extract<ParsedSource, { type: \"local\" }>): string {\n if (!existsSync(parsed.path)) {\n throw new Error(`Path does not exist on the mikan host: ${parsed.path}`);\n }\n if (!statSync(parsed.path).isDirectory()) {\n throw new Error(`Package path must be a directory: ${parsed.path}`);\n }\n return parsed.path;\n}\n\nfunction materializeGit(\n parsed: Extract<ParsedSource, { type: \"git\" }>,\n scopeDir: string,\n mode: MaterializeMode,\n): string {\n const requestedRef = parsed.ref ?? \"HEAD\";\n const cloneDir = gitCloneDir(parsed.url, scopeDir, requestedRef);\n migrateLegacyCheckout(parsed.url, scopeDir, cloneDir, requestedRef);\n const alreadyCloned = existsSync(join(cloneDir, \".git\"));\n const markerPath = join(cloneDir, \".git\", MATERIALIZED_REF_FILE);\n const recordedRef = alreadyCloned ? readTextFileIfExists(markerPath)?.trim() : undefined;\n const canReuse =\n alreadyCloned &&\n mode !== \"refresh\" &&\n (recordedRef === requestedRef ||\n (mode === \"offline\" &&\n recordedRef === undefined &&\n markerlessCheckoutMatchesRef(cloneDir, requestedRef)));\n\n if (canReuse) {\n return resolveSubpath(cloneDir, parsed);\n }\n if (mode === \"offline\") {\n throw new Error(`Not fetched on this host yet: ${describeRef(parsed)}`);\n }\n\n // An incomplete checkout must not retain a marker from an earlier attempt:\n // otherwise a retry could mistake a failed dependency install for success.\n if (alreadyCloned) rmSync(markerPath, { force: true });\n\n if (!alreadyCloned) {\n // A leftover directory without .git means a previous attempt died partway.\n if (existsSync(cloneDir)) rmSync(cloneDir, { recursive: true, force: true });\n ensureDirExists(cloneDir);\n git(cloneDir, [\"init\", \"-q\"]);\n git(cloneDir, [\"remote\", \"add\", \"origin\", parsed.url]);\n } else {\n // Reconcile: drop anything a previous checkout left behind so the new ref\n // lands on a clean tree.\n git(cloneDir, [\"remote\", \"set-url\", \"origin\", parsed.url]);\n git(cloneDir, [\"reset\", \"--hard\", \"-q\"]);\n git(cloneDir, [\"clean\", \"-qfd\"]);\n }\n\n // One fetch shape for every kind of ref — tag, branch, or commit sha — and\n // `HEAD` for \"whatever the remote's default branch is now\".\n try {\n git(cloneDir, [\"fetch\", \"--depth\", \"1\", \"origin\", requestedRef]);\n } catch (err) {\n if (!alreadyCloned) rmSync(cloneDir, { recursive: true, force: true });\n throw new Error(`Could not fetch ${describeRef(parsed)}: ${gitErrorText(err)}`, { cause: err });\n }\n git(cloneDir, [\"checkout\", \"-q\", \"--detach\", \"FETCH_HEAD\"]);\n\n const dir = resolveSubpath(cloneDir, parsed);\n installDependencies(dir);\n // This is the completion marker, not merely a fetched-ref marker. Write it\n // last so a failed npm install is retried by the next materialization.\n writeFileSync(markerPath, `${requestedRef}\\n`);\n return dir;\n}\n\n/**\n * Before keyed checkout paths existed, every ref used the legacy repo path.\n * Copy a matching complete checkout on first use of its keyed path so offline\n * loads keep working. Markerless legacy checkouts are accepted only when git\n * can prove the requested ref is the checked-out commit; a different or\n * unprovable pinned ref is rebuilt by fetch/refresh instead.\n */\nfunction migrateLegacyCheckout(\n url: string,\n scopeDir: string,\n cloneDir: string,\n requestedRef: string,\n): void {\n const legacyDir = gitCloneDir(url, scopeDir);\n if (cloneDir === legacyDir || existsSync(cloneDir)) return;\n const legacyMarker = join(legacyDir, \".git\", MATERIALIZED_REF_FILE);\n if (!existsSync(join(legacyDir, \".git\"))) return;\n const recordedRef = readTextFileIfExists(legacyMarker)?.trim();\n if (recordedRef !== requestedRef) {\n if (recordedRef !== undefined || !markerlessCheckoutMatchesRef(legacyDir, requestedRef)) {\n return;\n }\n }\n\n ensureDirExists(dirname(cloneDir));\n cpSync(legacyDir, cloneDir, { recursive: true });\n}\n\n/**\n * Legacy checkouts have no completion marker. Accept them offline only when\n * the checkout is clean and the local git metadata identifies the requested\n * commit/ref; never infer a pinned ref from HEAD alone.\n */\nfunction markerlessCheckoutMatchesRef(cloneDir: string, requestedRef: string): boolean {\n let head: string;\n try {\n head = git(cloneDir, [\"rev-parse\", \"--verify\", \"HEAD\"]).trim();\n if (!head || git(cloneDir, [\"status\", \"--porcelain\", \"--untracked-files=no\"]).trim()) {\n return false;\n }\n } catch {\n return false;\n }\n\n if (requestedRef === \"HEAD\") return true;\n\n try {\n if (git(cloneDir, [\"rev-parse\", \"--verify\", `${requestedRef}^{commit}`]).trim() === head) {\n return true;\n }\n } catch {\n // A shallow legacy fetch may retain only FETCH_HEAD, not a local ref.\n }\n\n try {\n if (git(cloneDir, [\"symbolic-ref\", \"--quiet\", \"--short\", \"HEAD\"]).trim() === requestedRef) {\n return true;\n }\n } catch {\n // Detached checkouts do not have a symbolic branch.\n }\n\n const fetchHead = readTextFileIfExists(join(cloneDir, \".git\", \"FETCH_HEAD\"));\n if (!fetchHead) return false;\n return fetchHead.split(\"\\n\").some((line) => {\n const match = /^(\\w+)\\s+.*(?:branch|tag) '([^']+)'/.exec(line);\n return match?.[1] === head && match[2] === requestedRef;\n });\n}\n\nfunction resolveSubpath(cloneDir: string, parsed: Extract<ParsedSource, { type: \"git\" }>): string {\n if (!parsed.subpath) return cloneDir;\n const dir = join(cloneDir, parsed.subpath);\n if (!existsSync(dir)) {\n throw new Error(`Subpath not found in repository: ${parsed.subpath}`);\n }\n return dir;\n}\n\n/**\n * Install runtime dependencies when the package declares any. This runs npm\n * on the host against code that was just fetched from a remote, which is the\n * same trust level as importing the package itself — but it is worth being\n * explicit that it happens, because it also runs the dependencies' install\n * scripts.\n */\nfunction installDependencies(dir: string): void {\n if (!hasDependencies(dir)) return;\n log.logInfo(`Installing package dependencies in ${dir}`);\n try {\n execFileSync(\"npm\", [\"install\", \"--omit=dev\", \"--no-audit\", \"--no-fund\"], {\n cwd: dir,\n timeout: NPM_TIMEOUT_MS,\n encoding: \"utf-8\",\n stdio: [\"ignore\", \"pipe\", \"pipe\"],\n });\n } catch (err) {\n throw new Error(`npm install failed for the package: ${gitErrorText(err)}`, { cause: err });\n }\n}\n\nfunction hasDependencies(dir: string): boolean {\n const raw = readTextFileIfExists(join(dir, \"package.json\"));\n if (raw === undefined) return false;\n try {\n const pkg = JSON.parse(raw) as { dependencies?: Record<string, string> };\n return Boolean(pkg.dependencies && Object.keys(pkg.dependencies).length > 0);\n } catch {\n return false;\n }\n}\n\nfunction git(cwd: string, args: string[]): string {\n return execFileSync(\"git\", args, {\n cwd,\n timeout: GIT_TIMEOUT_MS,\n encoding: \"utf-8\",\n stdio: [\"ignore\", \"pipe\", \"pipe\"],\n env: {\n ...process.env,\n // Never block a portal save on an interactive credential prompt.\n GIT_TERMINAL_PROMPT: \"0\",\n GIT_SSH_COMMAND: process.env.GIT_SSH_COMMAND ?? \"ssh -o BatchMode=yes -o ConnectTimeout=10\",\n },\n });\n}\n\nfunction describeRef(parsed: Extract<ParsedSource, { type: \"git\" }>): string {\n return parsed.ref ? `${parsed.url} at ${parsed.ref}` : parsed.url;\n}\n\n/** Prefer git's stderr over the generic \"Command failed\" wrapper. */\nfunction gitErrorText(err: unknown): string {\n if (err && typeof err === \"object\" && \"stderr\" in err) {\n const stderr = (err as { stderr?: unknown }).stderr;\n const text = typeof stderr === \"string\" ? stderr.trim() : \"\";\n if (text) return text.split(\"\\n\").slice(-3).join(\" \");\n }\n return err instanceof Error ? err.message : String(err);\n}\n"]}
@@ -110,10 +110,7 @@ function readScope(scope, options) {
110
110
  try {
111
111
  const sources = scope === "global"
112
112
  ? loadGlobalSettings().packages
113
- : resolveConversationSettings({
114
- address: options.address,
115
- conversationDir: options.conversationDir,
116
- }).packages;
113
+ : resolveConversationSettings(options.office).packages;
117
114
  return (sources ?? []).map((source) => ({ source, scope }));
118
115
  }
119
116
  catch (err) {
@@ -127,8 +124,8 @@ function materialize(declaration, options, errors) {
127
124
  try {
128
125
  return materializeSource(declaration.source, {
129
126
  scope: declaration.scope,
130
- address: options.address,
131
- stateDir: options.stateDir,
127
+ address: options.office.address,
128
+ stateDir: options.office.workspace.stateDir,
132
129
  mode: options.fetchMissing ? "fetch" : "offline",
133
130
  });
134
131
  }
@@ -146,8 +143,8 @@ function materialize(declaration, options, errors) {
146
143
  */
147
144
  function scopeConventionDirs(options) {
148
145
  return [
149
- join(packageScopeDir("global", undefined, options.stateDir), EXTENSIONS_SUBDIR),
150
- join(packageScopeDir("conversation", options.address, options.stateDir), EXTENSIONS_SUBDIR),
146
+ join(packageScopeDir("global", undefined, options.office.workspace.stateDir), EXTENSIONS_SUBDIR),
147
+ join(options.office.stateDir, EXTENSIONS_SUBDIR),
151
148
  ];
152
149
  }
153
150
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"resolve.js","sourceRoot":"","sources":["../../src/packages/resolve.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;GAoBG;AACH,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACzC,OAAO,EAAE,UAAU,EAAE,QAAQ,EAAE,MAAM,SAAS,CAAC;AAC/C,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AACjC,OAAO,EAAE,kBAAkB,EAAE,2BAA2B,EAAE,MAAM,cAAc,CAAC;AAC/E,OAAO,KAAK,GAAG,MAAM,WAAW,CAAC;AACjC,OAAO,EAAE,iBAAiB,EAAE,eAAe,EAAE,MAAM,kBAAkB,CAAC;AACtE,OAAO,EAAE,WAAW,EAAE,cAAc,EAAE,MAAM,aAAa,CAAC;AAY1D,iFAAiF;AACjF,MAAM,iBAAiB,GAAG,YAAY,CAAC;AACvC,MAAM,aAAa,GAAG,QAAQ,CAAC;AAC/B,gFAAgF;AAChF,MAAM,eAAe,GAAG,EAAE,CAAC;AAE3B;;;;;;;;;;;;;GAaG;AACH,MAAM,oBAA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AAe,GAAG,MAAM,CAAC,MAAM,GAAG,CAAC,CAAC,IAAI,MAAM,EAAE,CAAC;AAC/E,CAAC;AAED,qDAAqD;AACrD,SAAS,SAAS,CAAC,KAAmB;IACpC,OAAO,KAAK,KAAK,QAAQ,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;AACpC,CAAC;AAED,SAAS,UAAU,CAAC,CAAsB,EAAE,CAAsB;IAChE,OAAO,SAAS,CAAC,CAAC,CAAC,KAAK,CAAC,GAAG,SAAS,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC;AACjD,CAAC;AAED,SAAS,SAAS,CAAC,GAAY;IAC7B,OAAO,GAAG,YAAY,KAAK,CAAC,CAAC,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC;AAC1D,CAAC","sourcesContent":["/**\n * What a conversation actually loads: the two scopes' declared packages\n * combined, collisions resolved, and each surviving package turned into the\n * directories the extension loader and the skill loader consume.\n *\n * Two rules do all the work here:\n *\n * - **Additive scopes.** `global` packages load for every conversation; a\n * conversation's packages load on top. Neither list replaces the other.\n * - **Narrower scope wins.** When both scopes declare the same package\n * ({@link sourceIdentity}, which ignores the ref), only the conversation's\n * copy loads. That is what makes \"pin this one channel to v2 while everyone\n * else stays on v1\" work, and it is why the same package installed twice\n * cannot activate twice.\n *\n * Resolution never throws. A conversation with one malformed or unfetchable\n * source still loads every other package, and the failure is reported through\n * {@link ResolvedPackages.errors} for the portal and the logs. The alternative\n * — one bad string in settings taking a conversation offline — is a far worse\n * failure mode than a missing feature.\n */\nimport { createHash } from \"node:crypto\";\nimport { existsSync, statSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport { loadGlobalSettings, resolveConversationSettings } from \"../config.js\";\nimport * as log from \"../log.js\";\nimport { materializeSource, packageScopeDir } from \"./materialize.js\";\nimport { parseSource, sourceIdentity } from \"./source.js\";\nimport type {\n MaterializedPackage,\n PackageError,\n PackageScope,\n PackageSkillDir,\n ResolvePackagesOptions,\n ResolvedPackages,\n} from \"./types.js\";\n\nexport type { ResolvePackagesOptions, ResolvedPackages } from \"./types.js\";\n\n/** Conventional resource directories inside a package, mirroring pi's layout. */\nconst EXTENSIONS_SUBDIR = \"extensions\";\nconst SKILLS_SUBDIR = \"skills\";\n/** Slug length cap; long identities keep a digest tail instead of colliding. */\nconst SLUG_MAX_LENGTH = 96;\n\n/**\n * Where package resources appear inside the sandbox.\n *\n * Deliberately OUTSIDE `/workspace`. In `full` workspace-mount mode\n * `/workspace` is the entire working directory, so a `/workspace/packages`\n * mount would shadow a real `packages/` directory in the user's tree — mikan's\n * own repository has one. Living outside also keeps\n * `translateMountedRuntimePathToHost` correct by construction: it maps only\n * the `/workspace` prefix and returns everything else untouched, so a package\n * path can never be mistranslated into a host path that does not exist.\n *\n * Skills are referenced by absolute path in the system prompt, so the location\n * costs nothing in usability.\n */\nconst PACKAGE_RUNTIME_ROOT = \"/mikan/packages\";\n\n/** Runtime path a package's skills directory is mounted at. */\nexport function packageSkillRuntimeDir(slug: string): string {\n return `${PACKAGE_RUNTIME_ROOT}/${slug}/${SKILLS_SUBDIR}`;\n}\n\n/**\n * Read-only mounts exposing every resolved package's skills to the sandbox.\n *\n * Read-only rather than read-write because the host owns these files: the\n * directory is a git checkout that an update replaces wholesale, so an agent\n * edit would be silently discarded on the next refresh. Making the filesystem\n * refuse the write turns a confusing data-loss bug into an obvious error.\n *\n * Resolution is offline, so building the mount list never reaches the network.\n */\nexport function conversationPackageSkillMounts(\n options: ResolvePackagesOptions,\n): Array<{ source: string; target: string; readOnly: true }> {\n return resolveConversationPackages(options).skillDirs.map(({ slug, dir }) => ({\n source: dir,\n target: packageSkillRuntimeDir(slug),\n readOnly: true,\n }));\n}\n\n/**\n * Resolve the package set for one conversation. Reads both scopes' settings,\n * dedups, and reports the directories to load from.\n */\nexport function resolveConversationPackages(options: ResolvePackagesOptions): ResolvedPackages {\n const declarations = [...readScope(\"global\", options), ...readScope(\"conversation\", options)];\n\n const errors: PackageError[] = [];\n const byIdentity = new Map<string, MaterializedPackage>();\n\n for (const declaration of declarations) {\n let identity: string;\n try {\n identity = sourceIdentity(parseSource(declaration.source));\n } catch (err) {\n errors.push({ source: declaration.source, message: messageOf(err) });\n continue;\n }\n // Later scopes overwrite earlier ones: global is read first, so a\n // conversation declaring the same package shadows it.\n const existing = byIdentity.get(identity);\n if (existing && existing.scope !== declaration.scope) {\n log.logInfo(`Package ${identity} declared in both scopes; using the conversation's copy`);\n }\n const materialized = materialize(declaration, options, errors);\n if (materialized) byIdentity.set(identity, materialized);\n else byIdentity.delete(identity);\n }\n\n const packages = [...byIdentity.values()].toSorted(scopeOrder);\n const targets = packages.map(packageExtensionTargets);\n return {\n packages,\n extensionDirs: [...scopeConventionDirs(options), ...targets.flatMap((target) => target.dirs)],\n extensionRoots: targets.flatMap((target) => target.roots),\n skillDirs: packages.flatMap(packageSkillDir),\n errors,\n };\n}\n\ninterface Declaration {\n source: string;\n scope: PackageScope;\n}\n\nfunction readScope(scope: PackageScope, options: ResolvePackagesOptions): Declaration[] {\n try {\n const sources =\n scope === \"global\"\n ? loadGlobalSettings().packages\n : resolveConversationSettings({\n address: options.address,\n conversationDir: options.conversationDir,\n }).packages;\n return (sources ?? []).map((source) => ({ source, scope }));\n } catch (err) {\n // Unreadable settings must not take the conversation down; the other\n // scope, and the convention directories, still load.\n log.logWarning(`Could not read ${scope} package list`, messageOf(err));\n return [];\n }\n}\n\nfunction materialize(\n declaration: Declaration,\n options: ResolvePackagesOptions,\n errors: PackageError[],\n): MaterializedPackage | undefined {\n try {\n return materializeSource(declaration.source, {\n scope: declaration.scope,\n address: options.address,\n stateDir: options.stateDir,\n mode: options.fetchMissing ? \"fetch\" : \"offline\",\n });\n } catch (err) {\n errors.push({ source: declaration.source, message: messageOf(err) });\n return undefined;\n }\n}\n\n/**\n * The convention directories that need no declaration:\n * `<stateDir>/global/extensions` and\n * `<stateDir>/conversations/<id>/extensions`. These are the directories\n * `mikan ext install` writes into, so CLI installs and portal-declared\n * packages coexist.\n */\nfunction scopeConventionDirs(options: ResolvePackagesOptions): string[] {\n return [\n join(packageScopeDir(\"global\", undefined, options.stateDir), EXTENSIONS_SUBDIR),\n join(packageScopeDir(\"conversation\", options.address, options.stateDir), EXTENSIONS_SUBDIR),\n ];\n}\n\n/**\n * How a package contributes extensions. Two shapes are accepted, and which one\n * applies is decided by the package's own layout rather than by configuration:\n *\n * - **Collection**: an `extensions/` subdirectory, scanned for named children.\n * This is the shape a repository shipping several extensions has.\n * - **Single extension**: no `extensions/` subdirectory, but the package root\n * is itself a loadable extension (an index file, or a `package.json` with\n * `mikan.extensions`). This is what a one-extension repo looks like, and it\n * is what a developer's working copy looks like — so `mikan ext dev` needs\n * no special case.\n *\n * The slug comes from the package directory name in the single-extension\n * shape, so a repo named for its extension gets the identity its author\n * expects.\n */\nfunction packageExtensionTargets(pkg: MaterializedPackage): { dirs: string[]; roots: string[] } {\n const collection = join(pkg.dir, EXTENSIONS_SUBDIR);\n if (existsSync(collection)) return { dirs: [collection], roots: [] };\n return { dirs: [], roots: [pkg.dir] };\n}\n\nfunction packageSkillDir(pkg: MaterializedPackage): PackageSkillDir[] {\n const dir = join(pkg.dir, SKILLS_SUBDIR);\n if (!existsSync(dir) || !statSync(dir).isDirectory()) return [];\n return [{ slug: packageSlug(pkg), dir }];\n}\n\n/**\n * Filesystem-safe, collision-resistant name for a package, used as the mount\n * path segment for its skills. Derived from the identity rather than the\n * source string so the same package spelled two ways gets one name.\n */\nfunction packageSlug(pkg: MaterializedPackage): string {\n const readable = pkg.identity\n .replace(/^(git|local):/, \"\")\n .toLowerCase()\n .replace(/[^a-z0-9._-]+/g, \"-\")\n .replace(/^-+|-+$/g, \"\");\n if (readable.length <= SLUG_MAX_LENGTH) return readable;\n // Truncation alone would let two long identities sharing a prefix (deeply\n // nested self-hosted groups, file:// paths) land on the same slug — and\n // therefore the same mount target, where one package's skills would quietly\n // replace the other's. The digest makes the tail collision-resistant.\n const digest = createHash(\"sha256\").update(pkg.identity).digest(\"hex\").slice(0, 8);\n return `${readable.slice(0, SLUG_MAX_LENGTH - digest.length - 1)}-${digest}`;\n}\n\n/** Global packages load before conversation ones. */\nfunction scopeRank(scope: PackageScope): number {\n return scope === \"global\" ? 0 : 1;\n}\n\nfunction scopeOrder(a: MaterializedPackage, b: MaterializedPackage): number {\n return scopeRank(a.scope) - scopeRank(b.scope);\n}\n\nfunction messageOf(err: unknown): string {\n return err instanceof Error ? err.message : String(err);\n}\n"]}
1
+ {"version":3,"file":"resolve.js","sourceRoot":"","sources":["../../src/packages/resolve.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;GAoBG;AACH,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACzC,OAAO,EAAE,UAAU,EAAE,QAAQ,EAAE,MAAM,SAAS,CAAC;AAC/C,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AACjC,OAAO,EAAE,kBAAkB,EAAE,2BAA2B,EAAE,MAAM,cAAc,CAAC;AAC/E,OAAO,KAAK,GAAG,MAAM,WAAW,CAAC;AACjC,OAAO,EAAE,iBAAiB,EAAE,eAAe,EAAE,MAAM,kBAAkB,CAAC;AACtE,OAAO,EAAE,WAAW,EAAE,cAAc,EAAE,MAAM,aAAa,CAAC;AAY1D,iFAAiF;AACjF,MAAM,iBAAiB,GAAG,YAAY,CAAC;AACvC,MAAM,aAAa,GAAG,QAAQ,CAAC;AAC/B,gFAAgF;AAChF,MAAM,eAAe,GAAG,EAAE,CAAC;AAE3B;;;;;;;;;;;;;GAaG;AACH,MAAM,oBAAoB,GAAG,iBAAiB,CAAC;AAE/C,+DAA+D;AAC/D,MAAM,UAAU,sBAAsB,CAAC,IAAY;IACjD,OAAO,GAAG,oBAAoB,IAAI,IAAI,IAAI,aAAa,EAAE,CAAC;AAC5D,CAAC;AAED;;;;;;;;;GASG;AACH,MAAM,UAAU,8BAA8B,CAC5C,OAA+B;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CAAsB;IAChE,OAAO,SAAS,CAAC,CAAC,CAAC,KAAK,CAAC,GAAG,SAAS,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC;AACjD,CAAC;AAED,SAAS,SAAS,CAAC,GAAY;IAC7B,OAAO,GAAG,YAAY,KAAK,CAAC,CAAC,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC;AAC1D,CAAC","sourcesContent":["/**\n * What a conversation actually loads: the two scopes' declared packages\n * combined, collisions resolved, and each surviving package turned into the\n * directories the extension loader and the skill loader consume.\n *\n * Two rules do all the work here:\n *\n * - **Additive scopes.** `global` packages load for every conversation; a\n * conversation's packages load on top. Neither list replaces the other.\n * - **Narrower scope wins.** When both scopes declare the same package\n * ({@link sourceIdentity}, which ignores the ref), only the conversation's\n * copy loads. That is what makes \"pin this one channel to v2 while everyone\n * else stays on v1\" work, and it is why the same package installed twice\n * cannot activate twice.\n *\n * Resolution never throws. A conversation with one malformed or unfetchable\n * source still loads every other package, and the failure is reported through\n * {@link ResolvedPackages.errors} for the portal and the logs. The alternative\n * — one bad string in settings taking a conversation offline — is a far worse\n * failure mode than a missing feature.\n */\nimport { createHash } from \"node:crypto\";\nimport { existsSync, statSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport { loadGlobalSettings, resolveConversationSettings } from \"../config.js\";\nimport * as log from \"../log.js\";\nimport { materializeSource, packageScopeDir } from \"./materialize.js\";\nimport { parseSource, sourceIdentity } from \"./source.js\";\nimport type {\n MaterializedPackage,\n PackageError,\n PackageScope,\n PackageSkillDir,\n ResolvePackagesOptions,\n ResolvedPackages,\n} from \"./types.js\";\n\nexport type { ResolvePackagesOptions, ResolvedPackages } from \"./types.js\";\n\n/** Conventional resource directories inside a package, mirroring pi's layout. */\nconst EXTENSIONS_SUBDIR = \"extensions\";\nconst SKILLS_SUBDIR = \"skills\";\n/** Slug length cap; long identities keep a digest tail instead of colliding. */\nconst SLUG_MAX_LENGTH = 96;\n\n/**\n * Where package resources appear inside the sandbox.\n *\n * Deliberately OUTSIDE `/workspace`. In `full` workspace-mount mode\n * `/workspace` is the entire working directory, so a `/workspace/packages`\n * mount would shadow a real `packages/` directory in the user's tree — mikan's\n * own repository has one. Living outside also keeps\n * `translateMountedRuntimePathToHost` correct by construction: it maps only\n * the `/workspace` prefix and returns everything else untouched, so a package\n * path can never be mistranslated into a host path that does not exist.\n *\n * Skills are referenced by absolute path in the system prompt, so the location\n * costs nothing in usability.\n */\nconst PACKAGE_RUNTIME_ROOT = \"/mikan/packages\";\n\n/** Runtime path a package's skills directory is mounted at. */\nexport function packageSkillRuntimeDir(slug: string): string {\n return `${PACKAGE_RUNTIME_ROOT}/${slug}/${SKILLS_SUBDIR}`;\n}\n\n/**\n * Read-only mounts exposing every resolved package's skills to the sandbox.\n *\n * Read-only rather than read-write because the host owns these files: the\n * directory is a git checkout that an update replaces wholesale, so an agent\n * edit would be silently discarded on the next refresh. Making the filesystem\n * refuse the write turns a confusing data-loss bug into an obvious error.\n *\n * Resolution is offline, so building the mount list never reaches the network.\n */\nexport function conversationPackageSkillMounts(\n options: ResolvePackagesOptions,\n): Array<{ source: string; target: string; readOnly: true }> {\n return resolveConversationPackages(options).skillDirs.map(({ slug, dir }) => ({\n source: dir,\n target: packageSkillRuntimeDir(slug),\n readOnly: true,\n }));\n}\n\n/**\n * Resolve the package set for one conversation. Reads both scopes' settings,\n * dedups, and reports the directories to load from.\n */\nexport function resolveConversationPackages(options: ResolvePackagesOptions): ResolvedPackages {\n const declarations = [...readScope(\"global\", options), ...readScope(\"conversation\", options)];\n\n const errors: PackageError[] = [];\n const byIdentity = new Map<string, MaterializedPackage>();\n\n for (const declaration of declarations) {\n let identity: string;\n try {\n identity = sourceIdentity(parseSource(declaration.source));\n } catch (err) {\n errors.push({ source: declaration.source, message: messageOf(err) });\n continue;\n }\n // Later scopes overwrite earlier ones: global is read first, so a\n // conversation declaring the same package shadows it.\n const existing = byIdentity.get(identity);\n if (existing && existing.scope !== declaration.scope) {\n log.logInfo(`Package ${identity} declared in both scopes; using the conversation's copy`);\n }\n const materialized = materialize(declaration, options, errors);\n if (materialized) byIdentity.set(identity, materialized);\n else byIdentity.delete(identity);\n }\n\n const packages = [...byIdentity.values()].toSorted(scopeOrder);\n const targets = packages.map(packageExtensionTargets);\n return {\n packages,\n extensionDirs: [...scopeConventionDirs(options), ...targets.flatMap((target) => target.dirs)],\n extensionRoots: targets.flatMap((target) => target.roots),\n skillDirs: packages.flatMap(packageSkillDir),\n errors,\n };\n}\n\ninterface Declaration {\n source: string;\n scope: PackageScope;\n}\n\nfunction readScope(scope: PackageScope, options: ResolvePackagesOptions): Declaration[] {\n try {\n const sources =\n scope === \"global\"\n ? loadGlobalSettings().packages\n : resolveConversationSettings(options.office).packages;\n return (sources ?? []).map((source) => ({ source, scope }));\n } catch (err) {\n // Unreadable settings must not take the conversation down; the other\n // scope, and the convention directories, still load.\n log.logWarning(`Could not read ${scope} package list`, messageOf(err));\n return [];\n }\n}\n\nfunction materialize(\n declaration: Declaration,\n options: ResolvePackagesOptions,\n errors: PackageError[],\n): MaterializedPackage | undefined {\n try {\n return materializeSource(declaration.source, {\n scope: declaration.scope,\n address: options.office.address,\n stateDir: options.office.workspace.stateDir,\n mode: options.fetchMissing ? \"fetch\" : \"offline\",\n });\n } catch (err) {\n errors.push({ source: declaration.source, message: messageOf(err) });\n return undefined;\n }\n}\n\n/**\n * The convention directories that need no declaration:\n * `<stateDir>/global/extensions` and\n * `<stateDir>/conversations/<id>/extensions`. These are the directories\n * `mikan ext install` writes into, so CLI installs and portal-declared\n * packages coexist.\n */\nfunction scopeConventionDirs(options: ResolvePackagesOptions): string[] {\n return [\n join(\n packageScopeDir(\"global\", undefined, options.office.workspace.stateDir),\n EXTENSIONS_SUBDIR,\n ),\n join(options.office.stateDir, EXTENSIONS_SUBDIR),\n ];\n}\n\n/**\n * How a package contributes extensions. Two shapes are accepted, and which one\n * applies is decided by the package's own layout rather than by configuration:\n *\n * - **Collection**: an `extensions/` subdirectory, scanned for named children.\n * This is the shape a repository shipping several extensions has.\n * - **Single extension**: no `extensions/` subdirectory, but the package root\n * is itself a loadable extension (an index file, or a `package.json` with\n * `mikan.extensions`). This is what a one-extension repo looks like, and it\n * is what a developer's working copy looks like — so `mikan ext dev` needs\n * no special case.\n *\n * The slug comes from the package directory name in the single-extension\n * shape, so a repo named for its extension gets the identity its author\n * expects.\n */\nfunction packageExtensionTargets(pkg: MaterializedPackage): { dirs: string[]; roots: string[] } {\n const collection = join(pkg.dir, EXTENSIONS_SUBDIR);\n if (existsSync(collection)) return { dirs: [collection], roots: [] };\n return { dirs: [], roots: [pkg.dir] };\n}\n\nfunction packageSkillDir(pkg: MaterializedPackage): PackageSkillDir[] {\n const dir = join(pkg.dir, SKILLS_SUBDIR);\n if (!existsSync(dir) || !statSync(dir).isDirectory()) return [];\n return [{ slug: packageSlug(pkg), dir }];\n}\n\n/**\n * Filesystem-safe, collision-resistant name for a package, used as the mount\n * path segment for its skills. Derived from the identity rather than the\n * source string so the same package spelled two ways gets one name.\n */\nfunction packageSlug(pkg: MaterializedPackage): string {\n const readable = pkg.identity\n .replace(/^(git|local):/, \"\")\n .toLowerCase()\n .replace(/[^a-z0-9._-]+/g, \"-\")\n .replace(/^-+|-+$/g, \"\");\n if (readable.length <= SLUG_MAX_LENGTH) return readable;\n // Truncation alone would let two long identities sharing a prefix (deeply\n // nested self-hosted groups, file:// paths) land on the same slug — and\n // therefore the same mount target, where one package's skills would quietly\n // replace the other's. The digest makes the tail collision-resistant.\n const digest = createHash(\"sha256\").update(pkg.identity).digest(\"hex\").slice(0, 8);\n return `${readable.slice(0, SLUG_MAX_LENGTH - digest.length - 1)}-${digest}`;\n}\n\n/** Global packages load before conversation ones. */\nfunction scopeRank(scope: PackageScope): number {\n return scope === \"global\" ? 0 : 1;\n}\n\nfunction scopeOrder(a: MaterializedPackage, b: MaterializedPackage): number {\n return scopeRank(a.scope) - scopeRank(b.scope);\n}\n\nfunction messageOf(err: unknown): string {\n return err instanceof Error ? err.message : String(err);\n}\n"]}
@@ -66,10 +66,8 @@ export interface PackageSkillDir {
66
66
  dir: string;
67
67
  }
68
68
  export interface ResolvePackagesOptions {
69
- /** Office whose packages resolve; state-dir keys derive from it. */
70
- address: import("../types.js").OfficeAddress;
71
- stateDir: string;
72
- conversationDir: string;
69
+ /** Office whose packages resolve; identity and state-dir keys derive from it. */
70
+ office: import("../office/types.js").Office;
73
71
  fetchMissing?: boolean;
74
72
  }
75
73
  export type MaterializeMode = "offline" | "fetch" | "refresh";
@@ -94,7 +92,6 @@ export interface PackageInventory {
94
92
  conversation: PackageStatus[];
95
93
  }
96
94
  export interface PackageAdminContext extends ResolvePackagesOptions {
97
- workingDir: string;
98
95
  runtime?: import("../types.js").RunnerCacheControl & import("../types.js").GlobalRunnerCacheControl;
99
96
  }
100
97
  export interface PackageWriteResult {
@@ -1 +1 @@
1
- {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../src/packages/types.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AACH,MAAM,MAAM,mBAAmB,GAAG,MAAM,CAAC;AAEzC,qEAAqE;AACrE,MAAM,MAAM,YAAY,GAAG,QAAQ,GAAG,cAAc,CAAC;AAErD;;;;GAIG;AACH,UAAU,SAAS;IACjB,IAAI,EAAE,KAAK,CAAC;IACZ,4DAA4D;IAC5D,GAAG,EAAE,MAAM,CAAC;IACZ,GAAG,CAAC,EAAE,MAAM,CAAC;IACb,OAAO,CAAC,EAAE,MAAM,CAAC;CAClB;AAED;;;;GAIG;AACH,UAAU,WAAW;IACnB,IAAI,EAAE,OAAO,CAAC;IACd,IAAI,EAAE,MAAM,CAAC;CACd;AAED,MAAM,MAAM,YAAY,GAAG,SAAS,GAAG,WAAW,CAAC;AAEnD;;;;;;;GAOG;AACH,MAAM,MAAM,eAAe,GAAG,MAAM,CAAC;AAErC,wEAAwE;AACxE,MAAM,WAAW,mBAAmB;IAClC,MAAM,EAAE,mBAAmB,CAAC;IA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oB,SAAQ,sBAAsB;IACjE,OAAO,CAAC,EAAE,OAAO,aAAa,EAAE,kBAAkB,GAChD,OAAO,aAAa,EAAE,wBAAwB,CAAC;CAClD;AAED,MAAM,WAAW,kBAAkB;IACjC,MAAM,EAAE,MAAM,CAAC;IACf,GAAG,EAAE,MAAM,CAAC;CACb"}
@@ -1 +1 @@
1
- {"version":3,"file":"types.js","sourceRoot":"","sources":["../../src/packages/types.ts"],"names":[],"mappings":"","sourcesContent":["/**\n * A package source as written by a human: the string stored in `packages[]`\n * in global or conversation settings, and the string typed into the admin\n * portal. Parsing it is {@link parseSource}'s job.\n */\nexport type PackageSourceString = string;\n\n/** Scope a package belongs to. `global` spans every conversation. */\nexport type PackageScope = \"global\" | \"conversation\";\n\n/**\n * A git source. `ref` is a tag, branch, or commit — absent means \"whatever the\n * remote's default branch points at now\", which only moves on an explicit\n * update. `subpath` addresses a package inside a larger repository.\n */\ninterface GitSource {\n type: \"git\";\n /** Clone URL handed to `git`, after shorthand expansion. */\n url: string;\n ref?: string;\n subpath?: string;\n}\n\n/**\n * A directory on the mikan host, used by reference — never copied. Editing the\n * directory is picked up by the next harness instance, which is what makes\n * host-side development of an extension bearable.\n */\ninterface LocalSource {\n type: \"local\";\n path: string;\n}\n\nexport type ParsedSource = GitSource | LocalSource;\n\n/**\n * Stable identity of a package, independent of version and of the scope it is\n * installed in. Two sources with the same identity are the same package, so\n * the conversation scope's copy can shadow the global one.\n *\n * Deliberately excludes the ref: `…/repo@v1` in global and `…/repo@v2` in a\n * conversation are one package pinned two ways, and the conversation wins.\n */\nexport type PackageIdentity = string;\n\n/** Where a materialized package's files live, plus how it got there. */\nexport interface MaterializedPackage {\n source: PackageSourceString;\n parsed: ParsedSource;\n identity: PackageIdentity;\n /**\n * Directory holding the package's files. For git this is inside the state\n * dir (a clone, plus `subpath`); for local it is the referenced path itself.\n */\n dir: string;\n scope: PackageScope;\n}\n\n/** A source that failed to materialize, reported back to whoever asked. */\nexport interface PackageError {\n source: PackageSourceString;\n message: string;\n}\n\nexport interface ResolvedPackages {\n packages: MaterializedPackage[];\n extensionDirs: string[];\n extensionRoots: string[];\n skillDirs: PackageSkillDir[];\n errors: PackageError[];\n}\n\nexport interface PackageSkillDir {\n slug: string;\n dir: string;\n}\n\nexport interface ResolvePackagesOptions {\n /** Office whose packages resolve; state-dir keys derive from it. */\n address: import(\"../types.js\").OfficeAddress;\n stateDir: string;\n conversationDir: string;\n fetchMissing?: boolean;\n}\n\nexport type MaterializeMode = \"offline\" | \"fetch\" | \"refresh\";\n\nexport interface MaterializeOptions {\n scope: PackageScope;\n address?: import(\"../types.js\").OfficeAddress;\n stateDir: string;\n mode?: MaterializeMode;\n}\n\nexport interface PackageStatus {\n source: string;\n scope: PackageScope;\n ready: boolean;\n error?: string;\n dir?: string;\n shadowed?: boolean;\n extensions: string[];\n skills: string[];\n}\n\nexport interface PackageInventory {\n global: PackageStatus[];\n conversation: PackageStatus[];\n}\n\nexport interface PackageAdminContext extends ResolvePackagesOptions {\n workingDir: string;\n runtime?: import(\"../types.js\").RunnerCacheControl &\n import(\"../types.js\").GlobalRunnerCacheControl;\n}\n\nexport interface PackageWriteResult {\n source: string;\n dir: string;\n}\n"]}
1
+ {"version":3,"file":"types.js","sourceRoot":"","sources":["../../src/packages/types.ts"],"names":[],"mappings":"","sourcesContent":["/**\n * A package source as written by a human: the string stored in `packages[]`\n * in global or conversation settings, and the string typed into the admin\n * portal. Parsing it is {@link parseSource}'s job.\n */\nexport type PackageSourceString = string;\n\n/** Scope a package belongs to. `global` spans every conversation. */\nexport type PackageScope = \"global\" | \"conversation\";\n\n/**\n * A git source. `ref` is a tag, branch, or commit — absent means \"whatever the\n * remote's default branch points at now\", which only moves on an explicit\n * update. `subpath` addresses a package inside a larger repository.\n */\ninterface GitSource {\n type: \"git\";\n /** Clone URL handed to `git`, after shorthand expansion. */\n url: string;\n ref?: string;\n subpath?: string;\n}\n\n/**\n * A directory on the mikan host, used by reference — never copied. Editing the\n * directory is picked up by the next harness instance, which is what makes\n * host-side development of an extension bearable.\n */\ninterface LocalSource {\n type: \"local\";\n path: string;\n}\n\nexport type ParsedSource = GitSource | LocalSource;\n\n/**\n * Stable identity of a package, independent of version and of the scope it is\n * installed in. Two sources with the same identity are the same package, so\n * the conversation scope's copy can shadow the global one.\n *\n * Deliberately excludes the ref: `…/repo@v1` in global and `…/repo@v2` in a\n * conversation are one package pinned two ways, and the conversation wins.\n */\nexport type PackageIdentity = string;\n\n/** Where a materialized package's files live, plus how it got there. */\nexport interface MaterializedPackage {\n source: PackageSourceString;\n parsed: ParsedSource;\n identity: PackageIdentity;\n /**\n * Directory holding the package's files. For git this is inside the state\n * dir (a clone, plus `subpath`); for local it is the referenced path itself.\n */\n dir: string;\n scope: PackageScope;\n}\n\n/** A source that failed to materialize, reported back to whoever asked. */\nexport interface PackageError {\n source: PackageSourceString;\n message: string;\n}\n\nexport interface ResolvedPackages {\n packages: MaterializedPackage[];\n extensionDirs: string[];\n extensionRoots: string[];\n skillDirs: PackageSkillDir[];\n errors: PackageError[];\n}\n\nexport interface PackageSkillDir {\n slug: string;\n dir: string;\n}\n\nexport interface ResolvePackagesOptions {\n /** Office whose packages resolve; identity and state-dir keys derive from it. */\n office: import(\"../office/types.js\").Office;\n fetchMissing?: boolean;\n}\n\nexport type MaterializeMode = \"offline\" | \"fetch\" | \"refresh\";\n\nexport interface MaterializeOptions {\n scope: PackageScope;\n address?: import(\"../types.js\").OfficeAddress;\n stateDir: string;\n mode?: MaterializeMode;\n}\n\nexport interface PackageStatus {\n source: string;\n scope: PackageScope;\n ready: boolean;\n error?: string;\n dir?: string;\n shadowed?: boolean;\n extensions: string[];\n skills: string[];\n}\n\nexport interface PackageInventory {\n global: PackageStatus[];\n conversation: PackageStatus[];\n}\n\nexport interface PackageAdminContext extends ResolvePackagesOptions {\n runtime?: import(\"../types.js\").RunnerCacheControl &\n import(\"../types.js\").GlobalRunnerCacheControl;\n}\n\nexport interface PackageWriteResult {\n source: string;\n dir: string;\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"conversation-runtime.d.ts","sourceRoot":"","sources":["../../src/runtime/conversation-runtime.ts"],"names":[],"mappings":"AA6CA,YAAY,EACV,iBAAiB,EACjB,mBAAmB,EACnB,0BAA0B,GAC3B,MAAM,YAAY,CAAC;AACpB,OAAO,KAAK,EAEV,mBAAmB,EACnB,0BAA0B,EAE3B,MAAM,YAAY,CAAC;AA2BpB,wBAAgB,yBAAyB,CACvC,OAAO,EAAE,0BAA0B,GAClC,mBAAmB,CAErB"}
1
+ {"version":3,"file":"conversation-runtime.d.ts","sourceRoot":"","sources":["../../src/runtime/conversation-runtime.ts"],"names":[],"mappings":"AA6CA,YAAY,EACV,iBAAiB,EACjB,mBAAmB,EACnB,0BAA0B,GAC3B,MAAM,YAAY,CAAC;AACpB,OAAO,KAAK,EAEV,mBAAmB,EACnB,0BAA0B,EAE3B,MAAM,YAAY,CAAC;AA4BpB,wBAAgB,yBAAyB,CACvC,OAAO,EAAE,0BAA0B,GAClC,mBAAmB,CAErB"}
@@ -1,4 +1,4 @@
1
- import { conversationOfficeDir, officeDirName, officeKey } from "../office-address.js";
1
+ import { officeKey } from "../office/index.js";
2
2
  import { createRunner } from "../agent.js";
3
3
  import { MikanModels } from "../harness/index.js";
4
4
  import { defaultCommandHandlers, dispatchCommand } from "../commands/registry.js";
@@ -26,9 +26,10 @@ function portalNotConfiguredTokenStore(portal) {
26
26
  },
27
27
  };
28
28
  }
29
- function runtimeCwdForSandbox(sandbox, hostWorkspaceRoot, address) {
30
- const runtimeWorkspaceRoot = getUnresolvedSandboxPathContext(sandbox, hostWorkspaceRoot).runtimeWorkspaceRoot;
31
- return `${runtimeWorkspaceRoot.replace(/\/+$/, "")}/${officeDirName(address)}`;
29
+ function runtimeCwdForSandbox(sandbox, workspace, address) {
30
+ const runtimeWorkspaceRoot = getUnresolvedSandboxPathContext(sandbox, workspace.root).runtimeWorkspaceRoot;
31
+ // The office key names the same segment on the host and in the runtime.
32
+ return `${runtimeWorkspaceRoot.replace(/\/+$/, "")}/${workspace.office(address).key}`;
32
33
  }
33
34
  export function createConversationRuntime(options) {
34
35
  return new ConversationRuntimeImpl(options);
@@ -209,7 +210,7 @@ class ConversationRuntimeImpl {
209
210
  const conversationId = address.conversationId;
210
211
  if (message.conversationKind !== "shared" || sessionKey !== conversationId)
211
212
  return;
212
- const conversationDir = conversationOfficeDir(this.options.workingDir, address);
213
+ const conversationDir = this.options.workspace.office(address).dir;
213
214
  const currentSession = resolveChannelSessionFile(conversationDir);
214
215
  if (!currentSession || !shouldRotateTopLevelSession(currentSession, new Date()))
215
216
  return;
@@ -231,7 +232,7 @@ class ConversationRuntimeImpl {
231
232
  log.logWarning(`[${conversationId}] Automatic Session Dream failed${detail}`);
232
233
  return;
233
234
  }
234
- const runtimeCwd = runtimeCwdForSandbox(this.options.sandbox, this.options.workingDir, address);
235
+ const runtimeCwd = runtimeCwdForSandbox(this.options.sandbox, this.options.workspace, address);
235
236
  this.chatSessionManager.resetSession({ conversationDir, sessionKey, cwd: runtimeCwd });
236
237
  this.sessions.discard(address, sessionKey);
237
238
  log.logInfo(`[${conversationId}] Session Dream completed; rotated session: ${sessionKey}`);
@@ -247,8 +248,8 @@ class ConversationRuntimeImpl {
247
248
  async resetSession(state, bot) {
248
249
  const { address, sessionKey } = state;
249
250
  const conversationId = address.conversationId;
250
- const conversationDir = conversationOfficeDir(this.options.workingDir, address);
251
- const runtimeCwd = runtimeCwdForSandbox(this.options.sandbox, this.options.workingDir, address);
251
+ const conversationDir = this.options.workspace.office(address).dir;
252
+ const runtimeCwd = runtimeCwdForSandbox(this.options.sandbox, this.options.workspace, address);
252
253
  this.chatSessionManager.resetSession({ conversationDir, sessionKey, cwd: runtimeCwd });
253
254
  this.sessions.discard(address, sessionKey);
254
255
  log.logInfo(`[${conversationId}] Session reset: ${sessionKey}`);
@@ -322,7 +323,7 @@ class ConversationRuntimeImpl {
322
323
  }
323
324
  const releaseConversationWork = await this.sessions.acquireConversationWork(address);
324
325
  try {
325
- const conversationDir = conversationOfficeDir(this.options.workingDir, address);
326
+ const conversationDir = this.options.workspace.office(address).dir;
326
327
  const waitedForParent = await waitForThreadSessionBootstrap({
327
328
  parentSessionKey: conversationId,
328
329
  sessionKey,
@@ -541,10 +542,7 @@ class ConversationRuntimeImpl {
541
542
  const runner = await createRunner({
542
543
  sandboxConfig: this.options.sandbox,
543
544
  sessionKey: options.sessionKey,
544
- address: options.address,
545
- conversationId: options.conversationId,
546
- conversationDir,
547
- workspaceDir: this.options.workingDir,
545
+ office: this.options.workspace.office(options.address),
548
546
  sessionScope,
549
547
  vaultManager: this.options.vaultManager,
550
548
  provisioner: this.options.provisioner,
@@ -572,8 +570,8 @@ class ConversationRuntimeImpl {
572
570
  const existing = this.sessions.get(address, sessionKey);
573
571
  if (existing?.running)
574
572
  return existing;
575
- const conversationDir = conversationOfficeDir(this.options.workingDir, address);
576
- const runtimeCwd = runtimeCwdForSandbox(this.options.sandbox, this.options.workingDir, address);
573
+ const conversationDir = this.options.workspace.office(address).dir;
574
+ const runtimeCwd = runtimeCwdForSandbox(this.options.sandbox, this.options.workspace, address);
577
575
  const sessionScope = await this.chatSessionManager.resolveSessionScope({
578
576
  conversationDir,
579
577
  sessionKey,