@stigmer/runner 3.12.4 → 3.12.6

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 (180) hide show
  1. package/dist/.build-fingerprint +1 -1
  2. package/dist/activities/call-agent.js +19 -6
  3. package/dist/activities/call-agent.js.map +1 -1
  4. package/dist/activities/execute-cursor/cursor-mcp-config.d.ts +45 -0
  5. package/dist/activities/execute-cursor/cursor-mcp-config.js +76 -0
  6. package/dist/activities/execute-cursor/cursor-mcp-config.js.map +1 -0
  7. package/dist/activities/execute-cursor/error-classifier.d.ts +9 -0
  8. package/dist/activities/execute-cursor/error-classifier.js +30 -1
  9. package/dist/activities/execute-cursor/error-classifier.js.map +1 -1
  10. package/dist/activities/execute-cursor/index.d.ts +10 -1
  11. package/dist/activities/execute-cursor/index.js +62 -36
  12. package/dist/activities/execute-cursor/index.js.map +1 -1
  13. package/dist/activities/execute-cursor/prompt-builder.d.ts +13 -2
  14. package/dist/activities/execute-cursor/prompt-builder.js +11 -0
  15. package/dist/activities/execute-cursor/prompt-builder.js.map +1 -1
  16. package/dist/activities/execute-cursor/service-tier.d.ts +38 -29
  17. package/dist/activities/execute-cursor/service-tier.js +92 -63
  18. package/dist/activities/execute-cursor/service-tier.js.map +1 -1
  19. package/dist/activities/execute-cursor/session-lifecycle.d.ts +1 -1
  20. package/dist/activities/execute-cursor/skill-resolver.d.ts +2 -21
  21. package/dist/activities/execute-cursor/skill-resolver.js +5 -108
  22. package/dist/activities/execute-cursor/skill-resolver.js.map +1 -1
  23. package/dist/activities/execute-cursor/usage-accumulator.d.ts +16 -2
  24. package/dist/activities/execute-cursor/usage-accumulator.js +12 -2
  25. package/dist/activities/execute-cursor/usage-accumulator.js.map +1 -1
  26. package/dist/activities/execute-deep-agent/approval-file-change.d.ts +9 -0
  27. package/dist/activities/execute-deep-agent/approval-file-change.js +2 -1
  28. package/dist/activities/execute-deep-agent/approval-file-change.js.map +1 -1
  29. package/dist/activities/execute-deep-agent/cas-capture-backend.d.ts +18 -1
  30. package/dist/activities/execute-deep-agent/cas-capture-backend.js +20 -3
  31. package/dist/activities/execute-deep-agent/cas-capture-backend.js.map +1 -1
  32. package/dist/activities/execute-deep-agent/index.js +57 -5
  33. package/dist/activities/execute-deep-agent/index.js.map +1 -1
  34. package/dist/activities/execute-deep-agent/prompt-builder.d.ts +9 -0
  35. package/dist/activities/execute-deep-agent/prompt-builder.js +10 -0
  36. package/dist/activities/execute-deep-agent/prompt-builder.js.map +1 -1
  37. package/dist/activities/execute-deep-agent/setup.js +17 -16
  38. package/dist/activities/execute-deep-agent/setup.js.map +1 -1
  39. package/dist/activities/execute-deep-agent/subagent-transformer.js +17 -11
  40. package/dist/activities/execute-deep-agent/subagent-transformer.js.map +1 -1
  41. package/dist/activities/execute-deep-agent/subagent-wiring.d.ts +3 -3
  42. package/dist/index.d.ts +1 -1
  43. package/dist/index.js +1 -1
  44. package/dist/middleware/path-normalization.d.ts +49 -49
  45. package/dist/middleware/path-normalization.js +73 -84
  46. package/dist/middleware/path-normalization.js.map +1 -1
  47. package/dist/middleware/types.d.ts +3 -3
  48. package/dist/runner-manager.d.ts +1 -1
  49. package/dist/runner-manager.js +22 -15
  50. package/dist/runner-manager.js.map +1 -1
  51. package/dist/runner.js +11 -0
  52. package/dist/runner.js.map +1 -1
  53. package/dist/shared/args-preview.d.ts +8 -0
  54. package/dist/shared/args-preview.js +14 -3
  55. package/dist/shared/args-preview.js.map +1 -1
  56. package/dist/shared/artifact-storage.d.ts +11 -1
  57. package/dist/shared/artifact-storage.js +10 -1
  58. package/dist/shared/artifact-storage.js.map +1 -1
  59. package/dist/shared/caller-identity.d.ts +10 -7
  60. package/dist/shared/caller-identity.js +10 -7
  61. package/dist/shared/caller-identity.js.map +1 -1
  62. package/dist/shared/declared-preferences.d.ts +47 -0
  63. package/dist/shared/declared-preferences.js +64 -0
  64. package/dist/shared/declared-preferences.js.map +1 -0
  65. package/dist/shared/mcp-enabled-tools.d.ts +2 -3
  66. package/dist/shared/mcp-enabled-tools.js +2 -3
  67. package/dist/shared/mcp-enabled-tools.js.map +1 -1
  68. package/dist/shared/mcp-resolver.d.ts +20 -15
  69. package/dist/shared/mcp-resolver.js +11 -12
  70. package/dist/shared/mcp-resolver.js.map +1 -1
  71. package/dist/shared/placeholder-resolver.d.ts +9 -2
  72. package/dist/shared/placeholder-resolver.js +9 -2
  73. package/dist/shared/placeholder-resolver.js.map +1 -1
  74. package/dist/shared/plan-mode-permissions.d.ts +26 -46
  75. package/dist/shared/plan-mode-permissions.js +27 -55
  76. package/dist/shared/plan-mode-permissions.js.map +1 -1
  77. package/dist/shared/skill-mount.d.ts +89 -0
  78. package/dist/shared/skill-mount.js +142 -0
  79. package/dist/shared/skill-mount.js.map +1 -0
  80. package/dist/shared/skill-writer.d.ts +28 -26
  81. package/dist/shared/skill-writer.js +79 -102
  82. package/dist/shared/skill-writer.js.map +1 -1
  83. package/dist/shared/thinking-mode.d.ts +35 -0
  84. package/dist/shared/thinking-mode.js +43 -0
  85. package/dist/shared/thinking-mode.js.map +1 -0
  86. package/dist/shared/worker-shutdown.d.ts +67 -0
  87. package/dist/shared/worker-shutdown.js +79 -0
  88. package/dist/shared/worker-shutdown.js.map +1 -0
  89. package/dist/shared/workspace/types.d.ts +3 -2
  90. package/dist/workflow-engine/loader.js +82 -6
  91. package/dist/workflow-engine/loader.js.map +1 -1
  92. package/dist/workflow-engine/tasks/human-input.d.ts +2 -1
  93. package/dist/workflow-engine/tasks/human-input.js +31 -3
  94. package/dist/workflow-engine/tasks/human-input.js.map +1 -1
  95. package/dist/workflow-engine/types.d.ts +17 -3
  96. package/dist/workflow-engine/types.js.map +1 -1
  97. package/dist/workflows/human-input-orchestrator.d.ts +4 -0
  98. package/dist/workflows/human-input-orchestrator.js +13 -0
  99. package/dist/workflows/human-input-orchestrator.js.map +1 -1
  100. package/package.json +15 -11
  101. package/src/activities/call-agent.ts +20 -6
  102. package/src/activities/execute-cursor/__tests__/build-prompt.test.ts +50 -0
  103. package/src/activities/execute-cursor/__tests__/cursor-mcp-config.test.ts +111 -0
  104. package/src/activities/execute-cursor/__tests__/error-classifier-billing.test.ts +67 -0
  105. package/src/activities/execute-cursor/__tests__/service-tier.test.ts +67 -7
  106. package/src/activities/execute-cursor/__tests__/skill-resolver.test.ts +3 -94
  107. package/src/activities/execute-cursor/__tests__/usage-accumulator.test.ts +33 -1
  108. package/src/activities/execute-cursor/cursor-mcp-config.ts +107 -0
  109. package/src/activities/execute-cursor/error-classifier.ts +42 -1
  110. package/src/activities/execute-cursor/index.ts +78 -41
  111. package/src/activities/execute-cursor/prompt-builder.ts +29 -2
  112. package/src/activities/execute-cursor/service-tier.ts +94 -63
  113. package/src/activities/execute-cursor/session-lifecycle.ts +1 -1
  114. package/src/activities/execute-cursor/skill-resolver.ts +10 -137
  115. package/src/activities/execute-cursor/usage-accumulator.ts +11 -1
  116. package/src/activities/execute-deep-agent/__tests__/approval-file-change.test.ts +15 -0
  117. package/src/activities/execute-deep-agent/__tests__/cas-capture-backend.test.ts +75 -0
  118. package/src/activities/execute-deep-agent/__tests__/hitl-reject.test.ts +1 -0
  119. package/src/activities/execute-deep-agent/__tests__/hitl-resume-approve-all.test.ts +1 -0
  120. package/src/activities/execute-deep-agent/__tests__/hitl-resume-history.test.ts +1 -0
  121. package/src/activities/execute-deep-agent/__tests__/index.test.ts +1 -0
  122. package/src/activities/execute-deep-agent/__tests__/plan-mode-path-normalization.test.ts +42 -29
  123. package/src/activities/execute-deep-agent/__tests__/prompt-builder.test.ts +52 -0
  124. package/src/activities/execute-deep-agent/__tests__/sequential-gate-resume.test.ts +1 -0
  125. package/src/activities/execute-deep-agent/__tests__/subagent-plan-mode-permissions.test.ts +11 -8
  126. package/src/activities/execute-deep-agent/approval-file-change.ts +11 -1
  127. package/src/activities/execute-deep-agent/cas-capture-backend.ts +20 -3
  128. package/src/activities/execute-deep-agent/index.ts +57 -5
  129. package/src/activities/execute-deep-agent/prompt-builder.ts +22 -0
  130. package/src/activities/execute-deep-agent/setup.ts +21 -19
  131. package/src/activities/execute-deep-agent/subagent-transformer.ts +19 -12
  132. package/src/activities/execute-deep-agent/subagent-wiring.ts +3 -3
  133. package/src/index.ts +1 -1
  134. package/src/middleware/__tests__/path-normalization.test.ts +32 -32
  135. package/src/middleware/path-normalization.ts +78 -90
  136. package/src/middleware/types.ts +3 -3
  137. package/src/runner-manager.ts +26 -16
  138. package/src/runner.ts +14 -0
  139. package/src/shared/__tests__/artifact-storage.test.ts +28 -0
  140. package/src/shared/__tests__/bedrock-seam.test.ts +5 -5
  141. package/src/shared/__tests__/declared-preferences.test.ts +109 -0
  142. package/src/shared/__tests__/foundry-seam.test.ts +5 -5
  143. package/src/shared/__tests__/plan-mode-permissions.test.ts +15 -44
  144. package/src/shared/__tests__/skill-mount.test.ts +238 -0
  145. package/src/shared/__tests__/skill-writer.test.ts +151 -128
  146. package/src/shared/__tests__/vertex-adapter.test.ts +30 -3
  147. package/src/shared/__tests__/vertex-seam.test.ts +5 -5
  148. package/src/shared/__tests__/worker-shutdown.test.ts +101 -0
  149. package/src/shared/args-preview.ts +17 -3
  150. package/src/shared/artifact-storage.ts +20 -1
  151. package/src/shared/caller-identity.ts +10 -7
  152. package/src/shared/declared-preferences.ts +84 -0
  153. package/src/shared/mcp-enabled-tools.ts +2 -3
  154. package/src/shared/mcp-resolver.ts +20 -20
  155. package/src/shared/placeholder-resolver.ts +9 -2
  156. package/src/shared/plan-mode-permissions.ts +27 -58
  157. package/src/shared/skill-mount.ts +179 -0
  158. package/src/shared/skill-writer.ts +96 -130
  159. package/src/shared/thinking-mode.ts +52 -0
  160. package/src/shared/worker-shutdown.ts +99 -0
  161. package/src/shared/workspace/types.ts +3 -2
  162. package/src/workflow-engine/__tests__/loader.test.ts +95 -0
  163. package/src/workflow-engine/__tests__/tasks/human-input.test.ts +156 -0
  164. package/src/workflow-engine/loader.ts +97 -6
  165. package/src/workflow-engine/tasks/human-input.ts +41 -6
  166. package/src/workflow-engine/types.ts +18 -3
  167. package/src/workflows/human-input-orchestrator.ts +20 -2
  168. package/dist/activities/execute-cursor/connect-backfill.d.ts +0 -19
  169. package/dist/activities/execute-cursor/connect-backfill.js +0 -27
  170. package/dist/activities/execute-cursor/connect-backfill.js.map +0 -1
  171. package/dist/activities/execute-cursor/mcp-resolver.d.ts +0 -120
  172. package/dist/activities/execute-cursor/mcp-resolver.js +0 -194
  173. package/dist/activities/execute-cursor/mcp-resolver.js.map +0 -1
  174. package/dist/activities/execute-cursor/placeholder-resolver.d.ts +0 -34
  175. package/dist/activities/execute-cursor/placeholder-resolver.js +0 -82
  176. package/dist/activities/execute-cursor/placeholder-resolver.js.map +0 -1
  177. package/src/activities/execute-cursor/__tests__/mcp-resolver.test.ts +0 -125
  178. package/src/activities/execute-cursor/connect-backfill.ts +0 -52
  179. package/src/activities/execute-cursor/mcp-resolver.ts +0 -324
  180. package/src/activities/execute-cursor/placeholder-resolver.ts +0 -109
