@geminixiang/mikan 1.0.0-beta.21 → 1.0.0-beta.22

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 (112) hide show
  1. package/CHANGELOG.md +26 -0
  2. package/dist/adapters/intake.d.ts.map +1 -1
  3. package/dist/adapters/intake.js +5 -0
  4. package/dist/adapters/intake.js.map +1 -1
  5. package/dist/adapters/slack/bot.d.ts.map +1 -1
  6. package/dist/adapters/slack/bot.js +13 -2
  7. package/dist/adapters/slack/bot.js.map +1 -1
  8. package/dist/adapters/slack/types.d.ts +2 -0
  9. package/dist/adapters/slack/types.d.ts.map +1 -1
  10. package/dist/adapters/slack/types.js.map +1 -1
  11. package/dist/agent.d.ts.map +1 -1
  12. package/dist/agent.js +26 -15
  13. package/dist/agent.js.map +1 -1
  14. package/dist/commands/login.js +2 -2
  15. package/dist/commands/login.js.map +1 -1
  16. package/dist/commands/sandbox.js +2 -2
  17. package/dist/commands/sandbox.js.map +1 -1
  18. package/dist/execution-resolver.d.ts +5 -6
  19. package/dist/execution-resolver.d.ts.map +1 -1
  20. package/dist/execution-resolver.js +72 -103
  21. package/dist/execution-resolver.js.map +1 -1
  22. package/dist/harness/index.d.ts +1 -1
  23. package/dist/harness/index.d.ts.map +1 -1
  24. package/dist/harness/index.js.map +1 -1
  25. package/dist/harness/runner.d.ts +4 -0
  26. package/dist/harness/runner.d.ts.map +1 -1
  27. package/dist/harness/runner.js +16 -2
  28. package/dist/harness/runner.js.map +1 -1
  29. package/dist/harness/subagent-runner.d.ts +14 -13
  30. package/dist/harness/subagent-runner.d.ts.map +1 -1
  31. package/dist/harness/subagent-runner.js +105 -19
  32. package/dist/harness/subagent-runner.js.map +1 -1
  33. package/dist/harness/types.d.ts +11 -0
  34. package/dist/harness/types.d.ts.map +1 -1
  35. package/dist/harness/types.js.map +1 -1
  36. package/dist/runtime/conversation-runtime.d.ts.map +1 -1
  37. package/dist/runtime/conversation-runtime.js +23 -79
  38. package/dist/runtime/conversation-runtime.js.map +1 -1
  39. package/dist/runtime/session-lifecycle.d.ts +19 -0
  40. package/dist/runtime/session-lifecycle.d.ts.map +1 -0
  41. package/dist/runtime/session-lifecycle.js +76 -0
  42. package/dist/runtime/session-lifecycle.js.map +1 -0
  43. package/dist/runtime/types.d.ts +5 -0
  44. package/dist/runtime/types.d.ts.map +1 -1
  45. package/dist/runtime/types.js.map +1 -1
  46. package/dist/sandbox/cloudflare.d.ts.map +1 -1
  47. package/dist/sandbox/cloudflare.js +1 -0
  48. package/dist/sandbox/cloudflare.js.map +1 -1
  49. package/dist/sandbox/container.d.ts.map +1 -1
  50. package/dist/sandbox/container.js +1 -0
  51. package/dist/sandbox/container.js.map +1 -1
  52. package/dist/sandbox/firecracker.d.ts.map +1 -1
  53. package/dist/sandbox/firecracker.js +1 -0
  54. package/dist/sandbox/firecracker.js.map +1 -1
  55. package/dist/sandbox/gondolin.d.ts.map +1 -1
  56. package/dist/sandbox/gondolin.js +1 -0
  57. package/dist/sandbox/gondolin.js.map +1 -1
  58. package/dist/sandbox/host.d.ts.map +1 -1
  59. package/dist/sandbox/host.js +1 -0
  60. package/dist/sandbox/host.js.map +1 -1
  61. package/dist/sandbox/identity.d.ts +11 -16
  62. package/dist/sandbox/identity.d.ts.map +1 -1
  63. package/dist/sandbox/identity.js +32 -26
  64. package/dist/sandbox/identity.js.map +1 -1
  65. package/dist/sandbox/image.d.ts.map +1 -1
  66. package/dist/sandbox/image.js +1 -0
  67. package/dist/sandbox/image.js.map +1 -1
  68. package/dist/sandbox/index.d.ts +1 -0
  69. package/dist/sandbox/index.d.ts.map +1 -1
  70. package/dist/sandbox/index.js +6 -0
  71. package/dist/sandbox/index.js.map +1 -1
  72. package/dist/sandbox/types.d.ts +5 -0
  73. package/dist/sandbox/types.d.ts.map +1 -1
  74. package/dist/sandbox/types.js.map +1 -1
  75. package/dist/sessions/session-key.d.ts +9 -0
  76. package/dist/sessions/session-key.d.ts.map +1 -1
  77. package/dist/sessions/session-key.js +50 -2
  78. package/dist/sessions/session-key.js.map +1 -1
  79. package/dist/sessions/store.d.ts.map +1 -1
  80. package/dist/sessions/store.js +36 -8
  81. package/dist/sessions/store.js.map +1 -1
  82. package/dist/tools/sandbox.js +2 -2
  83. package/dist/tools/sandbox.js.map +1 -1
  84. package/dist/tools/subagent-slots.d.ts +3 -3
  85. package/dist/tools/subagent-slots.d.ts.map +1 -1
  86. package/dist/tools/subagent-slots.js +25 -10
  87. package/dist/tools/subagent-slots.js.map +1 -1
  88. package/dist/tools/subagent.d.ts +13 -2
  89. package/dist/tools/subagent.d.ts.map +1 -1
  90. package/dist/tools/subagent.js +16 -16
  91. package/dist/tools/subagent.js.map +1 -1
  92. package/dist/types.d.ts +7 -0
  93. package/dist/types.d.ts.map +1 -1
  94. package/dist/types.js.map +1 -1
  95. package/dist/vault/injection.d.ts +4 -14
  96. package/dist/vault/injection.d.ts.map +1 -1
  97. package/dist/vault/injection.js +5 -2
  98. package/dist/vault/injection.js.map +1 -1
  99. package/dist/vault/types.d.ts +4 -0
  100. package/dist/vault/types.d.ts.map +1 -1
  101. package/dist/vault/types.js.map +1 -1
  102. package/dist/web/admin/portal.js +2 -2
  103. package/dist/web/admin/portal.js.map +1 -1
  104. package/dist/workspace-projection/index.d.ts +5 -0
  105. package/dist/workspace-projection/index.d.ts.map +1 -0
  106. package/dist/workspace-projection/index.js +71 -0
  107. package/dist/workspace-projection/index.js.map +1 -0
  108. package/dist/workspace-projection/types.d.ts +7 -0
  109. package/dist/workspace-projection/types.d.ts.map +1 -0
  110. package/dist/workspace-projection/types.js +2 -0
  111. package/dist/workspace-projection/types.js.map +1 -0
  112. package/package.json +1 -1
