@geminixiang/mikan 1.0.0-beta.38 → 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.
- package/CHANGELOG.md +15 -0
- package/README.md +1 -1
- package/dist/adapter.js +1 -1
- package/dist/adapter.js.map +1 -1
- package/dist/adapters/discord/bot.d.ts +3 -6
- package/dist/adapters/discord/bot.d.ts.map +1 -1
- package/dist/adapters/discord/bot.js +16 -39
- package/dist/adapters/discord/bot.js.map +1 -1
- package/dist/adapters/github/bot.d.ts +2 -0
- package/dist/adapters/github/bot.d.ts.map +1 -1
- package/dist/adapters/github/bot.js +15 -11
- package/dist/adapters/github/bot.js.map +1 -1
- package/dist/adapters/github/github-ops.d.ts +1 -1
- package/dist/adapters/github/github-ops.d.ts.map +1 -1
- package/dist/adapters/github/github-ops.js +2 -1
- package/dist/adapters/github/github-ops.js.map +1 -1
- package/dist/adapters/github/repo.d.ts +2 -1
- package/dist/adapters/github/repo.d.ts.map +1 -1
- package/dist/adapters/github/repo.js +2 -3
- package/dist/adapters/github/repo.js.map +1 -1
- package/dist/adapters/github/types.d.ts +1 -1
- package/dist/adapters/github/types.d.ts.map +1 -1
- package/dist/adapters/github/types.js.map +1 -1
- package/dist/adapters/intake.js +1 -1
- package/dist/adapters/intake.js.map +1 -1
- package/dist/adapters/shared.d.ts +17 -5
- package/dist/adapters/shared.d.ts.map +1 -1
- package/dist/adapters/shared.js +44 -8
- package/dist/adapters/shared.js.map +1 -1
- package/dist/adapters/slack/blocks.d.ts +14 -0
- package/dist/adapters/slack/blocks.d.ts.map +1 -1
- package/dist/adapters/slack/blocks.js +34 -0
- package/dist/adapters/slack/blocks.js.map +1 -1
- package/dist/adapters/slack/bot.d.ts +19 -6
- package/dist/adapters/slack/bot.d.ts.map +1 -1
- package/dist/adapters/slack/bot.js +88 -21
- package/dist/adapters/slack/bot.js.map +1 -1
- package/dist/adapters/slack/types.d.ts +1 -1
- package/dist/adapters/slack/types.js.map +1 -1
- package/dist/adapters/telegram/bot.d.ts +5 -6
- package/dist/adapters/telegram/bot.d.ts.map +1 -1
- package/dist/adapters/telegram/bot.js +29 -51
- package/dist/adapters/telegram/bot.js.map +1 -1
- package/dist/adapters/types.d.ts +19 -1
- package/dist/adapters/types.d.ts.map +1 -1
- package/dist/adapters/types.js.map +1 -1
- package/dist/agent.d.ts.map +1 -1
- package/dist/agent.js +55 -54
- package/dist/agent.js.map +1 -1
- package/dist/cli/ext-dev.d.ts.map +1 -1
- package/dist/cli/ext-dev.js +8 -8
- package/dist/cli/ext-dev.js.map +1 -1
- package/dist/cli/ext.js +3 -3
- package/dist/cli/ext.js.map +1 -1
- package/dist/cli/office.js +2 -2
- package/dist/cli/office.js.map +1 -1
- package/dist/commands/auto-reply.d.ts.map +1 -1
- package/dist/commands/auto-reply.js +1 -2
- package/dist/commands/auto-reply.js.map +1 -1
- package/dist/commands/login.js +1 -1
- package/dist/commands/login.js.map +1 -1
- package/dist/commands/manifest.d.ts.map +1 -1
- package/dist/commands/manifest.js +3 -1
- package/dist/commands/manifest.js.map +1 -1
- package/dist/commands/model.d.ts.map +1 -1
- package/dist/commands/model.js +3 -7
- package/dist/commands/model.js.map +1 -1
- package/dist/commands/sandbox.d.ts.map +1 -1
- package/dist/commands/sandbox.js +7 -7
- package/dist/commands/sandbox.js.map +1 -1
- package/dist/commands/session-view.d.ts.map +1 -1
- package/dist/commands/session-view.js +1 -2
- package/dist/commands/session-view.js.map +1 -1
- package/dist/commands/types.d.ts +2 -1
- package/dist/commands/types.d.ts.map +1 -1
- package/dist/commands/types.js.map +1 -1
- package/dist/config.d.ts +10 -18
- package/dist/config.d.ts.map +1 -1
- package/dist/config.js +16 -15
- package/dist/config.js.map +1 -1
- package/dist/execution-resolver.d.ts +4 -6
- package/dist/execution-resolver.d.ts.map +1 -1
- package/dist/execution-resolver.js +10 -19
- package/dist/execution-resolver.js.map +1 -1
- package/dist/harness/extensions/loader.js +1 -1
- package/dist/harness/extensions/loader.js.map +1 -1
- package/dist/index.d.ts +2 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1 -0
- package/dist/index.js.map +1 -1
- package/dist/main.js +16 -16
- package/dist/main.js.map +1 -1
- package/dist/{office-address.d.ts → office/address.d.ts} +13 -14
- package/dist/office/address.d.ts.map +1 -0
- package/dist/{office-address.js → office/address.js} +13 -18
- package/dist/office/address.js.map +1 -0
- package/dist/office/index.d.ts +11 -0
- package/dist/office/index.d.ts.map +1 -0
- package/dist/office/index.js +11 -0
- package/dist/office/index.js.map +1 -0
- package/dist/office/layout.d.ts +20 -0
- package/dist/office/layout.d.ts.map +1 -0
- package/dist/office/layout.js +88 -0
- package/dist/office/layout.js.map +1 -0
- package/dist/{office-migration.d.ts → office/migration.d.ts} +3 -3
- package/dist/office/migration.d.ts.map +1 -0
- package/dist/{office-migration.js → office/migration.js} +8 -12
- package/dist/office/migration.js.map +1 -0
- package/dist/{office-registry.d.ts → office/registry.d.ts} +18 -24
- package/dist/office/registry.d.ts.map +1 -0
- package/dist/{office-registry.js → office/registry.js} +22 -83
- package/dist/office/registry.js.map +1 -0
- package/dist/office/types.d.ts +71 -0
- package/dist/office/types.d.ts.map +1 -0
- package/dist/office/types.js +2 -0
- package/dist/office/types.js.map +1 -0
- package/dist/packages/admin.js +5 -5
- package/dist/packages/admin.js.map +1 -1
- package/dist/packages/inspect.d.ts.map +1 -1
- package/dist/packages/inspect.js +3 -8
- package/dist/packages/inspect.js.map +1 -1
- package/dist/packages/materialize.js +1 -1
- package/dist/packages/materialize.js.map +1 -1
- package/dist/packages/resolve.js +5 -8
- package/dist/packages/resolve.js.map +1 -1
- package/dist/packages/types.d.ts +2 -5
- package/dist/packages/types.d.ts.map +1 -1
- package/dist/packages/types.js.map +1 -1
- package/dist/runtime/conversation-runtime.d.ts.map +1 -1
- package/dist/runtime/conversation-runtime.js +13 -15
- package/dist/runtime/conversation-runtime.js.map +1 -1
- package/dist/runtime/session-lifecycle.js +1 -1
- package/dist/runtime/session-lifecycle.js.map +1 -1
- package/dist/runtime/types.d.ts +3 -2
- package/dist/runtime/types.d.ts.map +1 -1
- package/dist/runtime/types.js.map +1 -1
- package/dist/sandbox/identity.js +1 -1
- package/dist/sandbox/identity.js.map +1 -1
- package/dist/settings-mutation.d.ts +3 -2
- package/dist/settings-mutation.d.ts.map +1 -1
- package/dist/settings-mutation.js +6 -7
- package/dist/settings-mutation.js.map +1 -1
- package/dist/tools/generate-image.d.ts +8 -2
- package/dist/tools/generate-image.d.ts.map +1 -1
- package/dist/tools/generate-image.js +5 -3
- package/dist/tools/generate-image.js.map +1 -1
- package/dist/tools/index.d.ts +5 -0
- package/dist/tools/index.d.ts.map +1 -1
- package/dist/tools/index.js +3 -5
- package/dist/tools/index.js.map +1 -1
- package/dist/trigger.d.ts +1 -1
- package/dist/trigger.d.ts.map +1 -1
- package/dist/trigger.js +5 -10
- package/dist/trigger.js.map +1 -1
- package/dist/types.d.ts +3 -22
- package/dist/types.d.ts.map +1 -1
- package/dist/types.js.map +1 -1
- package/dist/vault/index.js +1 -1
- package/dist/vault/index.js.map +1 -1
- package/dist/vault/injection.d.ts +3 -1
- package/dist/vault/injection.d.ts.map +1 -1
- package/dist/vault/injection.js +2 -2
- package/dist/vault/injection.js.map +1 -1
- package/dist/web/admin/portal.d.ts.map +1 -1
- package/dist/web/admin/portal.js +67 -80
- package/dist/web/admin/portal.js.map +1 -1
- package/dist/web/admin/types.d.ts +2 -1
- package/dist/web/admin/types.d.ts.map +1 -1
- package/dist/web/admin/types.js.map +1 -1
- package/dist/web/server.d.ts +1 -1
- package/dist/web/server.d.ts.map +1 -1
- package/dist/web/server.js +3 -3
- package/dist/web/server.js.map +1 -1
- package/dist/web/session-view/portal.js +1 -1
- package/dist/web/session-view/portal.js.map +1 -1
- package/dist/workspace-projection/index.d.ts +2 -4
- package/dist/workspace-projection/index.d.ts.map +1 -1
- package/dist/workspace-projection/index.js +21 -56
- package/dist/workspace-projection/index.js.map +1 -1
- package/dist/workspace-projection/types.d.ts +0 -2
- package/dist/workspace-projection/types.d.ts.map +1 -1
- package/dist/workspace-projection/types.js.map +1 -1
- package/package.json +41 -16
- package/dist/office-address.d.ts.map +0 -1
- package/dist/office-address.js.map +0 -1
- package/dist/office-migration.d.ts.map +0 -1
- package/dist/office-migration.js.map +0 -1
- package/dist/office-registry.d.ts.map +0 -1
- package/dist/office-registry.js.map +0 -1
- package/dist/store.d.ts +0 -51
- package/dist/store.d.ts.map +0 -1
- package/dist/store.js +0 -185
- package/dist/store.js.map +0 -1
|
@@ -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
|
|
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,c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O,YAAY,CAAC,KAAK,EAAE,IAAI,EAAE;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,C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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/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"]}
|
package/dist/packages/resolve.js
CHANGED
|
@@ -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(
|
|
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,EAA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1E,wEAAwE;IACxE,4EAA4E;IAC5E,sEAAsE;IACtE,MAAM,MAAM,GAAG,UAAU,CAAC,QAAQ,CAAC,CAAC,MAAM,CAAC,GAAG,CAAC,QAAQ,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,KAAK,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC;IACnF,OAAO,GAAG,QAAQ,CAAC,KAAK,CAAC,CAAC,EAAE,eAAe,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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,CAAC,EAAE,eAAe,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(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"]}
|
package/dist/packages/types.d.ts
CHANGED
|
@@ -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
|
-
|
|
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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D,MAAM,WAAW,kBAAkB;IACjC,KAAK,EAAE,YAAY,CAAC;IACpB,OAAO,CAAC,EAAE,OAAO,aAAa,EAAE,aAAa,CAAC;IAC9C,QAAQ,EAAE,MAAM,CAAC;IACjB,IAAI,CAAC,EAAE,eAAe,CAAC;CACxB;AAED,MAAM,WAAW,aAAa;IAC5B,MAAM,EAAE,MAAM,CAAC;IACf,KAAK,EAAE,YAAY,CAAC;IACpB,KAAK,EAAE,OAAO,CAAC;IACf,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,GAAG,CAAC,EAAE,MAAM,CAAC;IACb,QAAQ,CAAC,EAAE,OAAO,CAAC;IACnB,UAAU,EAAE,MAAM,EAAE,CAAC;IACrB,MAAM,EAAE,MAAM,EAAE,CAAC;CAClB;AAED,MAAM,WAAW,gBAAgB;IAC/B,MAAM,EAAE,aAAa,EAAE,CAAC;IACxB,YAAY,EAAE,aAAa,EAAE,CAAC;CAC/B;AAED,MAAM,WAAW,mBAAoB,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
|
|
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;
|
|
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 {
|
|
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,
|
|
30
|
-
const runtimeWorkspaceRoot = getUnresolvedSandboxPathContext(sandbox,
|
|
31
|
-
|
|
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 =
|
|
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.
|
|
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 =
|
|
251
|
-
const runtimeCwd = runtimeCwdForSandbox(this.options.sandbox, this.options.
|
|
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 =
|
|
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
|
-
|
|
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 =
|
|
576
|
-
const runtimeCwd = runtimeCwdForSandbox(this.options.sandbox, this.options.
|
|
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,
|