@@ -0,0 +1,179 @@
1
+ /**
2
+ * Skill mount mechanics — the ONE cache shape shared by both harnesses.
3
+ *
4
+ * A skill "mount" is the on-disk materialization of a skill inside the
5
+ * session's platform directory: `{platformDir}/skills/{name}/` holding
6
+ * SKILL.md plus the artifact's supporting files. Both harnesses write to
7
+ * that same physical location — the Cursor harness directly, the native
8
+ * (deep-agent) harness through the `.stigmer/` virtual namespace that
9
+ * LocalWorkspaceBackend routes there — so they MUST share one cache shape
10
+ * (issues #337/#672). This module owns that shape:
11
+ *
12
+ * - The mount is cached by the skill's content-addressed
13
+ * `status.version_hash`: metadata is still fetched every execution
14
+ * (that keeps latest-version freshness — push a skill update and the
15
+ * very next message picks it up), but the artifact download and file
16
+ * rewrite are skipped when the mounted content's hash already matches.
17
+ * - Remounts rebuild the directory from scratch, so files deleted between
18
+ * skill versions never linger in the mount.
19
+ * - Crash-safe by ordering: the marker is stamped LAST, after every file
20
+ * of the mount landed — a crash mid-write leaves no marker, so the next
21
+ * execution remounts instead of trusting a partial tree.
22
+ *
23
+ * Extracted from execute-cursor/skill-resolver.ts (PR #682) when the
24
+ * deep-agent path adopted the same cache (issue #337). Orchestration —
25
+ * which skills to mount, prompt metadata, degradation logging — stays
26
+ * with each harness; only the per-skill-directory mechanics live here.
27
+ */
28
+
29
+ import { mkdir, readFile, writeFile, rm } from "node:fs/promises";
30
+ import { join, dirname, extname, resolve } from "node:path";
31
+ import { ConnectError, Code } from "@connectrpc/connect";
32
+ import type { StigmerClient } from "../client/stigmer-client.js";
33
+ import type { Skill } from "@stigmer/protos/ai/stigmer/agentic/skill/v1/api_pb";
34
+ import { extractZipFileEntries } from "./zip-extract.js";
35
+
36
+ /** Subdirectory of the platform dir where skill mounts live. */
37
+ export const SKILLS_SUBDIR = "skills";
38
+
39
+ /**
40
+ * Marker recording what a skill's mount directory currently holds. Written
41
+ * LAST, after every file of the mount landed — a crash mid-write leaves no
42
+ * marker, so the next execution remounts instead of trusting a partial tree.
43
+ */
44
+ export const MOUNT_MARKER_FILE = ".stigmer-mount.json";
45
+
46
+ export interface MountMarker {
47
+ /** Content-addressed version hash (`Skill.status.version_hash`) of the mounted content. */
48
+ versionHash: string;
49
+ /**
50
+ * Whether the artifact's files are part of the mount. `false` when the
51
+ * skill has no artifact OR when the download failed and the mount fell
52
+ * back to SKILL.md only — the latter makes the next execution retry the
53
+ * download rather than cache the degraded mount.
54
+ */
55
+ artifactMounted: boolean;
56
+ }
57
+
58
+ /**
59
+ * File extensions written with the executable bit set. The ZIP layer is
60
+ * deliberately mode-blind (path + bytes only, see zip-extract.ts), so
61
+ * extension is the only signal available for `./script.sh`-style
62
+ * invocation to work out of the mount.
63
+ */
64
+ const SCRIPT_EXTENSIONS = new Set([".sh", ".py", ".js", ".ts", ".rb", ".pl"]);
65
+
66
+ /**
67
+ * Whether the mount at `skillDir` already holds this version's content.
68
+ *
69
+ * Fresh means: the marker's hash matches AND the mount isn't a degraded
70
+ * SKILL.md-only fallback when the skill does carry an artifact. Any read or
71
+ * parse failure counts as stale — the remount is the safe default.
72
+ */
73
+ export async function mountIsFresh(
74
+ skillDir: string,
75
+ versionHash: string,
76
+ wantsArtifact: boolean,
77
+ ): Promise<boolean> {
78
+ try {
79
+ const raw = await readFile(join(skillDir, MOUNT_MARKER_FILE), "utf-8");
80
+ const marker = JSON.parse(raw) as Partial<MountMarker>;
81
+ return marker.versionHash === versionHash && (marker.artifactMounted === true || !wantsArtifact);
82
+ } catch {
83
+ return false;
84
+ }
85
+ }
86
+
87
+ /**
88
+ * Download a skill artifact's ZIP bytes, transfer lane first (#675).
89
+ *
90
+ * The URL lane (getArtifactDownloadUrl → HTTP GET) carries any valid skill
91
+ * size; the unary getArtifact response is capped by the server's 10MB gRPC
92
+ * message limit. Servers that predate the lane (and cloud until its sibling
93
+ * lands) answer the mint with UNIMPLEMENTED — those fall back to the unary
94
+ * path, which behaves exactly as before for ≤10MB artifacts.
95
+ *
96
+ * Runs only on a mount-cache miss (the hash-keyed marker above) — a hit
97
+ * skips the transfer entirely, whichever lane would have carried it.
98
+ */
99
+ export async function downloadArtifact(
100
+ client: StigmerClient,
101
+ artifactStorageKey: string,
102
+ ): Promise<Uint8Array | undefined> {
103
+ let minted;
104
+ try {
105
+ minted = await client.getSkillArtifactDownloadUrl(artifactStorageKey);
106
+ } catch (err) {
107
+ if (err instanceof ConnectError && err.code === Code.Unimplemented) {
108
+ const resp = await client.getSkillArtifact(artifactStorageKey);
109
+ return resp.artifact && resp.artifact.length > 0 ? resp.artifact : undefined;
110
+ }
111
+ throw err;
112
+ }
113
+
114
+ const resp = await fetch(minted.url);
115
+ if (!resp.ok) {
116
+ throw new Error(`artifact fetch failed: HTTP ${resp.status} from ${minted.url}`);
117
+ }
118
+ const bytes = new Uint8Array(await resp.arrayBuffer());
119
+ if (minted.sizeBytes > 0n && BigInt(bytes.length) !== minted.sizeBytes) {
120
+ throw new Error(
121
+ `artifact fetch truncated: got ${bytes.length} bytes, expected ${minted.sizeBytes}`,
122
+ );
123
+ }
124
+ return bytes.length > 0 ? bytes : undefined;
125
+ }
126
+
127
+ /**
128
+ * (Re)write a skill's mount directory from scratch.
129
+ *
130
+ * The directory is removed first so files deleted between versions don't
131
+ * linger in the mount, then SKILL.md and the artifact files are written, and
132
+ * the marker is stamped LAST (see MOUNT_MARKER_FILE for the crash-safety
133
+ * contract). SKILL.md always comes from `spec.skillMd` — the server's
134
+ * authoritative copy, which the push pipeline guarantees is non-empty
135
+ * (push.go hard-fails a ZIP without an extractable SKILL.md) — never from
136
+ * the zip; both the zip's SKILL.md and any stray marker-named entry are
137
+ * excluded from extraction so the mount's ownership of those two files is
138
+ * unconditional.
139
+ *
140
+ * Every extracted entry must resolve inside `skillDir`. The server already
141
+ * rejects traversal at push (google/safearchive), but this runner-side
142
+ * check is kept as defense-in-depth: it is the guard the deep-agent path
143
+ * used to get from LocalWorkspaceBackend's platform-path routing, preserved
144
+ * here when skill writes moved to direct fs.
145
+ */
146
+ export async function writeSkillMount(
147
+ skill: Skill,
148
+ skillDir: string,
149
+ artifactBytes: Uint8Array | undefined,
150
+ ): Promise<void> {
151
+ await rm(skillDir, { recursive: true, force: true });
152
+ await mkdir(skillDir, { recursive: true });
153
+
154
+ await writeFile(join(skillDir, "SKILL.md"), skill.spec!.skillMd, "utf-8");
155
+
156
+ const artifactMounted = artifactBytes !== undefined && artifactBytes.length > 0;
157
+ if (artifactMounted) {
158
+ const normalizedSkillDir = resolve(skillDir);
159
+ const entries = await extractZipFileEntries(artifactBytes, { exclude: ["SKILL.md", MOUNT_MARKER_FILE] });
160
+ for (const entry of entries) {
161
+ const filePath = resolve(normalizedSkillDir, entry.path);
162
+ if (filePath !== normalizedSkillDir && !filePath.startsWith(normalizedSkillDir + "/")) {
163
+ throw new Error(
164
+ `skill artifact entry escapes its mount directory: '${entry.path}'`,
165
+ );
166
+ }
167
+ await mkdir(dirname(filePath), { recursive: true });
168
+ await writeFile(filePath, entry.content, {
169
+ mode: SCRIPT_EXTENSIONS.has(extname(entry.path)) ? 0o755 : 0o644,
170
+ });
171
+ }
172
+ }
173
+
174
+ const versionHash = skill.status?.versionHash ?? "";
175
+ if (versionHash !== "") {
176
+ const marker: MountMarker = { versionHash, artifactMounted };
177
+ await writeFile(join(skillDir, MOUNT_MARKER_FILE), JSON.stringify(marker), "utf-8");
178
+ }
179
+ }
@@ -1,5 +1,5 @@
1
1
  /**
2
- * Skill writing and prompt generation for the deep-agent execution path.
2
+ * Skill mounting and prompt generation for the deep-agent execution path.
3
3
  *
4
4
  * Follows the Agent Skills specification progressive disclosure model:
5
5
  *
@@ -10,19 +10,33 @@
10
10
  * 3. Resources (on demand) — scripts, references, and assets are
11
11
  * loaded by the agent only when required.
12
12
  *
13
- * Skills live under `.stigmer/skills/{name}/` relative to the workspace root.
14
- * Returned paths are workspace-relative so that the agent's sandbox backend
15
- * resolves them correctly regardless of mount strategy.
13
+ * Skills physically live in the session's platform directory
14
+ * (`{platformDir}/skills/{name}/` the SAME location the Cursor harness
15
+ * mounts into), and the agent sees them as `.stigmer/skills/{name}/`
16
+ * through the per-turn workspace symlink (see workspace/stigmer-link.ts).
17
+ * Returned paths are the agent-visible `.stigmer/…` form.
18
+ *
19
+ * Mounts are cached by the skill's content-addressed version hash via the
20
+ * shared skill-mount mechanics (issue #337, mirroring the Cursor harness's
21
+ * #672 fix): metadata is fetched every execution — a pushed skill update
22
+ * still lands on the very next message — but an unchanged skill skips the
23
+ * artifact download and rewrite entirely.
16
24
  */