@@ -1,10 +1,26 @@
1
- /**
2
- * Runtime actor identity: the one key that names a conversation's vault dir,
3
- * docker container and network, and cloudflare sandbox suffix. Everything
4
- * that needs such a name consumes actorKey(); nothing may re-derive or
5
- * re-sanitize it — two sanitizers with divergent outputs used to make a
6
- * container/vault mismatch a silent wrong-identity bug rather than an error.
7
- */
1
+ import { createHash } from "node:crypto";
2
+ const IDENTITY_HASH_LENGTH = 12;
3
+ export function credentialAuthorizationKey(baseConfig, ids) {
4
+ if (baseConfig.type === "host")
5
+ return identityKey("user", ids.userId);
6
+ if (baseConfig.type === "container")
7
+ return identityKey("container", baseConfig.container);
8
+ return identityKey("conversation", ids.conversationId);
9
+ }
10
+ export function legacyExactCredentialAuthorizationKey(baseConfig, ids) {
11
+ if (baseConfig.type === "host")
12
+ return ids.userId;
13
+ if (baseConfig.type === "container")
14
+ return `container-${baseConfig.container}`;
15
+ return undefined;
16
+ }
17
+ export function runtimeResourceKey(baseConfig, ids) {
18
+ if (baseConfig.type === "container")
19
+ return identityKey("container", baseConfig.container);
20
+ if (baseConfig.type === "host")
21
+ return identityKey("user", ids.userId);
22
+ return identityKey("conversation", ids.conversationId);
23
+ }
8
24
  export function sanitizeIdentitySegment(value) {
9
25
  const sanitized = value
10
26
  .toLowerCase()
@@ -12,25 +28,15 @@ export function sanitizeIdentitySegment(value) {
12
28
  .replace(/^-+|-+$/g, "");
13
29
  return sanitized || "unknown";
14
30
  }
15
- /**
16
- * The actor key for a sandbox config: per-conversation for managed sandboxes
17
- * (image/gondolin/cloudflare/firecracker), the fixed container name for a shared
18
- * container, and the platform user id on the host.
19
- */
20
- export function actorKey(baseConfig, ids) {
21
- if (baseConfig.type === "container") {
22
- return `container-${baseConfig.container}`;
23
- }
24
- if (baseConfig.type === "image" ||
25
- baseConfig.type === "gondolin" ||
26
- baseConfig.type === "cloudflare" ||
27
- baseConfig.type === "firecracker") {
28
- return sanitizeIdentitySegment(ids.conversationId);
29
- }
30
- return ids.userId;
31
+ export function scopeCloudflareSandboxId(baseId, resourceKey) {
32
+ return `${baseId}-${resourceKey}`;
31
33
  }
32
- /** Scope a base cloudflare sandbox id to one actor key. */
33
- export function scopeCloudflareSandboxId(baseId, actorVaultKey) {
34
- return `${baseId}-${sanitizeIdentitySegment(actorVaultKey)}`;
34
+ function identityKey(kind, value) {
35
+ const readable = sanitizeIdentitySegment(value).slice(0, 40).replace(/-+$/g, "") || "unknown";
36
+ const hash = createHash("sha256")
37
+ .update(`${kind}\0${value}`)
38
+ .digest("hex")
39
+ .slice(0, IDENTITY_HASH_LENGTH);
40
+ return `${readable}-${hash}`;
35
41
  }
36
42
  //# sourceMappingURL=identity.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"identity.js","sourceRoot":"","sources":["../../src/sandbox/identity.ts"],"names":[],"mappings":"AAEA;;;;;;GAMG;AACH,MAAM,UAAU,uBAAuB,CAAC,KAAa;IACnD,MAAM,SAAS,GAAG,KAAK;SACpB,WAAW,EAAE;SACb,OAAO,CAAC,aAAa,EAAE,GAAG,CAAC;SAC3B,OAAO,CAAC,UAAU,EAAE,EAAE,CAAC,CAAC;IAC3B,OAAO,SAAS,IAAI,SAAS,CAAC;AAChC,CAAC;AAED;;;;GAIG;AACH,MAAM,UAAU,QAAQ,CACtB,UAAyB,EACzB,GAA+C;IAE/C,IAAI,UAAU,CAAC,IAAI,KAAK,WAAW,EAAE,CAAC;QACpC,OAAO,aAAa,UAAU,CAAC,SAAS,EAAE,CAAC;IAC7C,CAAC;IACD,IACE,UAAU,CAAC,IAAI,KAAK,OAAO;QAC3B,UAAU,CAAC,IAAI,KAAK,UAAU;QAC9B,UAAU,CAAC,IAAI,KAAK,YAAY;QAChC,UAAU,CAAC,IAAI,KAAK,aAAa,EACjC,CAAC;QACD,OAAO,uBAAuB,CAAC,GAAG,CAAC,cAAc,CAAC,CAAC;IACrD,CAAC;IACD,OAAO,GAAG,CAAC,MAAM,CAAC;AACpB,CAAC;AAED,2DAA2D;AAC3D,MAAM,UAAU,wBAAwB,CAAC,MAAc,EAAE,aAAqB;IAC5E,OAAO,GAAG,MAAM,IAAI,uBAAuB,CAAC,aAAa,CAAC,EAAE,CAAC;AAC/D,CAAC","sourcesContent":["import type { SandboxConfig } from \"./types.js\";\n\n/**\n * Runtime actor identity: the one key that names a conversation's vault dir,\n * docker container and network, and cloudflare sandbox suffix. Everything\n * that needs such a name consumes actorKey(); nothing may re-derive or\n * re-sanitize it two sanitizers with divergent outputs used to make a\n * container/vault mismatch a silent wrong-identity bug rather than an error.\n */\nexport function sanitizeIdentitySegment(value: string): string {\n const sanitized = value\n .toLowerCase()\n .replace(/[^a-z0-9]+/g, \"-\")\n .replace(/^-+|-+$/g, \"\");\n return sanitized || \"unknown\";\n}\n\n/**\n * The actor key for a sandbox config: per-conversation for managed sandboxes\n * (image/gondolin/cloudflare/firecracker), the fixed container name for a shared\n * container, and the platform user id on the host.\n */\nexport function actorKey(\n baseConfig: SandboxConfig,\n ids: { userId: string; conversationId: string },\n): string {\n if (baseConfig.type === \"container\") {\n return `container-${baseConfig.container}`;\n }\n if (\n baseConfig.type === \"image\" ||\n baseConfig.type === \"gondolin\" ||\n baseConfig.type === \"cloudflare\" ||\n baseConfig.type === \"firecracker\"\n ) {\n return sanitizeIdentitySegment(ids.conversationId);\n }\n return ids.userId;\n}\n\n/** Scope a base cloudflare sandbox id to one actor key. */\nexport function scopeCloudflareSandboxId(baseId: string, actorVaultKey: string): string {\n return `${baseId}-${sanitizeIdentitySegment(actorVaultKey)}`;\n}\n"]}
1
+ {"version":3,"file":"identity.js","sourceRoot":"","sources":["../../src/sandbox/identity.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AAGzC,MAAM,oBAAoB,GAAG,EAAE,CAAC;AAEhC,MAAM,UAAU,0BAA0B,CACxC,UAAyB,EACzB,GAA+C;IAE/C,IAAI,UAAU,CAAC,IAAI,KAAK,MAAM;QAAE,OAAO,WAAW,CAAC,MAAM,EAAE,GAAG,CAAC,MAAM,CAAC,CAAC;IACvE,IAAI,UAAU,CAAC,IAAI,KAAK,WAAW;QAAE,OAAO,WAAW,CAAC,WAAW,EAAE,UAAU,CAAC,SAAS,CAAC,CAAC;IAC3F,OAAO,WAAW,CAAC,cAAc,EAAE,GAAG,CAAC,cAAc,CA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GAAG,IAAI,KAAK,KAAK,EAAE,CAAC;SAC3B,MAAM,CAAC,KAAK,CAAC;SACb,KAAK,CAAC,CAAC,EAAE,oBAAoB,CAAC,CAAC;IAClC,OAAO,GAAG,QAAQ,IAAI,IAAI,EAAE,CAAC;AAC/B,CAAC","sourcesContent":["import { createHash } from \"node:crypto\";\nimport type { SandboxConfig } from \"./types.js\";\n\nconst IDENTITY_HASH_LENGTH = 12;\n\nexport function credentialAuthorizationKey(\n baseConfig: SandboxConfig,\n ids: { userId: string; conversationId: string },\n): string {\n if (baseConfig.type === \"host\") return identityKey(\"user\", ids.userId);\n if (baseConfig.type === \"container\") return identityKey(\"container\", baseConfig.container);\n return identityKey(\"conversation\", ids.conversationId);\n}\n\nexport function legacyExactCredentialAuthorizationKey(\n baseConfig: SandboxConfig,\n ids: { userId: string; conversationId: string },\n): string | undefined {\n if (baseConfig.type === \"host\") return ids.userId;\n if (baseConfig.type === \"container\") return `container-${baseConfig.container}`;\n return undefined;\n}\n\nexport function runtimeResourceKey(\n baseConfig: SandboxConfig,\n ids: { userId: string; conversationId: string },\n): string {\n if (baseConfig.type === \"container\") return identityKey(\"container\", baseConfig.container);\n if (baseConfig.type === \"host\") return identityKey(\"user\", ids.userId);\n return identityKey(\"conversation\", ids.conversationId);\n}\n\nexport function sanitizeIdentitySegment(value: string): string {\n const sanitized = value\n .toLowerCase()\n .replace(/[^a-z0-9]+/g, \"-\")\n .replace(/^-+|-+$/g, \"\");\n return sanitized || \"unknown\";\n}\n\nexport function scopeCloudflareSandboxId(baseId: string, resourceKey: string): string {\n return `${baseId}-${resourceKey}`;\n}\n\nfunction identityKey(kind: \"user\" | \"conversation\" | \"container\", value: string): string {\n const readable = sanitizeIdentitySegment(value).slice(0, 40).replace(/-+$/g, \"\") || \"unknown\";\n const hash = createHash(\"sha256\")\n .update(`${kind}\\0${value}`)\n .digest(\"hex\")\n .slice(0, IDENTITY_HASH_LENGTH);\n return `${readable}-${hash}`;\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"image.d.ts","sourceRoot":"","sources":["../../src/sandbox/image.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,kBAAkB,EAAE,cAAc,EAAE,MAAM,YAAY,CAAC;AAyBrE,eAAO,MAAM,mBAAmB,EAAE,cAAc,CAAC,kBAAkB,CAIlE,CAAC"}
1
+ {"version":3,"file":"image.d.ts","sourceRoot":"","sources":["../../src/sandbox/image.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,kBAAkB,EAAE,cAAc,EAAE,MAAM,YAAY,CAAC;AAyBrE,eAAO,MAAM,mBAAmB,EAAE,cAAc,CAAC,kBAAkB,CAKlE,CAAC"}
@@ -21,6 +21,7 @@ async function validateImageSandbox(config) {
21
21
  }
22
22
  export const imageSandboxAdapter = {
23
23
  type: "image",
24
+ credentials: { env: true, fileMounts: true },
24
25
  parse: parseImageSandboxArg,
25
26
  validate: validateImageSandbox,
26
27
  };
@@ -1 +1 @@
1
- {"version":3,"file":"image.js","sourceRoot":"","sources":["../../src/sandbox/image.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AAC3C,OAAO,EAAE,UAAU,EAAE,MAAM,YAAY,CAAC;AAExC,SAAS,oBAAoB,CAAC,KAAa;IACzC,IAAI,CAAC,KAAK,CAAC,UAAU,CAAC,QAAQ,CAAC,EAAE,CAAC;QAChC,OAAO,SAAS,CAAC;IACnB,CAAC;IAED,MAAM,KAAK,GAAG,KAAK,CAAC,KAAK,CAAC,QAAQ,CAAC,MAAM,CAAC,CAAC;IAC3C,IAAI,CAAC,KAAK,EAAE,CAAC;QACX,MAAM,IAAI,YAAY,CAAC,qEAAqE,CAAC,CAAC;IAChG,CAAC;IACD,OAAO,EAAE,IAAI,EAAE,OAAO,EAAE,KAAK,EAAE,CAAC;AAClC,CAAC;AAED,KAAK,UAAU,oBAAoB,CAAC,MAA0B;IAC5D,IAAI,CAAC;QACH,MAAM,UAAU,CAAC,QAAQ,EAAE,CAAC,WAAW,CAAC,CAAC,CAAC;IAC5C,CAAC;IAAC,MAAM,CAAC;QACP,MAAM,IAAI,YAAY,CAAC,+CAA+C,CAAC,CAAC;IAC1E,CAAC;IACD,OAAO,CAAC,GAAG,CAAC,6CAA6C,MAAM,CAAC,KAAK,EAAE,CAAC,CAAC;AAC3E,CAAC;AAED,MAAM,CAAC,MAAM,mBAAmB,GAAuC;IACrE,IAAI,EAAE,OAAO;IACb,KAAK,EAAE,oBAAoB;IAC3B,QAAQ,EAAE,oBAAoB;CAC/B,CAAC","sourcesContent":["import type { ImageSandboxConfig, SandboxAdapter } from \"./types.js\";\nimport { SandboxError } from \"./errors.js\";\nimport { execSimple } from \"./utils.js\";\n\nfunction parseImageSandboxArg(value: string): ImageSandboxConfig | undefined {\n if (!value.startsWith(\"image:\")) {\n return undefined;\n }\n\n const image = value.slice(\"image:\".length);\n if (!image) {\n throw new SandboxError(\"Error: image sandbox requires image name (e.g., image:ubuntu:24.04)\");\n }\n return { type: \"image\", image };\n}\n\nasync function validateImageSandbox(config: ImageSandboxConfig): Promise<void> {\n try {\n await execSimple(\"docker\", [\"--version\"]);\n } catch {\n throw new SandboxError(\"Error: Docker is not installed or not in PATH\");\n }\n console.log(` Image auto-provisioning enabled. Image: ${config.image}`);\n}\n\nexport const imageSandboxAdapter: SandboxAdapter<ImageSandboxConfig> = {\n type: \"image\",\n parse: parseImageSandboxArg,\n validate: validateImageSandbox,\n};\n"]}
1
+ {"version":3,"file":"image.js","sourceRoot":"","sources":["../../src/sandbox/image.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AAC3C,OAAO,EAAE,UAAU,EAAE,MAAM,YAAY,CAAC;AAExC,SAAS,oBAAoB,CAAC,KAAa;IACzC,IAAI,CAAC,KAAK,CAAC,UAAU,CAAC,QAAQ,CAAC,EAAE,CAAC;QAChC,OAAO,SAAS,CAAC;IACnB,CAAC;IAED,MAAM,KAAK,GAAG,KAAK,CAAC,KAAK,CAAC,QAAQ,CAAC,MAAM,CAAC,CAAC;IAC3C,IAAI,CAAC,KAAK,EAAE,CAAC;QACX,MAAM,IAAI,YAAY,CAAC,qEAAqE,CAAC,CAAC;IAChG,CAAC;IACD,OAAO,EAAE,IAAI,EAAE,OAAO,EAAE,KAAK,EAAE,CAAC;AAClC,CAAC;AAED,KAAK,UAAU,oBAAoB,CAAC,MAA0B;IAC5D,IAAI,CAAC;QACH,MAAM,UAAU,CAAC,QAAQ,EAAE,CAAC,WAAW,CAAC,CAAC,CAAC;IAC5C,CAAC;IAAC,MAAM,CAAC;QACP,MAAM,IAAI,YAAY,CAAC,+CAA+C,CAAC,CAAC;IAC1E,CAAC;IACD,OAAO,CAAC,GAAG,CAAC,6CAA6C,MAAM,CAAC,KAAK,EAAE,CAAC,CAAC;AAC3E,CAAC;AAED,MAAM,CAAC,MAAM,mBAAmB,GAAuC;IACrE,IAAI,EAAE,OAAO;IACb,WAAW,EAAE,EAAE,GAAG,EAAE,IAAI,EAAE,UAAU,EAAE,IAAI,EAAE;IAC5C,KAAK,EAAE,oBAAoB;IAC3B,QAAQ,EAAE,oBAAoB;CAC/B,CAAC","sourcesContent":["import type { ImageSandboxConfig, SandboxAdapter } from \"./types.js\";\nimport { SandboxError } from \"./errors.js\";\nimport { execSimple } from \"./utils.js\";\n\nfunction parseImageSandboxArg(value: string): ImageSandboxConfig | undefined {\n if (!value.startsWith(\"image:\")) {\n return undefined;\n }\n\n const image = value.slice(\"image:\".length);\n if (!image) {\n throw new SandboxError(\"Error: image sandbox requires image name (e.g., image:ubuntu:24.04)\");\n }\n return { type: \"image\", image };\n}\n\nasync function validateImageSandbox(config: ImageSandboxConfig): Promise<void> {\n try {\n await execSimple(\"docker\", [\"--version\"]);\n } catch {\n throw new SandboxError(\"Error: Docker is not installed or not in PATH\");\n }\n console.log(` Image auto-provisioning enabled. Image: ${config.image}`);\n}\n\nexport const imageSandboxAdapter: SandboxAdapter<ImageSandboxConfig> = {\n type: \"image\",\n credentials: { env: true, fileMounts: true },\n parse: parseImageSandboxArg,\n validate: validateImageSandbox,\n};\n"]}
@@ -10,6 +10,7 @@ export { CloudflareSandboxExecutor, ContainerExecutor, FirecrackerExecutor, Host
10
10
  export { SandboxError } from "./errors.js";
11
11
  declare const sandboxAdapters: readonly [SandboxAdapter<import("./types.js").HostSandboxConfig>, SandboxAdapter<import("./types.js").ContainerSandboxConfig>, SandboxAdapter<import("./types.js").ImageSandboxConfig>, SandboxAdapter<import("./types.js").GondolinSandboxConfig>, SandboxAdapter<import("./types.js").FirecrackerSandboxConfig>, SandboxAdapter<import("./types.js").CloudflareSandboxConfig>];
12
12
  export declare function getSandboxAdapters(): readonly [...typeof sandboxAdapters];
13
+ export declare function getSandboxCredentialCapabilities(type: SandboxConfig["type"]): SandboxAdapter["credentials"];
13
14
  export declare function parseSandboxArg(value: string): SandboxConfig;
14
15
  export declare function validateSandbox(config: SandboxConfig): Promise<void>;
15
16
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/sandbox/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,iBAAiB,EAA2B,MAAM,gBAAgB,CAAC;AAC5E,OAAO,EAAE,mBAAmB,EAA6B,MAAM,kBAAkB,CAAC;AAClF,OAAO,EAAE,yBAAyB,EAA4B,MAAM,iBAAiB,CAAC;AACtF,OAAO,EAAE,YAAY,EAAsB,MAAM,WAAW,CAAC;AAE7D,OAAO,EAAE,gBAAgB,EAA0B,MAAM,eAAe,CAAC;AAGzE,OAAO,EAAE,wBAAwB,EAAE,KAAK,wBAAwB,EAAE,MAAM,yBAAyB,CAAC;AAClG,OAAO,KAAK,EAAE,QAAQ,EAAE,kBAAkB,EAAE,cAAc,EAAE,aAAa,EAAE,MAAM,YAAY,CAAC;AAE9F,YAAY,EACV,uBAAuB,EACvB,WAAW,EACX,UAAU,EACV,QAAQ,EACR,kBAAkB,EAClB,cAAc,EACd,aAAa,GAC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,YAAY,EACV,uBAAuB,EACvB,WAAW,EACX,UAAU,EACV,QAAQ,EACR,kBAAkB,EAClB,cAAc,EACd,aAAa,GACd,MAAM,YAAY,CAAC;AACpB,OAAO,EACL,yBAAyB,EACzB,iBAAiB,EACjB,mBAAmB,EACnB,YAAY,EACZ,gBAAgB,GACjB,CAAC;AACF,OAAO,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AAE3C,QAAA,MAAM,eAAe,kXAOX,CAAC;AAKX,wBAAgB,kBAAkB,IAAI,SAAS,CAAC,GAAG,OAAO,eAAe,CAAC,CAEzE;AAED,wBAAgB,gCAAgC,CAC9C,IAAI,EAAE,aAAa,CAAC,MAAM,CAAC,GAC1B,cAAc,CAAC,aAAa,CAAC,CAI/B;AAED,wBAAgB,eAAe,CAAC,KAAK,EAAE,MAAM,GAAG,aAAa,CAiB5D;AAED,wBAAsB,eAAe,CAAC,MAAM,EAAE,aAAa,GAAG,OAAO,CAAC,IAAI,CAAC,CAO1E;AAED;;GAEG;AACH,wBAAgB,cAAc,CAC5B,MAAM,EAAE,aAAa,EACrB,GAAG,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,EAC5B,WAAW,CAAC,EAAE,MAAM,OAAO,CAAC,IAAI,CAAC,GAChC,QAAQ,CASV;AAED;;;;;GAKG;AACH,wBAAgB,+BAA+B,CAC7C,aAAa,EAAE,aAAa,EAC5B,iBAAiB,EAAE,MAAM,GACxB,kBAAkB,CAMpB"}
@@ -21,6 +21,12 @@ const sandboxAdapterByType = new Map(sandboxAdapters.map((adapter) => [adapter.t
21
21
  export function getSandboxAdapters() {
22
22
  return sandboxAdapters;
23
23
  }
24
+ export function getSandboxCredentialCapabilities(type) {
25
+ const adapter = sandboxAdapterByType.get(type);
26
+ if (!adapter)
27
+ throw new SandboxError(`Error: Unsupported sandbox type '${type}'`);
28
+ return adapter.credentials;
29
+ }
24
30
  export function parseSandboxArg(value) {
25
31
  for (const adapter of sandboxAdapters) {
26
32
  const config = adapter.parse(value);
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/sandbox/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,iBAAiB,EAAE,uBAAuB,EAAE,MAAM,gBAAgB,CAAC;AAC5E,OAAO,EAAE,mBAAmB,EAAE,yBAAyB,EAAE,MAAM,kBAAkB,CAAC;AAClF,OAAO,EAAE,yBAAyB,EAAE,wBAAwB,EAAE,MAAM,iBAAiB,CAAC;AACtF,OAAO,EAAE,YAAY,EAAE,kBAAkB,EAAE,MAAM,WAAW,CAAC;AAC7D,OAAO,EAAE,mBAAmB,EAAE,MAAM,YAAY,CAAC;AACjD,OAAO,EAAE,gBAAgB,EAAE,sBAAsB,EAAE,MAAM,eAAe,CAAC;AACzE,OAAO,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AAC3C,OAAO,EAAE,+BAA+B,EAAE,MAAM,mBAAmB,CAAC;AACpE,OAAO,EAAE,wBAAwB,EAAiC,MAAM,yBAAyB,CAAC;AAYlG,OAAO,EACL,yBAAyB,EACzB,iBAAiB,EACjB,mBAAmB,EACnB,YAAY,EACZ,gBAAgB,GACjB,CAAC;AACF,OAAO,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AAE3C,MAAM,eAAe,GAAG;IACtB,kBAAkB;IAClB,uBAAuB;IACvB,mBAAmB;IACnB,sBAAsB;IACtB,yBAAyB;IACzB,wBAAwB;CAChB,CAAC;AACX,MAAM,oBAAoB,GAAG,IAAI,GAAG,CAClC,eAAe,CAAC,GAAG,CAAC,CAAC,OAAO,EAAE,EAAE,CAAC,CAAC,OAAO,CAAC,IAAI,EAAE,OAAO,CAAC,CAAC,CACZ,CAAC;AAEhD,MAAM,UAAU,kBAAkB;IAChC,OAAO,eAAe,CAAC;AACzB,CAAC;AAED,MAAM,UAAU,eAAe,CAAC,KAAa;IAC3C,KAAK,MAAM,OAAO,IAAI,eAAe,EAAE,CAAC;QACtC,MAAM,MAAM,GAAG,O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,IAAI,KAAK,OAAO,EAAE,CAAC;QACnC,OAAO,+BAA+B,CAAC,iBAAiB,EAAE,YAAY,CAAC,CAAC;IAC1E,CAAC;IAED,OAAO,cAAc,CAAC,aAAa,CAAC,CAAC,cAAc,CAAC,iBAAiB,CAAC,CAAC;AACzE,CAAC","sourcesContent":["import { ContainerExecutor, containerSandboxAdapter } from \"./container.js\";\nimport { FirecrackerExecutor, firecrackerSandboxAdapter } from \"./firecracker.js\";\nimport { CloudflareSandboxExecutor, cloudflareSandboxAdapter } from \"./cloudflare.js\";\nimport { HostExecutor, hostSandboxAdapter } from \"./host.js\";\nimport { imageSandboxAdapter } from \"./image.js\";\nimport { GondolinExecutor, gondolinSandboxAdapter } from \"./gondolin.js\";\nimport { SandboxError } from \"./errors.js\";\nimport { createMountedRuntimePathContext } from \"./path-context.js\";\nexport { configureGondolinRuntime, type GondolinBootstrapOptions } from \"./gondolin-bootstrap.js\";\nimport type { Executor, RuntimePathContext, SandboxAdapter, SandboxConfig } from \"./types.js\";\n\nexport type {\n CloudflareSandboxConfig,\n ExecOptions,\n ExecResult,\n Executor,\n RuntimePathContext,\n SandboxAdapter,\n SandboxConfig,\n} from \"./types.js\";\nexport {\n CloudflareSandboxExecutor,\n ContainerExecutor,\n FirecrackerExecutor,\n HostExecutor,\n GondolinExecutor,\n};\nexport { SandboxError } from \"./errors.js\";\n\nconst sandboxAdapters = [\n hostSandboxAdapter,\n containerSandboxAdapter,\n imageSandboxAdapter,\n gondolinSandboxAdapter,\n firecrackerSandboxAdapter,\n cloudflareSandboxAdapter,\n] as const;\nconst sandboxAdapterByType = new Map(\n sandboxAdapters.map((adapter) => [adapter.type, adapter]),\n) as Map<SandboxConfig[\"type\"], SandboxAdapter>;\n\nexport function getSandboxAdapters(): readonly [...typeof sandboxAdapters] {\n return sandboxAdapters;\n}\n\nexport function parseSandboxArg(value: string): SandboxConfig {\n for (const adapter of sandboxAdapters) {\n const config = adapter.parse(value);\n if (config) {\n return config;\n }\n }\n\n if (value.startsWith(\"docker:\")) {\n throw new SandboxError(\n `Error: '${value}' is not supported. Use 'container:<container-name>' for the shared-container mode or 'image:<image-name>' for mikan-managed per-user containers.`,\n );\n }\n\n throw new SandboxError(\n `Error: Invalid sandbox type '${value}'. Use 'host', 'container:<container-name>', 'image:<image-name>', 'gondolin:default', 'firecracker:<vm-id>:<host-path>', or 'cloudflare:<sandbox-id>'`,\n );\n}\n\nexport async function validateSandbox(config: SandboxConfig): Promise<void> {\n const adapter = sandboxAdapterByType.get(config.type);\n if (!adapter) {\n throw new SandboxError(`Error: Unsupported sandbox type '${config.type}'`);\n }\n\n await adapter.validate?.(config);\n}\n\n/**\n * Create an executor that runs commands on host, in Docker, in a microVM, in a Firecracker VM, or through a Cloudflare sandbox bridge.\n */\nexport function createExecutor(\n config: SandboxConfig,\n env?: Record<string, string>,\n ensureReady?: () => Promise<void>,\n): Executor {\n const adapter = sandboxAdapterByType.get(config.type);\n if (!adapter) {\n throw new SandboxError(`Error: Unsupported sandbox type '${config.type}'`);\n }\n if (!adapter.createExecutor) {\n throw new SandboxError(\"Error: image sandbox must resolve to a concrete container executor\");\n }\n return adapter.createExecutor(config, env, ensureReady);\n}\n\n/**\n * The runtime path context for a sandbox config before an actor-specific\n * executor is resolved. `image` configs are unresolved by nature (the actor\n * decides the concrete container), but their mount layout is fixed, so path\n * mapping is known without resolving.\n */\nexport function getUnresolvedSandboxPathContext(\n sandboxConfig: SandboxConfig,\n hostWorkspaceRoot: string,\n): RuntimePathContext {\n if (sandboxConfig.type === \"image\") {\n return createMountedRuntimePathContext(hostWorkspaceRoot, \"/workspace\");\n }\n\n return createExecutor(sandboxConfig).getPathContext(hostWorkspaceRoot);\n}\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/sandbox/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,iBAAiB,EAAE,uBAAuB,EAAE,MAAM,gBAAgB,CAAC;AAC5E,OAAO,EAAE,mBAAmB,EAAE,yBAAyB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,EAC5B,iBAAyB;IAEzB,IAAI,aAAa,CAAC,IAAI,KAAK,OAAO,EAAE,CAAC;QACnC,OAAO,+BAA+B,CAAC,iBAAiB,EAAE,YAAY,CAAC,CAAC;IAC1E,CAAC;IAED,OAAO,cAAc,CAAC,aAAa,CAAC,CAAC,cAAc,CAAC,iBAAiB,CAAC,CAAC;AACzE,CAAC","sourcesContent":["import { ContainerExecutor, containerSandboxAdapter } from \"./container.js\";\nimport { FirecrackerExecutor, firecrackerSandboxAdapter } from \"./firecracker.js\";\nimport { CloudflareSandboxExecutor, cloudflareSandboxAdapter } from \"./cloudflare.js\";\nimport { HostExecutor, hostSandboxAdapter } from \"./host.js\";\nimport { imageSandboxAdapter } from \"./image.js\";\nimport { GondolinExecutor, gondolinSandboxAdapter } from \"./gondolin.js\";\nimport { SandboxError } from \"./errors.js\";\nimport { createMountedRuntimePathContext } from \"./path-context.js\";\nexport { configureGondolinRuntime, type GondolinBootstrapOptions } from \"./gondolin-bootstrap.js\";\nimport type { Executor, RuntimePathContext, SandboxAdapter, SandboxConfig } from \"./types.js\";\n\nexport type {\n CloudflareSandboxConfig,\n ExecOptions,\n ExecResult,\n Executor,\n RuntimePathContext,\n SandboxAdapter,\n SandboxConfig,\n} from \"./types.js\";\nexport {\n CloudflareSandboxExecutor,\n ContainerExecutor,\n FirecrackerExecutor,\n HostExecutor,\n GondolinExecutor,\n};\nexport { SandboxError } from \"./errors.js\";\n\nconst sandboxAdapters = [\n hostSandboxAdapter,\n containerSandboxAdapter,\n imageSandboxAdapter,\n gondolinSandboxAdapter,\n firecrackerSandboxAdapter,\n cloudflareSandboxAdapter,\n] as const;\nconst sandboxAdapterByType = new Map(\n sandboxAdapters.map((adapter) => [adapter.type, adapter]),\n) as Map<SandboxConfig[\"type\"], SandboxAdapter>;\n\nexport function getSandboxAdapters(): readonly [...typeof sandboxAdapters] {\n return sandboxAdapters;\n}\n\nexport function getSandboxCredentialCapabilities(\n type: SandboxConfig[\"type\"],\n): SandboxAdapter[\"credentials\"] {\n const adapter = sandboxAdapterByType.get(type);\n if (!adapter) throw new SandboxError(`Error: Unsupported sandbox type '${type}'`);\n return adapter.credentials;\n}\n\nexport function parseSandboxArg(value: string): SandboxConfig {\n for (const adapter of sandboxAdapters) {\n const config = adapter.parse(value);\n if (config) {\n return config;\n }\n }\n\n if (value.startsWith(\"docker:\")) {\n throw new SandboxError(\n `Error: '${value}' is not supported. Use 'container:<container-name>' for the shared-container mode or 'image:<image-name>' for mikan-managed per-user containers.`,\n );\n }\n\n throw new SandboxError(\n `Error: Invalid sandbox type '${value}'. Use 'host', 'container:<container-name>', 'image:<image-name>', 'gondolin:default', 'firecracker:<vm-id>:<host-path>', or 'cloudflare:<sandbox-id>'`,\n );\n}\n\nexport async function validateSandbox(config: SandboxConfig): Promise<void> {\n const adapter = sandboxAdapterByType.get(config.type);\n if (!adapter) {\n throw new SandboxError(`Error: Unsupported sandbox type '${config.type}'`);\n }\n\n await adapter.validate?.(config);\n}\n\n/**\n * Create an executor that runs commands on host, in Docker, in a microVM, in a Firecracker VM, or through a Cloudflare sandbox bridge.\n */\nexport function createExecutor(\n config: SandboxConfig,\n env?: Record<string, string>,\n ensureReady?: () => Promise<void>,\n): Executor {\n const adapter = sandboxAdapterByType.get(config.type);\n if (!adapter) {\n throw new SandboxError(`Error: Unsupported sandbox type '${config.type}'`);\n }\n if (!adapter.createExecutor) {\n throw new SandboxError(\"Error: image sandbox must resolve to a concrete container executor\");\n }\n return adapter.createExecutor(config, env, ensureReady);\n}\n\n/**\n * The runtime path context for a sandbox config before an actor-specific\n * executor is resolved. `image` configs are unresolved by nature (the actor\n * decides the concrete container), but their mount layout is fixed, so path\n * mapping is known without resolving.\n */\nexport function getUnresolvedSandboxPathContext(\n sandboxConfig: SandboxConfig,\n hostWorkspaceRoot: string,\n): RuntimePathContext {\n if (sandboxConfig.type === \"image\") {\n return createMountedRuntimePathContext(hostWorkspaceRoot, \"/workspace\");\n }\n\n return createExecutor(sandboxConfig).getPathContext(hostWorkspaceRoot);\n}\n"]}
@@ -88,8 +88,13 @@ export interface ExecResult {
88
88
  stderr: string;
89
89
  code: number;
90
90
  }
91
+ export interface SandboxCredentialCapabilities {
92
+ env: boolean;
93
+ fileMounts: boolean;
94
+ }
91
95
  export interface SandboxAdapter<TConfig extends SandboxConfig = SandboxConfig> {
92
96
  type: TConfig["type"];
97
+ credentials: SandboxCredentialCapabilities;
93
98
  parse(value: string): TConfig | undefined;
94
99
  validate?(config: TConfig): Promise<void>;
95
100
  createExecutor?(config: TConfig, env?: Record<string, string>, ensureReady?: () => Promise<void>): Executor;
@@ -1 +1 @@
1
- {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../src/sandbox/types.ts"],"names":[],"mappings":"AAAA,MAAM,MAAM,aAAa,GACrB,iBAAiB,GACjB,sBAAsB,GACtB,kBAAkB,GAClB,qBAAqB,GACrB,wBAAwB,GACxB,uBAAuB,CAAC;AAE5B,MAAM,WAAW,iBAAiB;IAChC,IAAI,EAAE,MAAM,CAAC;CACd;AAED,MAAM,WAAW,sBAAsB;IACrC,IAAI,EAAE,WAAW,CAAC;IAClB,SAAS,EAAE,MAAM,CAAC;CACnB;AAED,MAAM,WAAW,kBAAkB;IACjC,IAAI,EAAE,OAAO,CAAC;IACd,KAAK,EAAE,MAAM,CAAC;CACf;AAED,MAAM,WAAW,qBAAqB;IACpC,IAAI,EAAE,UAAU,CAAC;IACjB,OAAO,EAAE,SAAS,GAAG,QAAQ,CAAC;IAC9B,4EAA4E;IAC5E,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,aAAa,CAAC,EAAE,MAAM,CAAC;IACvB,MAAM,CAAC,EAAE,KAAK,CAAC;QAAE,MAAM,EAAE,MAAM,CAAC;QAAC,MAAM,EAAE,MAAM,CAAA;KAAE,CAAC,CAAC;IACnD,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,WAAW,CAAC,EAAE,MAAM,CAAC;CACtB;AAED,MAAM,WAAW,wBAAwB;IACvC,IAAI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MAAM,CAAC;IAC1B,yEAAyE;IACzE,oBAAoB,EAAE,MAAM,CAAC;IAC7B,oFAAoF;IACpF,iBAAiB,CAAC,EAAE,CAAC,WAAW,EAAE,MAAM,KAAK,MAAM,CAAC;CACrD;AAED,MAAM,WAAW,WAAW;IAC1B,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,MAAM,CAAC,EAAE,WAAW,CAAC;CACtB;AAED,MAAM,WAAW,UAAU;IACzB,MAAM,EAAE,MAAM,CAAC;IACf,MAAM,EAAE,MAAM,CAAC;IACf,IAAI,EAAE,MAAM,CAAC;CACd;AAED,MAAM,WAAW,6BAA6B;IAC5C,GAAG,EAAE,OAAO,CAAC;IACb,UAAU,EAAE,OAAO,CAAC;CACrB;AAED,MAAM,WAAW,cAAc,CAAC,OAAO,SAAS,aAAa,GAAG,aAAa;IAC3E,IAAI,EAAE,OAAO,CAAC,MAAM,CAAC,CAAC;IACtB,WAAW,EAAE,6BAA6B,CAAC;IAC3C,KAAK,CAAC,KAAK,EAAE,MAAM,GAAG,OAAO,GAAG,SAAS,CAAC;IAC1C,QAAQ,CAAC,CAAC,MAAM,EAAE,OAAO,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;IAC1C,cAAc,CAAC,CACb,MAAM,EAAE,OAAO,EACf,GAAG,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,EAC5B,WAAW,CAAC,EAAE,MAAM,OAAO,CAAC,IAAI,CAAC,GAChC,QAAQ,CAAC;CACb"}
@@ -1 +1 @@
1
- {"version":3,"file":"types.js","sourceRoot":"","sources":["../../src/sandbox/types.ts"],"names":[],"mappings":"","sourcesContent":["export type SandboxConfig =\n | HostSandboxConfig\n | ContainerSandboxConfig\n | ImageSandboxConfig\n | GondolinSandboxConfig\n | FirecrackerSandboxConfig\n | CloudflareSandboxConfig;\n\nexport interface HostSandboxConfig {\n type: \"host\";\n}\n\nexport interface ContainerSandboxConfig {\n type: \"container\";\n container: string;\n}\n\nexport interface ImageSandboxConfig {\n type: \"image\";\n image: string;\n}\n\nexport interface GondolinSandboxConfig {\n type: \"gondolin\";\n profile: \"default\" | \"remote\";\n /** Local-only runtime details supplied after actor/workspace resolution. */\n image?: string;\n workspacePath?: string;\n mounts?: Array<{ source: string; target: string }>;\n instanceId?: string;\n resourceKey?: string;\n}\n\nexport interface FirecrackerSandboxConfig {\n type: \"firecracker\";\n vmId: string;\n hostPath: string;\n sshUser?: string;\n sshPort?: number;\n}\n\nexport interface CloudflareSandboxConfig {\n type: \"cloudflare\";\n sandboxId: string;\n}\n\nexport interface Executor {\n /**\n * Execute a bash command.\n */\n exec(command: string, options?: ExecOptions): Promise<ExecResult>;\n\n /**\n * Read a runtime file as UTF-8 text. The executor owns the transport, so\n * file contents never pass through shell argv or extra shell parse layers.\n */\n readFile(path: string, options?: ExecOptions): Promise<string>;\n\n /**\n * Read a runtime file as base64 (for binary content, e.g. images). Same\n * transport ownership as readFile.\n */\n readFileBase64(path: string, options?: ExecOptions): Promise<string>;\n\n /**\n * Write a runtime file, creating parent directories and replacing via a\n * staging file so an aborted write never truncates the target. Like\n * readFile, transport is the executor's concern — content must survive\n * arbitrary quoting and ARG_MAX limits.\n */\n writeFile(path: string, content: string, options?: ExecOptions): Promise<void>;\n\n /**\n * Get the workspace path prefix for this executor.\n * Host: returns the actual path.\n * Container/Firecracker: returns /workspace.\n */\n getWorkspacePath(hostPath: string): string;\n\n /**\n * Return explicit host/control-plane/runtime path semantics for this executor.\n */\n getPathContext(hostWorkspaceRoot: string): RuntimePathContext;\n\n /**\n * Get the current sandbox config used by this executor.\n */\n getSandboxConfig(): SandboxConfig;\n}\n\nexport interface RuntimePathContext {\n /** Host-side workspace root used by mikan's control plane. */\n hostWorkspaceRoot: string;\n /** Workspace root as seen by bash/read/write/edit inside the runtime. */\n runtimeWorkspaceRoot: string;\n /** Translate a runtime path back to a host path when the runtime is host-backed. */\n runtimeToHostPath?: (runtimePath: string) => string;\n}\n\nexport interface ExecOptions {\n timeout?: number;\n signal?: AbortSignal;\n}\n\nexport interface ExecResult {\n stdout: string;\n stderr: string;\n code: number;\n}\n\nexport interface SandboxAdapter<TConfig extends SandboxConfig = SandboxConfig> {\n type: TConfig[\"type\"];\n parse(value: string): TConfig | undefined;\n validate?(config: TConfig): Promise<void>;\n createExecutor?(\n config: TConfig,\n env?: Record<string, string>,\n ensureReady?: () => Promise<void>,\n ): Executor;\n}\n"]}
1
+ {"version":3,"file":"types.js","sourceRoot":"","sources":["../../src/sandbox/types.ts"],"names":[],"mappings":"","sourcesContent":["export type SandboxConfig =\n | HostSandboxConfig\n | ContainerSandboxConfig\n | ImageSandboxConfig\n | GondolinSandboxConfig\n | FirecrackerSandboxConfig\n | CloudflareSandboxConfig;\n\nexport interface HostSandboxConfig {\n type: \"host\";\n}\n\nexport interface ContainerSandboxConfig {\n type: \"container\";\n container: string;\n}\n\nexport interface ImageSandboxConfig {\n type: \"image\";\n image: string;\n}\n\nexport interface GondolinSandboxConfig {\n type: \"gondolin\";\n profile: \"default\" | \"remote\";\n /** Local-only runtime details supplied after actor/workspace resolution. */\n image?: string;\n workspacePath?: string;\n mounts?: Array<{ source: string; target: string }>;\n instanceId?: string;\n resourceKey?: string;\n}\n\nexport interface FirecrackerSandboxConfig {\n type: \"firecracker\";\n vmId: string;\n hostPath: string;\n sshUser?: string;\n sshPort?: number;\n}\n\nexport interface CloudflareSandboxConfig {\n type: \"cloudflare\";\n sandboxId: string;\n}\n\nexport interface Executor {\n /**\n * Execute a bash command.\n */\n exec(command: string, options?: ExecOptions): Promise<ExecResult>;\n\n /**\n * Read a runtime file as UTF-8 text. The executor owns the transport, so\n * file contents never pass through shell argv or extra shell parse layers.\n */\n readFile(path: string, options?: ExecOptions): Promise<string>;\n\n /**\n * Read a runtime file as base64 (for binary content, e.g. images). Same\n * transport ownership as readFile.\n */\n readFileBase64(path: string, options?: ExecOptions): Promise<string>;\n\n /**\n * Write a runtime file, creating parent directories and replacing via a\n * staging file so an aborted write never truncates the target. Like\n * readFile, transport is the executor's concern — content must survive\n * arbitrary quoting and ARG_MAX limits.\n */\n writeFile(path: string, content: string, options?: ExecOptions): Promise<void>;\n\n /**\n * Get the workspace path prefix for this executor.\n * Host: returns the actual path.\n * Container/Firecracker: returns /workspace.\n */\n getWorkspacePath(hostPath: string): string;\n\n /**\n * Return explicit host/control-plane/runtime path semantics for this executor.\n */\n getPathContext(hostWorkspaceRoot: string): RuntimePathContext;\n\n /**\n * Get the current sandbox config used by this executor.\n */\n getSandboxConfig(): SandboxConfig;\n}\n\nexport interface RuntimePathContext {\n /** Host-side workspace root used by mikan's control plane. */\n hostWorkspaceRoot: string;\n /** Workspace root as seen by bash/read/write/edit inside the runtime. */\n runtimeWorkspaceRoot: string;\n /** Translate a runtime path back to a host path when the runtime is host-backed. */\n runtimeToHostPath?: (runtimePath: string) => string;\n}\n\nexport interface ExecOptions {\n timeout?: number;\n signal?: AbortSignal;\n}\n\nexport interface ExecResult {\n stdout: string;\n stderr: string;\n code: number;\n}\n\nexport interface SandboxCredentialCapabilities {\n env: boolean;\n fileMounts: boolean;\n}\n\nexport interface SandboxAdapter<TConfig extends SandboxConfig = SandboxConfig> {\n type: TConfig[\"type\"];\n credentials: SandboxCredentialCapabilities;\n parse(value: string): TConfig | undefined;\n validate?(config: TConfig): Promise<void>;\n createExecutor?(\n config: TConfig,\n env?: Record<string, string>,\n ensureReady?: () => Promise<void>,\n ): Executor;\n}\n"]}
@@ -11,8 +11,17 @@
11
11
  * asserted here at every derivation instead of being assumed everywhere.
12
12
  */
13
13
  export declare function assertConversationId(conversationId: string): string;
14
+ /** Validate the opaque scoped suffix without changing its platform value. */
15
+ export declare function assertSessionSuffix(suffix: string): string;
14
16
  /** Build a scoped thread session key. */
15
17
  export declare function makeThreadSessionKey(conversationId: string, suffix: string): string;
18
+ /**
19
+ * Validate that a platform-computed session key belongs to its conversation.
20
+ * The key may be the bare conversation id or one of that conversation's
21
+ * scoped keys; callers must not be able to select another conversation's
22
+ * runtime/cache entry.
23
+ */
24
+ export declare function assertSessionKeyBelongsToConversation(sessionKey: string, conversationId: string): string;
16
25
  /**
17
26
  * The runtime fallback: honor a platform-computed session key, otherwise
18
27
  * scope the event to its thread (or to itself for thread-starting messages).
@@ -1 +1 @@
1
- {"version":3,"file":"session-key.d.ts","sourceRoot":"","sources":["../../src/sessions/session-key.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;GAWG;AAEH,wBAAgB,oBAAoB,CAAC,cAAc,EAAE,MAAM,GAAG,MAAM,CAQnE;AAED,yCAAyC;AACzC,wBAAgB,oBAAoB,CAAC,cAAc,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,GAAG,MAAM,CAEnF;AAED;;;GAGG;AACH,wBAAgB,gBAAgB,CAAC,KAAK,EAAE;IACtC,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,cAAc,EAAE,MAAM,CAAC;IACvB,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,EAAE,EAAE,MAAM,CAAC;CACZ,GAAG,MAAM,CAIT;AAED,wBAAgB,kBAAkB,CAAC,UAAU,EAAE,MAAM,GAAG,OAAO,CAE9D;AAED,0EAA0E;AAC1E,wBAAgB,gBAAgB,CAAC,UAAU,EAAE,MAAM,GAAG,MAAM,CAG3D;AAED,8EAA8E;AAC9E,wBAAgB,cAAc,CAAC,UAAU,EAAE,MAAM,GAAG,MAAM,GAAG,IAAI,CAGhE"}
1
+ {"version":3,"file":"session-key.d.ts","sourceRoot":"","sources":["../../src/sessions/session-key.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;GAWG;AA0BH,wBAAgB,oBAAoB,CAAC,cAAc,EAAE,MAAM,GAAG,MAAM,CASnE;AAED,6EAA6E;AAC7E,wBAAgB,mBAAmB,CAAC,MAAM,EAAE,MAAM,GAAG,MAAM,CAE1D;AAED,yCAAyC;AACzC,wBAAgB,oBAAoB,CAAC,cAAc,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,GAAG,MAAM,CAEnF;AAED;;;;;GAKG;AACH,wBAAgB,qCAAqC,CACnD,UAAU,EAAE,MAAM,EAClB,cAAc,EAAE,MAAM,GACrB,MAAM,CAYR;AAED;;;GAGG;AACH,wBAAgB,gBAAgB,CAAC,KAAK,EAAE;IACtC,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,cAAc,EAAE,MAAM,CAAC;IACvB,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,EAAE,EAAE,MAAM,CAAC;CACZ,GAAG,MAAM,CAKT;AAED,wBAAgB,kBAAkB,CAAC,UAAU,EAAE,MAAM,GAAG,OAAO,CAE9D;AAED,0EAA0E;AAC1E,wBAAgB,gBAAgB,CAAC,UAAU,EAAE,MAAM,GAAG,MAAM,CAG3D;AAED,8EAA8E;AAC9E,wBAAgB,cAAc,CAAC,UAAU,EAAE,MAAM,GAAG,MAAM,GAAG,IAAI,CAGhE"}
@@ -10,23 +10,71 @@
10
10
  * only works because conversation ids never contain ":" — that invariant is
11
11
  * asserted here at every derivation instead of being assumed everywhere.
12
12
  */
13
+ /** Characters that can change host path structure or make identity logs ambiguous. */
14
+ const PATH_SEPARATOR_PATTERN = /[\\/]/;
15
+ function containsControlCharacter(value) {
16
+ for (const character of value) {
17
+ const codePoint = character.codePointAt(0);
18
+ if (codePoint <= 0x1f || codePoint === 0x7f)
19
+ return true;
20
+ }
21
+ return false;
22
+ }
23
+ function assertSafeIdentityPart(value, label) {
24
+ if (!value || value === "." || value === "..") {
25
+ throw new Error(`${label} must be a non-empty identity segment (got ${JSON.stringify(value)})`);
26
+ }
27
+ if (PATH_SEPARATOR_PATTERN.test(value)) {
28
+ throw new Error(`${label} must not contain path separators (got ${JSON.stringify(value)})`);
29
+ }
30
+ if (containsControlCharacter(value)) {
31
+ throw new Error(`${label} must not contain control characters (got ${JSON.stringify(value)})`);
32
+ }
33
+ return value;
34
+ }
13
35
  export function assertConversationId(conversationId) {
36
+ assertSafeIdentityPart(conversationId, "Conversation id");
14
37
  if (conversationId.includes(":")) {
15
38
  throw new Error(`Conversation id must not contain ":" (got ${JSON.stringify(conversationId)}); ` +
16
39
  "the session-key grammar reserves it for thread suffixes");
17
40
  }
18
41
  return conversationId;
19
42
  }
43
+ /** Validate the opaque scoped suffix without changing its platform value. */
44
+ export function assertSessionSuffix(suffix) {
45
+ return assertSafeIdentityPart(suffix, "Session suffix");
46
+ }
20
47
  /** Build a scoped thread session key. */
21
48
  export function makeThreadSessionKey(conversationId, suffix) {
22
- return `${assertConversationId(conversationId)}:${suffix}`;
49
+ return `${assertConversationId(conversationId)}:${assertSessionSuffix(suffix)}`;
50
+ }
51
+ /**
52
+ * Validate that a platform-computed session key belongs to its conversation.
53
+ * The key may be the bare conversation id or one of that conversation's
54
+ * scoped keys; callers must not be able to select another conversation's
55
+ * runtime/cache entry.
56
+ */
57
+ export function assertSessionKeyBelongsToConversation(sessionKey, conversationId) {
58
+ const expectedConversationId = assertConversationId(conversationId);
59
+ const actualConversationId = conversationIdOf(sessionKey);
60
+ if (actualConversationId !== expectedConversationId) {
61
+ throw new Error(`Session key ${JSON.stringify(sessionKey)} does not belong to conversation ` +
62
+ JSON.stringify(conversationId));
63
+ }
64
+ const suffix = threadSuffixOf(sessionKey);
65
+ if (suffix !== null)
66
+ assertSessionSuffix(suffix);
67
+ return sessionKey;
23
68
  }
24
69
  /**
25
70
  * The runtime fallback: honor a platform-computed session key, otherwise
26
71
  * scope the event to its thread (or to itself for thread-starting messages).
27
72
  */
28
73
  export function deriveSessionKey(event) {
29
- return (event.sessionKey ?? makeThreadSessionKey(event.conversationId, event.thread_ts ?? event.ts));
74
+ if (event.sessionKey !== undefined) {
75
+ return assertSessionKeyBelongsToConversation(event.sessionKey, event.conversationId);
76
+ }
77
+ return makeThreadSessionKey(event.conversationId, event.thread_ts ?? event.ts);
30
78
  }
31
79
  export function isThreadSessionKey(sessionKey) {
32
80
  return sessionKey.includes(":");
@@ -1 +1 @@
1
- {"version":3,"file":"session-key.js","sourceRoot":"","sources":["../../src/sessions/session-key.ts"],"names":[],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SAAS,GAAG,CAAC,CAAC,CAAC;AACnE,CAAC","sourcesContent":["/**\n * The session-key grammar. A session key is the conversation-scoped runtime\n * identity used to serialize and resume work (see CONTEXT.md):\n *\n * `conversationId` — the persistent conversation session\n * `conversationId:suffix` — a scoped thread session (suffix = thread\n * ts / message id, opaque to this module)\n *\n * This module owns the convention; nothing else may split on \":\". The grammar\n * only works because conversation ids never contain \":\" — that invariant is\n * asserted here at every derivation instead of being assumed everywhere.\n */\n\nexport function assertConversationId(conversationId: string): string {\n if (conversationId.includes(\":\")) {\n throw new Error(\n `Conversation id must not contain \":\" (got ${JSON.stringify(conversationId)}); ` +\n \"the session-key grammar reserves it for thread suffixes\",\n );\n }\n return conversationId;\n}\n\n/** Build a scoped thread session key. */\nexport function makeThreadSessionKey(conversationId: string, suffix: string): string {\n return `${assertConversationId(conversationId)}:${suffix}`;\n}\n\n/**\n * The runtime fallback: honor a platform-computed session key, otherwise\n * scope the event to its thread (or to itself for thread-starting messages).\n */\nexport function deriveSessionKey(event: {\n sessionKey?: string;\n conversationId: string;\n thread_ts?: string;\n ts: string;\n}): string {\n return (\n event.sessionKey ?? makeThreadSessionKey(event.conversationId, event.thread_ts ?? event.ts)\n );\n}\n\nexport function isThreadSessionKey(sessionKey: string): boolean {\n return sessionKey.includes(\":\");\n}\n\n/** The conversation a session key belongs to (identity for bare keys). */\nexport function conversationIdOf(sessionKey: string): string {\n const separator = sessionKey.indexOf(\":\");\n return separator === -1 ? sessionKey : sessionKey.slice(0, separator);\n}\n\n/** The thread suffix of a scoped key, or null for a bare conversation key. */\nexport function threadSuffixOf(sessionKey: string): string | null {\n const separator = sessionKey.indexOf(\":\");\n return separator === -1 ? null : sessionKey.slice(separator + 1);\n}\n"]}
1
+ {"version":3,"file":"session-key.js","sourceRoot":"","sources":["../../src/sessions/session-key.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;GAWG;AAEH,sFAAsF;AACtF,MAAM,sBAAsB,GAAG,OAAO,CAAC;AAEvC,SAA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AAC1E,MAAM,UAAU,gBAAgB,CAAC,UAAkB;IACjD,MAAM,SAAS,GAAG,UAAU,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC;IAC1C,OAAO,SAAS,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,UAAU,CAAC,CAAC,CAAC,UAAU,CAAC,KAAK,CAAC,CAAC,EAAE,SAAS,CAAC,CAAC;AACxE,CAAC;AAED,8EAA8E;AAC9E,MAAM,UAAU,cAAc,CAAC,UAAkB;IAC/C,MAAM,SAAS,GAAG,UAAU,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC;IAC1C,OAAO,SAAS,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,UAAU,CAAC,KAAK,CAAC,SAAS,GAAG,CAAC,CAAC,CAAC;AACnE,CAAC","sourcesContent":["/**\n * The session-key grammar. A session key is the conversation-scoped runtime\n * identity used to serialize and resume work (see CONTEXT.md):\n *\n * `conversationId` — the persistent conversation session\n * `conversationId:suffix` — a scoped thread session (suffix = thread\n * ts / message id, opaque to this module)\n *\n * This module owns the convention; nothing else may split on \":\". The grammar\n * only works because conversation ids never contain \":\" — that invariant is\n * asserted here at every derivation instead of being assumed everywhere.\n */\n\n/** Characters that can change host path structure or make identity logs ambiguous. */\nconst PATH_SEPARATOR_PATTERN = /[\\\\/]/;\n\nfunction containsControlCharacter(value: string): boolean {\n for (const character of value) {\n const codePoint = character.codePointAt(0)!;\n if (codePoint <= 0x1f || codePoint === 0x7f) return true;\n }\n return false;\n}\n\nfunction assertSafeIdentityPart(value: string, label: string): string {\n if (!value || value === \".\" || value === \"..\") {\n throw new Error(`${label} must be a non-empty identity segment (got ${JSON.stringify(value)})`);\n }\n if (PATH_SEPARATOR_PATTERN.test(value)) {\n throw new Error(`${label} must not contain path separators (got ${JSON.stringify(value)})`);\n }\n if (containsControlCharacter(value)) {\n throw new Error(`${label} must not contain control characters (got ${JSON.stringify(value)})`);\n }\n return value;\n}\n\nexport function assertConversationId(conversationId: string): string {\n assertSafeIdentityPart(conversationId, \"Conversation id\");\n if (conversationId.includes(\":\")) {\n throw new Error(\n `Conversation id must not contain \":\" (got ${JSON.stringify(conversationId)}); ` +\n \"the session-key grammar reserves it for thread suffixes\",\n );\n }\n return conversationId;\n}\n\n/** Validate the opaque scoped suffix without changing its platform value. */\nexport function assertSessionSuffix(suffix: string): string {\n return assertSafeIdentityPart(suffix, \"Session suffix\");\n}\n\n/** Build a scoped thread session key. */\nexport function makeThreadSessionKey(conversationId: string, suffix: string): string {\n return `${assertConversationId(conversationId)}:${assertSessionSuffix(suffix)}`;\n}\n\n/**\n * Validate that a platform-computed session key belongs to its conversation.\n * The key may be the bare conversation id or one of that conversation's\n * scoped keys; callers must not be able to select another conversation's\n * runtime/cache entry.\n */\nexport function assertSessionKeyBelongsToConversation(\n sessionKey: string,\n conversationId: string,\n): string {\n const expectedConversationId = assertConversationId(conversationId);\n const actualConversationId = conversationIdOf(sessionKey);\n if (actualConversationId !== expectedConversationId) {\n throw new Error(\n `Session key ${JSON.stringify(sessionKey)} does not belong to conversation ` +\n JSON.stringify(conversationId),\n );\n }\n const suffix = threadSuffixOf(sessionKey);\n if (suffix !== null) assertSessionSuffix(suffix);\n return sessionKey;\n}\n\n/**\n * The runtime fallback: honor a platform-computed session key, otherwise\n * scope the event to its thread (or to itself for thread-starting messages).\n */\nexport function deriveSessionKey(event: {\n sessionKey?: string;\n conversationId: string;\n thread_ts?: string;\n ts: string;\n}): string {\n if (event.sessionKey !== undefined) {\n return assertSessionKeyBelongsToConversation(event.sessionKey, event.conversationId);\n }\n return makeThreadSessionKey(event.conversationId, event.thread_ts ?? event.ts);\n}\n\nexport function isThreadSessionKey(sessionKey: string): boolean {\n return sessionKey.includes(\":\");\n}\n\n/** The conversation a session key belongs to (identity for bare keys). */\nexport function conversationIdOf(sessionKey: string): string {\n const separator = sessionKey.indexOf(\":\");\n return separator === -1 ? sessionKey : sessionKey.slice(0, separator);\n}\n\n/** The thread suffix of a scoped key, or null for a bare conversation key. */\nexport function threadSuffixOf(sessionKey: string): string | null {\n const separator = sessionKey.indexOf(\":\");\n return separator === -1 ? null : sessionKey.slice(separator + 1);\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"store.d.ts","sourceRoot":"","sources":["../../src/sessions/store.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,YAAY,EAAE,MAAM,qBAAqB,CAAC;AAKnD,YAAY,EAAE,oBAAoB,EAAE,iBAAiB,EAAE,MAAM,YAAY,CAAC;AAE1E;;;;GAIG;AACH,wBAAgB,oBAAoB,CAAC,UAAU,EAAE,MAAM,GAAG,MAAM,CAE/D;AAED;;;;GAIG;AACH,wBAAgB,kBAAkB,CAAC,UAAU,EAAE,MAAM,GAAG,MAAM,CAI7D;AAED;;;GAGG;AACH,wBAAgB,yBAAyB,CAAC,UAAU,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,GAAG,MAAM,CAIjF;AAED;;;GAGG;AACH,wBAAgB,kBAAkB,CAAC,WAAW,EAAE,MAAM,GAAG,MAAM,CAE9D;AAED;;;GAGG;AACH,wBAAgB,oBAAoB,CAAC,UAAU,EAAE,MAAM,GAAG,MAAM,CAE/D;AAED;;;;;;GAMG;AACH,wBAAgB,oBAAoB,CAAC,UAAU,EAAE,MAAM,GAAG,MAAM,CAO/D;AAED;;;;GAIG;AACH,wBAAgB,wBAAwB,CAAC,UAAU,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,GAAG,MAAM,CAOhF;AAED;;;GAGG;AACH,wBAAgB,kBAAkB,CAAC,WAAW,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,GAAG,YAAY,CAMjF;AAaD;;GAEG;AACH,wBAAgB,8BAA8B,CAAC,WAAW,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,GAAG,MAAM,CAGvF;AASD;;GAEG;AACH,wBAAgB,oBAAoB,CAAC,UAAU,EAAE,MAAM,EAAE,UAAU,EAAE,MAAM,GAAG,MAAM,C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MAAM,EAAE,GAAG,EAAE,MAAM,GAAG,MAAM,CAGvF;AASD;;GAEG;AACH,wBAAgB,oBAAoB,CAAC,UAAU,EAAE,MAAM,EAAE,UAAU,EAAE,MAAM,GAAG,MAAM,CAGnF;AA8DD;;;GAGG;AACH,wBAAgB,wBAAwB,CAAC,UAAU,EAAE,MAAM,GAAG,MAAM,GAAG,IAAI,CAI1E;AAED;;;GAGG;AACH,wBAAgB,uBAAuB,CAAC,WAAW,EAAE,MAAM,GAAG,MAAM,GAAG,IAAI,CAE1E;AAED;;;GAGG;AACH,wBAAgB,yBAAyB,CAAC,UAAU,EAAE,MAAM,GAAG,MAAM,GAAG,IAAI,CAE3E"}
@@ -1,11 +1,11 @@
1
1
  import { randomUUID } from "crypto";
2
- import { existsSync, mkdirSync, rmSync } from "fs";
3
- import { basename, dirname, join } from "path";
2
+ import { lstatSync, mkdirSync, rmSync } from "fs";
3
+ import { basename, dirname, join, relative, resolve, sep } from "path";
4
4
  import { SessionStore } from "../harness/index.js";
5
5
  import { isRecord, parseJsonValue, readTextFileIfExists } from "../utils/file-guards.js";
6
6
  import { atomicWritePrivateFile } from "../utils/fs-atomic.js";
7
7
  import { isPlatformHistorySession } from "./metadata.js";
8
- import { threadSuffixOf } from "./session-key.js";
8
+ import { assertSessionSuffix, threadSuffixOf } from "./session-key.js";
9
9
  /**
10
10
  * Returns the shared session directory for a conversation.
11
11
  * Channel sessions use a current pointer within this directory.
@@ -47,7 +47,21 @@ export function extractSessionUuid(sessionFile) {
47
47
  * "channelId:threadId" → "threadId", "channelId" → "channelId"
48
48
  */
49
49
  export function extractSessionSuffix(sessionKey) {
50
- return threadSuffixOf(sessionKey) ?? sessionKey;
50
+ return assertSessionSuffix(threadSuffixOf(sessionKey) ?? sessionKey);
51
+ }
52
+ /**
53
+ * Resolve one child path and prove it remains inside its owning directory.
54
+ * Identity validation is the first guard; containment is defense in depth for
55
+ * every session path derived from platform-controlled values.
56
+ */
57
+ function resolveChildPath(root, child) {
58
+ const resolvedRoot = resolve(root);
59
+ const resolvedChild = resolve(resolvedRoot, child);
60
+ const relation = relative(resolvedRoot, resolvedChild);
61
+ if (!relation || relation === ".." || relation.startsWith(`..${sep}`)) {
62
+ throw new Error(`Session path escapes its owning directory: ${JSON.stringify(child)}`);
63
+ }
64
+ return resolvedChild;
51
65
  }
52
66
  /**
53
67
  * Creates an empty timestamped file and updates the "current" pointer.
@@ -113,7 +127,16 @@ function writeSessionHeader(sessionFile, cwd, sessionId = randomUUID()) {
113
127
  * Returns the fixed session file path for a Slack thread.
114
128
  */
115
129
  export function getThreadSessionFile(channelDir, sessionKey) {
116
- return join(getChannelSessionDir(channelDir), `${extractSessionSuffix(sessionKey)}.jsonl`);
130
+ const sessionDir = getChannelSessionDir(channelDir);
131
+ return resolveChildPath(sessionDir, `${extractSessionSuffix(sessionKey)}.jsonl`);
132
+ }
133
+ function isRegularSessionFile(sessionFile) {
134
+ try {
135
+ return lstatSync(sessionFile).isFile();
136
+ }
137
+ catch {
138
+ return false;
139
+ }
117
140
  }
118
141
  function hasSessionHeader(sessionFile) {
119
142
  try {
@@ -158,7 +181,12 @@ function getCurrentSessionPath(sessionDir) {
158
181
  const filename = readTextFileIfExists(pointerFile)?.trim();
159
182
  if (!filename)
160
183
  return null;
161
- return join(sessionDir, filename);
184
+ try {
185
+ return resolveChildPath(sessionDir, filename);
186
+ }
187
+ catch {
188
+ return null;
189
+ }
162
190
  }
163
191
  /**
164
192
  * Try to resolve an existing current session file.
@@ -166,7 +194,7 @@ function getCurrentSessionPath(sessionDir) {
166
194
  */
167
195
  export function tryResolveCurrentSession(sessionDir) {
168
196
  const fullPath = getCurrentSessionPath(sessionDir);
169
- if (fullPath && existsSync(fullPath) && hasSessionHeader(fullPath))
197
+ if (fullPath && isRegularSessionFile(fullPath) && hasSessionHeader(fullPath))
170
198
  return fullPath;
171
199
  return null;
172
200
  }
@@ -175,7 +203,7 @@ export function tryResolveCurrentSession(sessionDir) {
175
203
  * Returns the file path if found, or null if no valid thread session exists yet.
176
204
  */
177
205
  export function tryResolveThreadSession(sessionFile) {
178
- return existsSync(sessionFile) && hasSessionHeader(sessionFile) ? sessionFile : null;
206
+ return isRegularSessionFile(sessionFile) && hasSessionHeader(sessionFile) ? sessionFile : null;
179
207
  }
180
208
  /**
181
209
  * Resolve the channel's current session file path.
@@ -1 +1 @@
1
- {"version":3,"file":"store.js","sourceRoot":"","sources":["../../src/sessions/store.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,QAAQ,CAAC;AACpC,OAAO,EAAE,UAAU,EAAE,SAAS,EAAE,MAAM,EAAE,MAAM,IAAI,CAAC;AACnD,OAAO,EAAE,QAAQ,EAAE,OAAO,EAAE,IAAI,EAAE,MAAM,MAAM,CAAC;AAC/C,OAAO,EAAE,YAAY,EAAE,MAAM,qBAAqB,CAAC;AACnD,OAAO,EAAE,QAAQ,EAAE,cAAc,EAAE,oBAAoB,EAAE,MAAM,yBAAyB,CAAC;AACzF,OAAO,EAAE,sBAAsB,EAAE,MAAM,uBAAuB,CAAC;AAC/D,OAAO,EAAE,wBAAwB,EAAE,MAAM,eAAe,CAAC;AACzD,OAAO,EAAE,cAAc,EAAE,MAAM,kBAAkB,CAAC;AAGlD;;;;GAIG;AACH,MAAM,UAAU,oBAAoB,CAAC,UAAkB;IACrD,OAAO,IAAI,CAAC,UAAU,EAAE,UAAU,CAAC,CAAC;AACtC,CAAC;AAED;;;;GAIG;AACH,MAAM,UAAU,kBAAkB,CAAC,UAAkB;IACnD,MAAM,QAAQ,GAAG,wBAAwB,CAAC,UAAU,CAAC,CAAC;IACtD,IAAI,QAAQ;QAAE,OAAO,QAAQ,CAAC;IAC9B,OAAO,oBAAoB,CAAC,UAAU,CAAC,CAAC;AAC1C,CAAC;AAED;;;GAGG;AACH,MAAM,UAAU,yBAAyB,CAAC,UAAkB,EAAE,GAAW;IACvE,MAAM,YAAY,GAAG,qBAAqB,CAAC,UAAU,CAAC,CAAC;IACvD,IAAI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,yBAAyB,CAAC,UAAkB;IAC1D,OAAO,wBAAwB,CAAC,oBAAoB,CAAC,UAAU,CAAC,CAAC,CAAC;AACpE,CAAC","sourcesContent":["import { randomUUID } from \"crypto\";\nimport { existsSync, mkdirSync, rmSync } from \"fs\";\nimport { basename, dirname, join } from \"path\";\nimport { SessionStore } from \"../harness/index.js\";\nimport { isRecord, parseJsonValue, readTextFileIfExists } from \"../utils/file-guards.js\";\nimport { atomicWritePrivateFile } from \"../utils/fs-atomic.js\";\nimport { isPlatformHistorySession } from \"./metadata.js\";\nimport { threadSuffixOf } from \"./session-key.js\";\nexport type { ResolvedSessionScope, ThreadRootMessage } from \"./types.js\";\n\n/**\n * Returns the shared session directory for a conversation.\n * Channel sessions use a current pointer within this directory.\n * Thread sessions are stored as fixed files within the same directory.\n */\nexport function getChannelSessionDir(channelDir: string): string {\n return join(channelDir, \"sessions\");\n}\n\n/**\n * Resolves the current active session file for a session directory.\n * Reads the \"current\" pointer file; creates a new session if none exists\n * or the pointed-to file is missing.\n */\nexport function resolveSessionFile(sessionDir: string): string {\n const existing = tryResolveCurrentSession(sessionDir);\n if (existing) return existing;\n return createNewSessionFile(sessionDir);\n}\n\n/**\n * Resolve the current active session file for a session directory.\n * Creates a fully initialized persistent session with the provided cwd when none exists.\n */\nexport function resolveManagedSessionFile(sessionDir: string, cwd: string): string {\n const existingPath = getCurrentSessionPath(sessionDir);\n if (existingPath && !isPlatformHistorySession(existingPath)) return existingPath;\n return createManagedSessionFile(sessionDir, cwd);\n}\n\n/**\n * Extracts the short UUID from a session file path.\n * e.g. \"2026-04-05T00-00_7b54cf90.jsonl\" → \"7b54cf90\"\n */\nexport function extractSessionUuid(sessionFile: string): string {\n return basename(sessionFile).replace(\".jsonl\", \"\").split(\"_\").pop()!;\n}\n\n/**\n * Extracts the thread/suffix part of a session key.\n * \"channelId:threadId\" → \"threadId\", \"channelId\" → \"channelId\"\n */\nexport function extractSessionSuffix(sessionKey: string): string {\n return threadSuffixOf(sessionKey) ?? sessionKey;\n}\n\n/**\n * Creates an empty timestamped file and updates the \"current\" pointer.\n * Used only by tests for placeholder-file scenarios.\n *\n * Order matters: write the session file first, then atomic-rename the pointer\n * last so a crash mid-create never leaves \"current\" pointing at a missing file.\n */\nexport function createNewSessionFile(sessionDir: string): string {\n mkdirSync(sessionDir, { recursive: true });\n const filename = createSessionFilename();\n const filePath = join(sessionDir, filename);\n atomicWritePrivateFile(filePath, \"\");\n atomicWritePrivateFile(join(sessionDir, \"current\"), filename);\n return filePath;\n}\n\n/**\n * Creates a new persistent session file with a proper SessionManager header and cwd.\n * Also updates the \"current\" pointer. Header is written before the pointer flips so a\n * partial create cannot leave \"current\" pointing at a missing file.\n */\nexport function createManagedSessionFile(sessionDir: string, cwd: string): string {\n mkdirSync(sessionDir, { recursive: true });\n const sessionId = randomUUID();\n const sessionFile = join(sessionDir, createSessionFilename(sessionId));\n writeSessionHeader(sessionFile, cwd, sessionId);\n setCurrentPointer(sessionDir, sessionFile);\n return sessionFile;\n}\n\n/**\n * Open a session file with an explicit cwd, even if the file does not exist yet.\n * This avoids SessionStore.open() falling back to process.cwd() for fresh sessions.\n */\nexport function openManagedSession(sessionFile: string, cwd: string): SessionStore {\n if (shouldRecreatePreinitializedSession(sessionFile)) {\n rmSync(sessionFile, { force: true });\n }\n\n return SessionStore.open(sessionFile, cwd);\n}\n\nfunction createSessionFilename(sessionId = randomUUID()): string {\n const timestamp = new Date().toISOString().replace(/[:.]/g, \"-\");\n return `${timestamp}_${sessionId.slice(0, 8)}.jsonl`;\n}\n\nfunction setCurrentPointer(sessionDir: string, sessionFilePath: string): void {\n const filename = sessionFilePath.split(\"/\").pop()!;\n mkdirSync(sessionDir, { recursive: true });\n atomicWritePrivateFile(join(sessionDir, \"current\"), filename);\n}\n\n/**\n * Creates or overwrites a fixed-path session file with a valid session header.\n */\nexport function createManagedSessionFileAtPath(sessionFile: string, cwd: string): string {\n writeSessionHeader(sessionFile, cwd);\n return sessionFile;\n}\n\nfunction writeSessionHeader(sessionFile: string, cwd: string, sessionId = randomUUID()): void {\n mkdirSync(dirname(sessionFile), { recursive: true });\n // The header format (and its version) is owned by the harness store; this\n // layer only decides the path and the id.\n SessionStore.create(sessionFile, cwd, { id: sessionId });\n}\n\n/**\n * Returns the fixed session file path for a Slack thread.\n */\nexport function getThreadSessionFile(channelDir: string, sessionKey: string): string {\n return join(getChannelSessionDir(channelDir), `${extractSessionSuffix(sessionKey)}.jsonl`);\n}\n\nfunction hasSessionHeader(sessionFile: string): boolean {\n try {\n const raw = readTextFileIfExists(sessionFile);\n if (raw === undefined) return false;\n const lines = raw.split(\"\\n\");\n for (const line of lines) {\n const trimmed = line.trim();\n if (!trimmed) continue;\n const entry = parseSessionEntry(trimmed);\n return entry.type === \"session\";\n }\n } catch {\n return false;\n }\n return false;\n}\n\nfunction shouldRecreatePreinitializedSession(sessionFile: string): boolean {\n try {\n const raw = readTextFileIfExists(sessionFile);\n if (raw === undefined) return false;\n const entries = raw\n .split(\"\\n\")\n .map((line) => line.trim())\n .filter(Boolean)\n .map(parseSessionEntry);\n\n return entries.length === 1 && entries[0]?.type === \"session\";\n } catch {\n return false;\n }\n}\n\nfunction parseSessionEntry(line: string): { type?: string } {\n return parseJsonValue(\n line,\n (value): value is { type?: string } => isRecord(value),\n (detail) => (detail === \"unexpected JSON shape\" ? \"expected a JSON object\" : detail),\n );\n}\n\nfunction getCurrentSessionPath(sessionDir: string): string | null {\n const pointerFile = join(sessionDir, \"current\");\n const filename = readTextFileIfExists(pointerFile)?.trim();\n if (!filename) return null;\n return join(sessionDir, filename);\n}\n\n/**\n * Try to resolve an existing current session file.\n * Returns null if no current pointer exists or the pointed file has no valid session header.\n */\nexport function tryResolveCurrentSession(sessionDir: string): string | null {\n const fullPath = getCurrentSessionPath(sessionDir);\n if (fullPath && existsSync(fullPath) && hasSessionHeader(fullPath)) return fullPath;\n return null;\n}\n\n/**\n * Try to resolve an existing thread session file.\n * Returns the file path if found, or null if no valid thread session exists yet.\n */\nexport function tryResolveThreadSession(sessionFile: string): string | null {\n return existsSync(sessionFile) && hasSessionHeader(sessionFile) ? sessionFile : null;\n}\n\n/**\n * Resolve the channel's current session file path.\n * Returns null if no channel session exists.\n */\nexport function resolveChannelSessionFile(channelDir: string): string | null {\n return tryResolveCurrentSession(getChannelSessionDir(channelDir));\n}\n"]}
1
+ {"version":3,"file":"store.js","sourceRoot":"","sources":["../../src/sessions/store.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,QAAQ,CAAC;AACpC,OAAO,EAAE,SAAS,EAAE,SAAS,EAAE,MAAM,EAAE,MAAM,IAAI,CAAC;AAClD,OAAO,EAAE,QAAQ,EAAE,OAAO,EAAE,IAAI,EAAE,QAAQ,EAAE,OAAO,EAAE,GAAG,EAAE,MAAM,MAAM,CAAC;AACvE,OAAO,EAAE,YAAY,EAAE,MAAM,qBAAqB,CAAC;AACnD,OAAO,EAAE,QAAQ,EAAE,cAAc,EAAE,oBAAoB,EAAE,MAAM,yBAAyB,CAAC;AACzF,OAAO,EAAE,sBAAsB,EAAE,MAAM,uBAAuB,CAAC;AAC/D,OAAO,EAAE,wBAAwB,EAAE,MAAM,eAAe,CAAC;AACzD,OAAO,EAAE,mBAAmB,EAAE,cAAc,EAAE,MAAM,kBAAkB,CAAC;AAGvE;;;;GAIG;AACH,MAAM,UAAU,oBAAoB,CAAC,UAAkB;IACrD,OAAO,IAAI,CAAC,UAAU,EAAE,UAAU,CAAC,CAAC;AACtC,CAAC;AAED;;;;GAIG;AACH,MAAM,UAAU,kBAAkB,CAAC,UAAkB;IACnD,MAAM,QAAQ,GAAG,wBAAwB,CAAC,UAAU,CAAC,CAAC;IACtD,IAAI,QAAQ;QAAE,OAAO,QAAQ,CAAC;IAC9B,OAAO,oBAAoB,CAAC,UAAU,CAAC,CAAC;AAC1C,CAAC;AAED;;;GAGG;AACH,MAAM,UAAU,yBAAyB,CAAC,UAAkB,EAAE,GAAW;IACvE,MAAM,YAAY,GAAG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AC,CACrF,CAAC;AACJ,CAAC;AAED,SAAS,qBAAqB,CAAC,UAAkB;IAC/C,MAAM,WAAW,GAAG,IAAI,CAAC,UAAU,EAAE,SAAS,CAAC,CAAC;IAChD,MAAM,QAAQ,GAAG,oBAAoB,CAAC,WAAW,CAAC,EAAE,IAAI,EAAE,CAAC;IAC3D,IAAI,CAAC,QAAQ;QAAE,OAAO,IAAI,CAAC;IAC3B,IAAI,CAAC;QACH,OAAO,gBAAgB,CAAC,UAAU,EAAE,QAAQ,CAAC,CAAC;IAChD,CAAC;IAAC,MAAM,CAAC;QACP,OAAO,IAAI,CAAC;IACd,CAAC;AACH,CAAC;AAED;;;GAGG;AACH,MAAM,UAAU,wBAAwB,CAAC,UAAkB;IACzD,MAAM,QAAQ,GAAG,qBAAqB,CAAC,UAAU,CAAC,CAAC;IACnD,IAAI,QAAQ,IAAI,oBAAoB,CAAC,QAAQ,CAAC,IAAI,gBAAgB,CAAC,QAAQ,CAAC;QAAE,OAAO,QAAQ,CAAC;IAC9F,OAAO,IAAI,CAAC;AACd,CAAC;AAED;;;GAGG;AACH,MAAM,UAAU,uBAAuB,CAAC,WAAmB;IACzD,OAAO,oBAAoB,CAAC,WAAW,CAAC,IAAI,gBAAgB,CAAC,WAAW,CAAC,CAAC,CAAC,CAAC,WAAW,CAAC,CAAC,CAAC,IAAI,CAAC;AACjG,CAAC;AAED;;;GAGG;AACH,MAAM,UAAU,yBAAyB,CAAC,UAAkB;IAC1D,OAAO,wBAAwB,CAAC,oBAAoB,CAAC,UAAU,CAAC,CAAC,CAAC;AACpE,CAAC","sourcesContent":["import { randomUUID } from \"crypto\";\nimport { lstatSync, mkdirSync, rmSync } from \"fs\";\nimport { basename, dirname, join, relative, resolve, sep } from \"path\";\nimport { SessionStore } from \"../harness/index.js\";\nimport { isRecord, parseJsonValue, readTextFileIfExists } from \"../utils/file-guards.js\";\nimport { atomicWritePrivateFile } from \"../utils/fs-atomic.js\";\nimport { isPlatformHistorySession } from \"./metadata.js\";\nimport { assertSessionSuffix, threadSuffixOf } from \"./session-key.js\";\nexport type { ResolvedSessionScope, ThreadRootMessage } from \"./types.js\";\n\n/**\n * Returns the shared session directory for a conversation.\n * Channel sessions use a current pointer within this directory.\n * Thread sessions are stored as fixed files within the same directory.\n */\nexport function getChannelSessionDir(channelDir: string): string {\n return join(channelDir, \"sessions\");\n}\n\n/**\n * Resolves the current active session file for a session directory.\n * Reads the \"current\" pointer file; creates a new session if none exists\n * or the pointed-to file is missing.\n */\nexport function resolveSessionFile(sessionDir: string): string {\n const existing = tryResolveCurrentSession(sessionDir);\n if (existing) return existing;\n return createNewSessionFile(sessionDir);\n}\n\n/**\n * Resolve the current active session file for a session directory.\n * Creates a fully initialized persistent session with the provided cwd when none exists.\n */\nexport function resolveManagedSessionFile(sessionDir: string, cwd: string): string {\n const existingPath = getCurrentSessionPath(sessionDir);\n if (existingPath && !isPlatformHistorySession(existingPath)) return existingPath;\n return createManagedSessionFile(sessionDir, cwd);\n}\n\n/**\n * Extracts the short UUID from a session file path.\n * e.g. \"2026-04-05T00-00_7b54cf90.jsonl\" → \"7b54cf90\"\n */\nexport function extractSessionUuid(sessionFile: string): string {\n return basename(sessionFile).replace(\".jsonl\", \"\").split(\"_\").pop()!;\n}\n\n/**\n * Extracts the thread/suffix part of a session key.\n * \"channelId:threadId\" → \"threadId\", \"channelId\" → \"channelId\"\n */\nexport function extractSessionSuffix(sessionKey: string): string {\n return assertSessionSuffix(threadSuffixOf(sessionKey) ?? sessionKey);\n}\n\n/**\n * Resolve one child path and prove it remains inside its owning directory.\n * Identity validation is the first guard; containment is defense in depth for\n * every session path derived from platform-controlled values.\n */\nfunction resolveChildPath(root: string, child: string): string {\n const resolvedRoot = resolve(root);\n const resolvedChild = resolve(resolvedRoot, child);\n const relation = relative(resolvedRoot, resolvedChild);\n if (!relation || relation === \"..\" || relation.startsWith(`..${sep}`)) {\n throw new Error(`Session path escapes its owning directory: ${JSON.stringify(child)}`);\n }\n return resolvedChild;\n}\n\n/**\n * Creates an empty timestamped file and updates the \"current\" pointer.\n * Used only by tests for placeholder-file scenarios.\n *\n * Order matters: write the session file first, then atomic-rename the pointer\n * last so a crash mid-create never leaves \"current\" pointing at a missing file.\n */\nexport function createNewSessionFile(sessionDir: string): string {\n mkdirSync(sessionDir, { recursive: true });\n const filename = createSessionFilename();\n const filePath = join(sessionDir, filename);\n atomicWritePrivateFile(filePath, \"\");\n atomicWritePrivateFile(join(sessionDir, \"current\"), filename);\n return filePath;\n}\n\n/**\n * Creates a new persistent session file with a proper SessionManager header and cwd.\n * Also updates the \"current\" pointer. Header is written before the pointer flips so a\n * partial create cannot leave \"current\" pointing at a missing file.\n */\nexport function createManagedSessionFile(sessionDir: string, cwd: string): string {\n mkdirSync(sessionDir, { recursive: true });\n const sessionId = randomUUID();\n const sessionFile = join(sessionDir, createSessionFilename(sessionId));\n writeSessionHeader(sessionFile, cwd, sessionId);\n setCurrentPointer(sessionDir, sessionFile);\n return sessionFile;\n}\n\n/**\n * Open a session file with an explicit cwd, even if the file does not exist yet.\n * This avoids SessionStore.open() falling back to process.cwd() for fresh sessions.\n */\nexport function openManagedSession(sessionFile: string, cwd: string): SessionStore {\n if (shouldRecreatePreinitializedSession(sessionFile)) {\n rmSync(sessionFile, { force: true });\n }\n\n return SessionStore.open(sessionFile, cwd);\n}\n\nfunction createSessionFilename(sessionId = randomUUID()): string {\n const timestamp = new Date().toISOString().replace(/[:.]/g, \"-\");\n return `${timestamp}_${sessionId.slice(0, 8)}.jsonl`;\n}\n\nfunction setCurrentPointer(sessionDir: string, sessionFilePath: string): void {\n const filename = sessionFilePath.split(\"/\").pop()!;\n mkdirSync(sessionDir, { recursive: true });\n atomicWritePrivateFile(join(sessionDir, \"current\"), filename);\n}\n\n/**\n * Creates or overwrites a fixed-path session file with a valid session header.\n */\nexport function createManagedSessionFileAtPath(sessionFile: string, cwd: string): string {\n writeSessionHeader(sessionFile, cwd);\n return sessionFile;\n}\n\nfunction writeSessionHeader(sessionFile: string, cwd: string, sessionId = randomUUID()): void {\n mkdirSync(dirname(sessionFile), { recursive: true });\n // The header format (and its version) is owned by the harness store; this\n // layer only decides the path and the id.\n SessionStore.create(sessionFile, cwd, { id: sessionId });\n}\n\n/**\n * Returns the fixed session file path for a Slack thread.\n */\nexport function getThreadSessionFile(channelDir: string, sessionKey: string): string {\n const sessionDir = getChannelSessionDir(channelDir);\n return resolveChildPath(sessionDir, `${extractSessionSuffix(sessionKey)}.jsonl`);\n}\n\nfunction isRegularSessionFile(sessionFile: string): boolean {\n try {\n return lstatSync(sessionFile).isFile();\n } catch {\n return false;\n }\n}\n\nfunction hasSessionHeader(sessionFile: string): boolean {\n try {\n const raw = readTextFileIfExists(sessionFile);\n if (raw === undefined) return false;\n const lines = raw.split(\"\\n\");\n for (const line of lines) {\n const trimmed = line.trim();\n if (!trimmed) continue;\n const entry = parseSessionEntry(trimmed);\n return entry.type === \"session\";\n }\n } catch {\n return false;\n }\n return false;\n}\n\nfunction shouldRecreatePreinitializedSession(sessionFile: string): boolean {\n try {\n const raw = readTextFileIfExists(sessionFile);\n if (raw === undefined) return false;\n const entries = raw\n .split(\"\\n\")\n .map((line) => line.trim())\n .filter(Boolean)\n .map(parseSessionEntry);\n\n return entries.length === 1 && entries[0]?.type === \"session\";\n } catch {\n return false;\n }\n}\n\nfunction parseSessionEntry(line: string): { type?: string } {\n return parseJsonValue(\n line,\n (value): value is { type?: string } => isRecord(value),\n (detail) => (detail === \"unexpected JSON shape\" ? \"expected a JSON object\" : detail),\n );\n}\n\nfunction getCurrentSessionPath(sessionDir: string): string | null {\n const pointerFile = join(sessionDir, \"current\");\n const filename = readTextFileIfExists(pointerFile)?.trim();\n if (!filename) return null;\n try {\n return resolveChildPath(sessionDir, filename);\n } catch {\n return null;\n }\n}\n\n/**\n * Try to resolve an existing current session file.\n * Returns null if no current pointer exists or the pointed file has no valid session header.\n */\nexport function tryResolveCurrentSession(sessionDir: string): string | null {\n const fullPath = getCurrentSessionPath(sessionDir);\n if (fullPath && isRegularSessionFile(fullPath) && hasSessionHeader(fullPath)) return fullPath;\n return null;\n}\n\n/**\n * Try to resolve an existing thread session file.\n * Returns the file path if found, or null if no valid thread session exists yet.\n */\nexport function tryResolveThreadSession(sessionFile: string): string | null {\n return isRegularSessionFile(sessionFile) && hasSessionHeader(sessionFile) ? sessionFile : null;\n}\n\n/**\n * Resolve the channel's current session file path.\n * Returns null if no channel session exists.\n */\nexport function resolveChannelSessionFile(channelDir: string): string | null {\n return tryResolveCurrentSession(getChannelSessionDir(channelDir));\n}\n"]}
@@ -1,5 +1,5 @@
1
1
  import { Type } from "@sinclair/typebox";
2
- import { actorKey } from "../sandbox/identity.js";
2
+ import { runtimeResourceKey } from "../sandbox/identity.js";
3
3
  const sandboxSchema = Type.Object({
4
4
  action: Type.Union([Type.Literal("status"), Type.Literal("set")], {
5
5
  description: "Use status to inspect current limits, or set to apply temporary limits.",
@@ -29,7 +29,7 @@ export function createSandboxTool(controller) {
29
29
  !controller.resourceController) {
30
30
  throw new Error("The sandbox tool only supports image:* and gondolin:* managed sandboxes");
31
31
  }
32
- const containerKey = actorKey(controller.sandbox, {
32
+ const containerKey = runtimeResourceKey(controller.sandbox, {
33
33
  userId: sandboxContext.userId,
34
34
  conversationId: sandboxContext.conversationId,
35
35
  });
@@ -1 +1 @@
1
- {"version":3,"file":"sandbox.js","sourceRoot":"","sources":["../../src/tools/sandbox.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,IAAI,EAAE,MAAM,mBAAmB,CAAC;AAGzC,OAAO,EAAE,QAAQ,EAAE,MAAM,wBAAwB,CAAC;AAElD,MAAM,aAAa,GAAG,IAAI,CAAC,MAAM,CAAC;IAChC,MAAM,EAAE,IAAI,CAAC,KAAK,CAAC,CAAC,IAAI,CAAC,OAAO,CAAC,QAAQ,CAAC,EAAE,IAAI,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC,EAAE;QAChE,WAAW,EAAE,yEAAyE;KACvF,CAAC;IACF,IAAI,EAAE,I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AAK,CAAC,IAAI,EAAE,CAAC;IAC7B,IAAI,CAAC,OAAO;QAAE,OAAO,SAAS,CAAC;IAC/B,IAAI,CAAC,mBAAmB,CAAC,IAAI,CAAC,OAAO,CAAC,EAAE,CAAC;QACvC,MAAM,IAAI,KAAK,CAAC,GAAG,IAAI,sDAAsD,CAAC,CAAC;IACjF,CAAC;IACD,OAAO,OAAO,CAAC;AACjB,CAAC;AAED,SAAS,YAAY,CAAC,MAAkC;IACtD,OAAO,OAAO,MAAM,EAAE,IAAI,IAAI,WAAW,aAAa,MAAM,EAAE,MAAM,IAAI,WAAW,EAAE,CAAC;AACxF,CAAC;AAED,SAAS,UAAU,CAAC,IAAY;IAI9B,OAAO,EAAE,OAAO,EAAE,CAAC,EAAE,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,CAAC,EAAE,OAAO,EAAE,SAAS,EAAE,CAAC;AACnE,CAAC","sourcesContent":["import type { AgentTool } from \"@earendil-works/pi-agent-core\";\nimport { Type } from \"@sinclair/typebox\";\nimport type { SandboxConfig } from \"../sandbox/index.js\";\nimport type { ResourceLimits, SandboxResourceController } from \"../types.js\";\nimport { actorKey } from \"../sandbox/identity.js\";\n\nconst sandboxSchema = Type.Object({\n action: Type.Union([Type.Literal(\"status\"), Type.Literal(\"set\")], {\n description: \"Use status to inspect current limits, or set to apply temporary limits.\",\n }),\n cpus: Type.Optional(\n Type.String({\n description: \"CPU limit for action=set, for example '0.5', '1', or '2'.\",\n }),\n ),\n memory: Type.Optional(\n Type.String({\n description: \"Docker memory limit for action=set, for example '512m', '1g', or '4g'.\",\n }),\n ),\n});\n\ntype SandboxToolParams = {\n action: \"status\" | \"set\";\n cpus?: string;\n memory?: string;\n};\n\ninterface SandboxToolContext {\n userId: string;\n conversationId: string;\n}\n\ninterface SandboxToolController {\n sandbox: SandboxConfig;\n resourceController?: Pick<SandboxResourceController, \"getLimitStatus\" | \"setLimits\">;\n}\n\nexport function createSandboxTool(controller: SandboxToolController): {\n tool: AgentTool<typeof sandboxSchema>;\n setSandboxContext: (context: SandboxToolContext) => void;\n} {\n let sandboxContext: SandboxToolContext | null = null;\n\n const tool: AgentTool<typeof sandboxSchema> = {\n name: \"sandbox\",\n label: \"sandbox\",\n description:\n \"Inspect or temporarily set CPU/memory limits for the current managed sandbox. Limits apply to this conversation's runtime and are cleared when it stops.\",\n parameters: sandboxSchema,\n execute: async (_toolCallId: string, params: SandboxToolParams, signal?: AbortSignal) => {\n if (signal?.aborted) {\n throw new Error(\"Operation aborted\");\n }\n if (!sandboxContext) {\n throw new Error(\"Sandbox context not configured\");\n }\n if (\n (controller.sandbox.type !== \"image\" && controller.sandbox.type !== \"gondolin\") ||\n !controller.resourceController\n ) {\n throw new Error(\"The sandbox tool only supports image:* and gondolin:* managed sandboxes\");\n }\n\n const containerKey = actorKey(controller.sandbox, {\n userId: sandboxContext.userId,\n conversationId: sandboxContext.conversationId,\n });\n\n if (params.action === \"set\") {\n const limits = normalizeLimits(params);\n const status = await controller.resourceController.setLimits(containerKey, limits);\n return textResult(\n `Updated sandbox limits for ${containerKey}: ${formatLimits(status.limits)}. These temporary limits are cleared when the sandbox runtime stops.`,\n );\n }\n\n const status = controller.resourceController.getLimitStatus(containerKey);\n return textResult(\n `Sandbox limits for ${containerKey}: ${formatLimits(status.limits)}${status.boosted ? \" (boosted)\" : \"\"}.`,\n );\n },\n };\n\n return {\n tool,\n setSandboxContext: (context: SandboxToolContext) => {\n sandboxContext = context;\n },\n };\n}\n\nfunction normalizeLimits(params: SandboxToolParams): ResourceLimits {\n const cpus = normalizeLimitValue(\"cpus\", params.cpus);\n const memory = normalizeLimitValue(\"memory\", params.memory);\n if (!cpus && !memory) {\n throw new Error(\"action=set requires cpus and/or memory\");\n }\n return { ...(cpus ? { cpus } : {}), ...(memory ? { memory } : {}) };\n}\n\nfunction normalizeLimitValue(name: string, value: string | undefined): string | undefined {\n if (value === undefined) return undefined;\n const trimmed = value.trim();\n if (!trimmed) return undefined;\n if (!/^[A-Za-z0-9_.-]+$/.test(trimmed)) {\n throw new Error(`${name} must not contain whitespace or shell metacharacters`);\n }\n return trimmed;\n}\n\nfunction formatLimits(limits: ResourceLimits | undefined): string {\n return `CPU ${limits?.cpus ?? \"unlimited\"} / Memory ${limits?.memory ?? \"unlimited\"}`;\n}\n\nfunction textResult(text: string): {\n content: Array<{ type: \"text\"; text: string }>;\n details: undefined;\n} {\n return { content: [{ type: \"text\", text }], details: undefined };\n}\n"]}
1
+ {"version":3,"file":"sandbox.js","sourceRoot":"","sources":["../../src/tools/sandbox.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,IAAI,EAAE,MAAM,mBAAmB,CAAC;AAGzC,OAAO,EAAE,kBAAkB,EAAE,MAAM,wBAAwB,CAAC;AAE5D,MAAM,aAAa,GAAG,IAAI,CAAC,MAAM,CAAC;IAChC,MAAM,EAAE,IAAI,CAAC,KAAK,CAAC,CAAC,IAAI,CAAC,OAAO,CAAC,QAAQ,CAAC,EAAE,IAAI,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC,EAAE;QAChE,WAAW,EAAE,yEAAyE;KACvF,CAAC;IACF,IAAI,EAAE,IAAI,CAAC,QAAQ,CACjB,IAAI,CAAC,MAAM,CAAC;QACV,WAAW,EAAE,2DAA2D;KACzE,CAAC,CACH;IACD,MAAM,EAAE,IAAI,CAAC,QAAQ,CACnB,IAAI,CAAC,MAAM,CAAC;QACV,WAAW,EAAE,wEAAwE;KACtF,CAAC,CACH;CACF,CAAC,CAAC;AAkBH,MAAM,UAAU,iBAAiB,CAAC,UAAiC;IAIjE,IAAI,cAAc,GAA8B,IAAI,CAAC;IAErD,MAAM,IAAI,GAAoC;QAC5C,IAAI,EAAE,SAAS;QACf,KAAK,EAAE,SAAS;QAChB,WAAW,EACT,0JAA0J;QAC5J,UAAU,EAAE,aAAa;QACzB,OAAO,EAAE,KAAK,EAAE,WAAmB,EAAE,MAAyB,EAAE,MAAoB,EAAE,EAAE;YACtF,IAAI,MAAM,EAAE,OAAO,EAAE,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SAAS,EAAE,CAAC;AACnE,CAAC","sourcesContent":["import type { AgentTool } from \"@earendil-works/pi-agent-core\";\nimport { Type } from \"@sinclair/typebox\";\nimport type { SandboxConfig } from \"../sandbox/index.js\";\nimport type { ResourceLimits, SandboxResourceController } from \"../types.js\";\nimport { runtimeResourceKey } from \"../sandbox/identity.js\";\n\nconst sandboxSchema = Type.Object({\n action: Type.Union([Type.Literal(\"status\"), Type.Literal(\"set\")], {\n description: \"Use status to inspect current limits, or set to apply temporary limits.\",\n }),\n cpus: Type.Optional(\n Type.String({\n description: \"CPU limit for action=set, for example '0.5', '1', or '2'.\",\n }),\n ),\n memory: Type.Optional(\n Type.String({\n description: \"Docker memory limit for action=set, for example '512m', '1g', or '4g'.\",\n }),\n ),\n});\n\ntype SandboxToolParams = {\n action: \"status\" | \"set\";\n cpus?: string;\n memory?: string;\n};\n\ninterface SandboxToolContext {\n userId: string;\n conversationId: string;\n}\n\ninterface SandboxToolController {\n sandbox: SandboxConfig;\n resourceController?: Pick<SandboxResourceController, \"getLimitStatus\" | \"setLimits\">;\n}\n\nexport function createSandboxTool(controller: SandboxToolController): {\n tool: AgentTool<typeof sandboxSchema>;\n setSandboxContext: (context: SandboxToolContext) => void;\n} {\n let sandboxContext: SandboxToolContext | null = null;\n\n const tool: AgentTool<typeof sandboxSchema> = {\n name: \"sandbox\",\n label: \"sandbox\",\n description:\n \"Inspect or temporarily set CPU/memory limits for the current managed sandbox. Limits apply to this conversation's runtime and are cleared when it stops.\",\n parameters: sandboxSchema,\n execute: async (_toolCallId: string, params: SandboxToolParams, signal?: AbortSignal) => {\n if (signal?.aborted) {\n throw new Error(\"Operation aborted\");\n }\n if (!sandboxContext) {\n throw new Error(\"Sandbox context not configured\");\n }\n if (\n (controller.sandbox.type !== \"image\" && controller.sandbox.type !== \"gondolin\") ||\n !controller.resourceController\n ) {\n throw new Error(\"The sandbox tool only supports image:* and gondolin:* managed sandboxes\");\n }\n\n const containerKey = runtimeResourceKey(controller.sandbox, {\n userId: sandboxContext.userId,\n conversationId: sandboxContext.conversationId,\n });\n\n if (params.action === \"set\") {\n const limits = normalizeLimits(params);\n const status = await controller.resourceController.setLimits(containerKey, limits);\n return textResult(\n `Updated sandbox limits for ${containerKey}: ${formatLimits(status.limits)}. These temporary limits are cleared when the sandbox runtime stops.`,\n );\n }\n\n const status = controller.resourceController.getLimitStatus(containerKey);\n return textResult(\n `Sandbox limits for ${containerKey}: ${formatLimits(status.limits)}${status.boosted ? \" (boosted)\" : \"\"}.`,\n );\n },\n };\n\n return {\n tool,\n setSandboxContext: (context: SandboxToolContext) => {\n sandboxContext = context;\n },\n };\n}\n\nfunction normalizeLimits(params: SandboxToolParams): ResourceLimits {\n const cpus = normalizeLimitValue(\"cpus\", params.cpus);\n const memory = normalizeLimitValue(\"memory\", params.memory);\n if (!cpus && !memory) {\n throw new Error(\"action=set requires cpus and/or memory\");\n }\n return { ...(cpus ? { cpus } : {}), ...(memory ? { memory } : {}) };\n}\n\nfunction normalizeLimitValue(name: string, value: string | undefined): string | undefined {\n if (value === undefined) return undefined;\n const trimmed = value.trim();\n if (!trimmed) return undefined;\n if (!/^[A-Za-z0-9_.-]+$/.test(trimmed)) {\n throw new Error(`${name} must not contain whitespace or shell metacharacters`);\n }\n return trimmed;\n}\n\nfunction formatLimits(limits: ResourceLimits | undefined): string {\n return `CPU ${limits?.cpus ?? \"unlimited\"} / Memory ${limits?.memory ?? \"unlimited\"}`;\n}\n\nfunction textResult(text: string): {\n content: Array<{ type: \"text\"; text: string }>;\n details: undefined;\n} {\n return { content: [{ type: \"text\", text }], details: undefined };\n}\n"]}