17
25
 
18
- import type { WorkspaceBackend } from "./workspace/types.js";
26
+ import { join } from "node:path";
19
27
  import type { Skill } from "@stigmer/protos/ai/stigmer/agentic/skill/v1/api_pb";
20
28
  import type { ApiResourceReference } from "@stigmer/protos/ai/stigmer/commons/apiresource/io_pb";
21
29
  import type { StigmerClient } from "../client/stigmer-client.js";
22
- import { extractZipFileEntries } from "./zip-extract.js";
30
+ import {
31
+ SKILLS_SUBDIR,
32
+ mountIsFresh,
33
+ downloadArtifact,
34
+ writeSkillMount,
35
+ } from "./skill-mount.js";
36
+ import { STIGMER_LOCAL_STATE_DIR } from "./workspace/stigmer-link.js";
23
37
 
24
- const SKILLS_RELATIVE_BASE = ".stigmer/skills";
25
- const SCRIPT_EXTENSIONS = new Set([".sh", ".py", ".js", ".ts", ".rb", ".pl"]);
38
+ /** Agent-visible base of the skills tree (via the workspace `.stigmer` symlink). */
39
+ const SKILLS_RELATIVE_BASE = `${STIGMER_LOCAL_STATE_DIR}/${SKILLS_SUBDIR}`;
26
40
 
27
41
  // ─── Types ───────────────────────────────────────────────────────────────
28
42
 
@@ -81,114 +95,100 @@ export async function fetchSkillsByRefs(
81
95
  return results;
82
96
  }
83
97
 
84
- // ─── Write ───────────────────────────────────────────────────────────────
98
+ // ─── Mount ───────────────────────────────────────────────────────────────
85
99
 
86
100
  /**
87
- * Write skill artifacts to the workspace. Returns a map of
88
- * skill-id -> workspace-relative directory path.
101
+ * Mount skills into the session's platform directory, downloading each
102
+ * skill's artifact only on a version-hash cache miss (see skill-mount.ts
103
+ * for the marker mechanics). Returns a map of skill-id -> agent-visible
104
+ * directory path.
105
+ *
106
+ * The returned map is a NAMING function, not a success record: every skill
107
+ * gets its path entry so prompt generation stays total, while mount
108
+ * failures degrade that one skill (loud log, no throw) — one broken skill
109
+ * must never kill the run.
89
110
  *
90
- * For each skill:
91
- * - If a ZIP artifact is available, extract it to .stigmer/skills/{name}/
92
- * - Otherwise, write just the SKILL.md from the spec
93
- * - Make scripts executable
111
+ * Skills mount in parallel (each owns an independent directory), EXCEPT
112
+ * when two skills resolve to the same directory name (same `spec.name`
113
+ * from different orgs): concurrent remove-and-rewrite passes on one
114
+ * directory would corrupt the mount, so only the first claimant mounts and
115
+ * the collision is logged loudly. (The sequential code this replaced
116
+ * silently let the last writer win — no better, just quieter.)
94
117
  */
95
- export async function writeSkills(
118
+ export async function mountSkills(
119
+ client: StigmerClient,
96
120
  skills: readonly Skill[],
97
- workspaceBackend: WorkspaceBackend,
98
- artifacts: ReadonlyMap<string, Uint8Array>,
121
+ platformDir: string,
99
122
  ): Promise<SkillPathMap> {
100
123
  const paths = new Map<string, string>();
124
+ const claims = new Map<string, Skill>();
101
125
 
102
126
  for (const skill of skills) {
103
127
  const name = skill.spec?.name || skill.metadata?.slug || "unknown";
104
128
  const skillId = skill.metadata?.id ?? name;
105
- const relativeDir = `${SKILLS_RELATIVE_BASE}/${name}`;
106
- paths.set(skillId, relativeDir);
129
+ paths.set(skillId, `${SKILLS_RELATIVE_BASE}/${name}`);
107
130
 
108
- const artifactBytes = artifacts.get(skillId);
109
- if (skill.spec?.skillMd) {
110
- const skillMdPath = `${relativeDir}/SKILL.md`;
111
- await workspaceBackend.writeFile(skillMdPath, skill.spec.skillMd);
112
- if (artifactBytes && artifactBytes.length > 0) {
113
- await extractZipToWorkspaceExcluding(artifactBytes, "SKILL.md", relativeDir, workspaceBackend);
114
- }
115
- } else if (artifactBytes && artifactBytes.length > 0) {
116
- await extractZipToWorkspace(artifactBytes, relativeDir, workspaceBackend);
131
+ // Impossible through the push pipeline (push.go hard-fails a ZIP
132
+ // without an extractable SKILL.md and always populates spec.skill_md),
133
+ // so an empty skillMd means a broken resource — skip, same as Cursor.
134
+ if (!skill.spec?.skillMd) {
135
+ console.warn(
136
+ `[skill-writer] skill ${name} (${skillId}) has no skillMd content — skipping mount`,
137
+ );
138
+ continue;
117
139
  }
118
140
 
119
- await makeScriptsExecutable(relativeDir, workspaceBackend);
120
- }
121
-
122
- return { paths };
123
- }
124
-
125
- /**
126
- * Compute skill paths without writing anything (for resume integrity checks).
127
- */
128
- export function computeSkillPaths(skills: readonly Skill[]): Map<string, string> {
129
- const paths = new Map<string, string>();
130
- for (const skill of skills) {
131
- const name = skill.spec?.name || skill.metadata?.slug || "unknown";
132
- const skillId = skill.metadata?.id ?? name;
133
- paths.set(skillId, `${SKILLS_RELATIVE_BASE}/${name}`);
141
+ const prev = claims.get(name);
142
+ if (prev) {
143
+ console.warn(
144
+ `[skill-writer] mount directory collision on '${name}': ` +
145
+ `${prev.metadata?.org}/${prev.metadata?.slug} already claims it, ` +
146
+ `skipping ${skill.metadata?.org}/${skill.metadata?.slug}`,
147
+ );
148
+ continue;
149
+ }
150
+ claims.set(name, skill);
134
151
  }
135
- return paths;
136
- }
137
-
138
- /**
139
- * Check workspace integrity for resume fast-path.
140
- * Returns true if the sentinel SKILL.md file exists for the first skill.
141
- */
142
- export async function checkSkillIntegrity(
143
- skills: readonly Skill[],
144
- workspaceBackend: WorkspaceBackend,
145
- ): Promise<boolean> {
146
- if (skills.length === 0) return true;
147
-
148
- const paths = computeSkillPaths(skills);
149
- const firstPath = paths.values().next().value;
150
- if (!firstPath) return true;
151
152
 
152
- const sentinel = `${firstPath}/SKILL.md`;
153
- return workspaceBackend.exists(sentinel);
154
- }
153
+ await Promise.all([...claims.entries()].map(async ([name, skill]) => {
154
+ const skillDir = join(platformDir, SKILLS_SUBDIR, name);
155
+ try {
156
+ const versionHash = skill.status?.versionHash ?? "";
157
+ const wantsArtifact = Boolean(skill.status?.artifactStorageKey);
155
158
 
156
- // ─── ZIP extraction ──────────────────────────────────────────────────────
159
+ if (versionHash !== "" && (await mountIsFresh(skillDir, versionHash, wantsArtifact))) {
160
+ console.log(
161
+ `[skill-writer] mount cache hit: ${name} (version ${versionHash.slice(0, 12)}) — skipping artifact transfer`,
162
+ );
163
+ return;
164
+ }
157
165
 
158
- async function extractZipToWorkspace(
159
- zipBytes: Uint8Array,
160
- targetDir: string,
161
- backend: WorkspaceBackend,
162
- ): Promise<void> {
163
- const entries = await extractZipFileEntries(zipBytes);
164
- for (const entry of entries) {
165
- await backend.writeFileBuffer(`${targetDir}/${entry.path}`, Buffer.from(entry.content));
166
- }
167
- }
166
+ let artifactBytes: Uint8Array | undefined;
167
+ if (wantsArtifact) {
168
+ try {
169
+ artifactBytes = await downloadArtifact(client, skill.status!.artifactStorageKey);
170
+ } catch (err) {
171
+ // Deliberate degradation, but LOUD (#675): the run still gets
172
+ // SKILL.md, and the marker records artifactMounted=false so the
173
+ // next execution retries the download.
174
+ console.error(
175
+ `[skill-writer] artifact download FAILED for ${name} ` +
176
+ `(key=${skill.status!.artifactStorageKey}) — mounting SKILL.md WITHOUT the skill's ` +
177
+ `supporting files (scripts/references will be missing): ${err instanceof Error ? err.message : err}`,
178
+ );
179
+ }
180
+ }
168
181
 
169
- async function extractZipToWorkspaceExcluding(
170
- zipBytes: Uint8Array,
171
- excludeName: string,
172
- targetDir: string,
173
- backend: WorkspaceBackend,
174
- ): Promise<void> {
175
- const entries = await extractZipFileEntries(zipBytes, { exclude: [excludeName] });
176
- for (const entry of entries) {
177
- await backend.writeFileBuffer(`${targetDir}/${entry.path}`, Buffer.from(entry.content));
178
- }
179
- }
182
+ await writeSkillMount(skill, skillDir, artifactBytes);
183
+ console.log(`[skill-writer] wrote skill mount: ${name}`);
184
+ } catch (err) {
185
+ console.warn(
186
+ `[skill-writer] failed to mount skill ${name}: ${err instanceof Error ? err.message : err}`,
187
+ );
188
+ }
189
+ }));
180
190
 
181
- async function makeScriptsExecutable(
182
- relativeDir: string,
183
- backend: WorkspaceBackend,
184
- ): Promise<void> {
185
- const extensions = [...SCRIPT_EXTENSIONS].map(ext => `-name '*${ext}'`).join(" -o ");
186
- const cmd = `find ${relativeDir} -type f \\( ${extensions} \\) -exec chmod +x {} \\; 2>/dev/null || true`;
187
- try {
188
- await backend.execute(cmd);
189
- } catch {
190
- // Non-fatal: scripts may not be executable in all environments
191
- }
191
+ return { paths };
192
192
  }
193
193
 
194
194
  // ─── Prompt generation ───────────────────────────────────────────────────
@@ -264,37 +264,3 @@ export function generateAlsoAvailableSection(
264
264
  "read its SKILL.md at `.stigmer/skills/<name>/SKILL.md` to activate it.\n"
265
265
  );
266
266
  }
267
-
268
- // ─── Artifact fetching ───────────────────────────────────────────────────
269
-
270
- /**
271
- * Download skill artifacts for all skills that have a storage key.
272
- * Returns a map from skill ID to artifact bytes.
273
- */
274
- export async function fetchSkillArtifacts(
275
- client: StigmerClient,
276
- skills: readonly Skill[],
277
- ): Promise<Map<string, Uint8Array>> {
278
- const artifacts = new Map<string, Uint8Array>();
279
-
280
- const fetches = skills
281
- .filter(s => s.status?.artifactStorageKey)
282
- .map(async (skill) => {
283
- const key = skill.status!.artifactStorageKey;
284
- const skillId = skill.metadata?.id ?? skill.spec?.name ?? "unknown";
285
- try {
286
- const response = await client.getSkillArtifact(key);
287
- if (response.artifact && response.artifact.length > 0) {
288
- artifacts.set(skillId, response.artifact);
289
- }
290
- } catch (err) {
291
- console.warn(
292
- `[skill-writer] Failed to download artifact for ${skill.spec?.name}: ` +
293
- `${err instanceof Error ? err.message : String(err)}. Falling back to SKILL.md only.`,
294
- );
295
- }
296
- });
297
-
298
- await Promise.all(fetches);
299
- return artifacts;
300
- }
@@ -0,0 +1,52 @@
1
+ /**
2
+ * Harness-neutral thinking-mode semantics (stigmer/stigmer#772) — the
3
+ * second variant dimension alongside `shared/service-tier.ts`.
4
+ *
5
+ * The platform contract mirrors the service tier's: the thinking pin is
6
+ * ALWAYS explicit by the time a provider request leaves the runner.
7
+ * UNSPECIFIED resolves to DISABLED here and ONLY here — every upstream
8
+ * layer preserves the caller's raw enum so "user chose disabled" stays
9
+ * distinguishable from "platform default" all the way to the ledger.
10
+ *
11
+ * Unlike the fast tier, thinking is NOT separately priced: Cursor bills
12
+ * thinking variants at base per-token rates (ledger-verified 2026-08-15 —
13
+ * 277 events at exactly base; thinking+fast at exactly the fast rate).
14
+ * The cost of ENABLED is the extra reasoning tokens, billed as output.
15
+ * Selection is therefore capability-gated (registry capabilities.thinking)
16
+ * rather than pricing-gated, and the estimate/billing paths need no
17
+ * thinking-specific rates.
18
+ *
19
+ * v1 translates thinking on the Cursor harness only (the explicit
20
+ * `thinking` variant parameter, `execute-cursor/service-tier.ts`). No
21
+ * native wire mapping exists yet — create-time validation refuses ENABLED
22
+ * for native-harness models, mirroring the tier's #361 posture.
23
+ */
24
+
25
+ import { ThinkingMode } from "@stigmer/protos/ai/stigmer/agentic/agentexecution/v1/enum_pb";
26
+
27
+ /**
28
+ * The effective mode after platform-default resolution: never UNSPECIFIED.
29
+ */
30
+ export type EffectiveThinkingMode = ThinkingMode.DISABLED | ThinkingMode.ENABLED;
31
+
32
+ /**
33
+ * Resolve the configured mode to its effective value. The single place in
34
+ * the platform where UNSPECIFIED becomes DISABLED.
35
+ */
36
+ export function resolveEffectiveThinkingMode(
37
+ configured: ThinkingMode | undefined,
38
+ ): EffectiveThinkingMode {
39
+ return configured === ThinkingMode.ENABLED ? ThinkingMode.ENABLED : ThinkingMode.DISABLED;
40
+ }
41
+
42
+ /** Human-readable mode label for logs and error messages. */
43
+ export function thinkingModeLabel(mode: ThinkingMode): string {
44
+ switch (mode) {
45
+ case ThinkingMode.ENABLED:
46
+ return "enabled";
47
+ case ThinkingMode.DISABLED:
48
+ return "disabled";
49
+ default:
50
+ return "unspecified";
51
+ }
52
+ }
@@ -0,0 +1,99 @@
1
+ /**
2
+ * Per-task-queue worker-shutdown signals — the classification channel that
3
+ * lets an in-flight activity distinguish "my worker is shutting down" from
4
+ * "the orchestrator cancelled me" (a user pause).
5
+ *
6
+ * The signal carries NO lifecycle authority: aborting it never stops a
7
+ * worker or an activity (Temporal's own drain does that). It exists purely
8
+ * so the activity's cancellation handling can classify the interruption
9
+ * honestly — a shutdown is not a pause, and must surface as the
10
+ * worker-shutdown failure shape the control planes recognize (issue #776).
11
+ *
12
+ * Ownership contract:
13
+ * - whoever creates a Worker registers a signal for its queue BEFORE the
14
+ * worker starts polling;
15
+ * - whoever initiates a full shutdown (SIGTERM handler, desktop quit)
16
+ * aborts the signal BEFORE calling worker.shutdown(), so activities
17
+ * cancelled by the drain observe it already aborted;
18
+ * - a graceful single-worker teardown (view close, deferred teardown in
19
+ * the runner-manager) must NOT abort — those paths only run once no
20
+ * activity is in flight, and aborting earlier is exactly the regression
21
+ * that killed running activities on a view close.
22
+ *
23
+ * Module-level (not per-manager) because activities resolve their signal by
24
+ * task-queue name via {@link getShutdownSignalForQueue} without a handle to
25
+ * the runner/manager instance that created their worker.
26
+ */
27
+
28
+ const registry = new Map<string, AbortController>();
29
+
30
+ /**
31
+ * Register a fresh shutdown signal for a task queue, replacing any previous
32
+ * registration (a re-created worker on a reused queue must not observe the
33
+ * old worker's aborted signal). Returns the controller so the worker's owner
34
+ * can abort it at shutdown.
35
+ */
36
+ export function registerWorkerShutdownSignal(taskQueue: string): AbortController {
37
+ const controller = new AbortController();
38
+ registry.set(taskQueue, controller);
39
+ return controller;
40
+ }
41
+
42
+ /** The signal an activity on `taskQueue` should observe, if one is registered. */
43
+ export function getShutdownSignalForQueue(taskQueue: string): AbortSignal | undefined {
44
+ return registry.get(taskQueue)?.signal;
45
+ }
46
+
47
+ /**
48
+ * Abort the queue's signal, marking any in-flight activity's imminent
49
+ * cancellation as a worker shutdown. Idempotent; no-op for an unknown queue.
50
+ */
51
+ export function signalWorkerShutdown(taskQueue: string): void {
52
+ registry.get(taskQueue)?.abort();
53
+ }
54
+
55
+ /** Drop the registration once the queue's worker is fully torn down. */
56
+ export function unregisterWorkerShutdownSignal(taskQueue: string): void {
57
+ registry.delete(taskQueue);
58
+ }
59
+
60
+ /** The evidence a turn's post-stream classification weighs (see below). */
61
+ export interface TurnInterruptionEvidence {
62
+ /** The periodic heartbeat threw CancelledFailure with no shutdown signal. */
63
+ heartbeatCancelled: boolean;
64
+ /** The periodic heartbeat threw CancelledFailure with the signal aborted. */
65
+ heartbeatWorkerShutdown: boolean;
66
+ /** Temporal delivered cancellation to the activity. */
67
+ cancellationSignalAborted: boolean;
68
+ /** This queue's worker-shutdown signal is aborted. */
69
+ shutdownSignalAborted: boolean;
70
+ }
71
+
72
+ /**
73
+ * Classify how (whether) a turn's stream was interrupted, from the evidence
74
+ * available after the stream ends. Pure so the decision table is directly
75
+ * testable — the activities feed it their heartbeat flags and signals.
76
+ *
77
+ * The load-bearing rule is the grace-window guard (#776): an aborted
78
+ * shutdown signal ALONE is "none", because a run that completes normally
79
+ * inside the drain grace window reaches the classification with the signal
80
+ * already aborted and nothing actually interrupted. Shutdown requires
81
+ * interruption evidence (a heartbeat CancelledFailure or a delivered
82
+ * cancellation) alongside the signal; a heartbeat cancellation with no
83
+ * shutdown signal is the orchestrator's pause.
84
+ */
85
+ export function classifyTurnInterruption(
86
+ evidence: TurnInterruptionEvidence,
87
+ ): "worker-shutdown" | "pause" | "none" {
88
+ const interrupted =
89
+ evidence.heartbeatCancelled ||
90
+ evidence.heartbeatWorkerShutdown ||
91
+ evidence.cancellationSignalAborted;
92
+ if (!interrupted) {
93
+ return "none";
94
+ }
95
+ if (evidence.heartbeatWorkerShutdown || evidence.shutdownSignalAborted) {
96
+ return "worker-shutdown";
97
+ }
98
+ return evidence.heartbeatCancelled ? "pause" : "none";
99
+ }
@@ -49,8 +49,9 @@ export class WorkspaceProvisionError extends Error {
49
49
  /**
50
50
  * Abstraction for executing commands inside a workspace.
51
51
  *
52
- * In local mode, commands run via child_process. In cloud mode (Phase 3),
53
- * commands route through the Daytona sandbox proxy.
52
+ * Commands run via child_process in both modes: in cloud mode the runner
53
+ * itself lives inside the sandbox, so "local" execution is already
54
+ * sandbox-scoped there.
54
55
  *
55
56
  * When `platformDir` is set, paths under `.stigmer/` are transparently
56
57
  * routed to the platform directory instead of the workspace root, keeping