@opengeni/worker-bundle 0.17.2 → 0.20.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (75) hide show
  1. package/dist/activities/agent-run-admission.d.ts +12 -0
  2. package/dist/activities/agent-turn.d.ts +25 -0
  3. package/dist/activities/browser-state-artifact-reaper.d.ts +29 -0
  4. package/dist/activities/capabilities.d.ts +6 -0
  5. package/dist/activities/codex-capacity.d.ts +1 -0
  6. package/dist/activities/environment.d.ts +7 -1
  7. package/dist/activities/packs.d.ts +8 -10
  8. package/dist/activities/session-state.d.ts +4 -2
  9. package/dist/activities/site-auth-maintenance.d.ts +27 -0
  10. package/dist/activities/types.d.ts +16 -0
  11. package/dist/activities/video-generation-admission.d.ts +9 -4
  12. package/dist/activities/video-generation-credential.d.ts +17 -0
  13. package/dist/activities/video-reference-staging.d.ts +7 -1
  14. package/dist/activities/xai-auth.d.ts +23 -0
  15. package/dist/activities/xai-image-generation.d.ts +26 -0
  16. package/dist/activities/xai-video-generation.d.ts +18 -0
  17. package/dist/{activities-control-44KBWLSM.js → activities-control-XURE4VKN.js} +387 -51
  18. package/dist/activities-control-XURE4VKN.js.map +1 -0
  19. package/dist/activities-control.d.ts +8 -0
  20. package/dist/{activities-turn-K4CEDEGJ.js → activities-turn-6EBXGGLS.js} +5312 -3951
  21. package/dist/activities-turn-6EBXGGLS.js.map +1 -0
  22. package/dist/activities.d.ts +9 -1
  23. package/dist/{chunk-KKCRGAGZ.js → chunk-5GRJIP5H.js} +99 -98
  24. package/dist/chunk-5GRJIP5H.js.map +1 -0
  25. package/dist/{chunk-E3RI3I33.js → chunk-TYNPCG4U.js} +88 -10
  26. package/dist/chunk-TYNPCG4U.js.map +1 -0
  27. package/dist/index.d.ts +13 -0
  28. package/dist/index.js +49 -2
  29. package/dist/index.js.map +1 -1
  30. package/dist/model-checkpoint-memory-collector.d.ts +1 -0
  31. package/dist/model-context-contributions.d.ts +40 -0
  32. package/dist/observability-metrics.d.ts +20 -1
  33. package/dist/sandbox-routing.d.ts +4 -0
  34. package/dist/workflow-bundle.js +59 -15
  35. package/dist/workflows/activities.d.ts +1 -1
  36. package/dist/workflows/site-auth-maintenance.d.ts +2 -0
  37. package/dist/workflows.d.ts +1 -0
  38. package/package.json +16 -15
  39. package/src/activities/agent-run-admission.ts +76 -0
  40. package/src/activities/agent-turn.ts +1178 -142
  41. package/src/activities/browser-state-artifact-reaper.ts +120 -0
  42. package/src/activities/capabilities.ts +10 -0
  43. package/src/activities/codex-capacity.ts +48 -1
  44. package/src/activities/environment.ts +14 -8
  45. package/src/activities/goals.ts +2 -1
  46. package/src/activities/packs.ts +45 -122
  47. package/src/activities/parent-wake.ts +13 -1
  48. package/src/activities/scheduled-tasks.ts +30 -73
  49. package/src/activities/session-state.ts +18 -0
  50. package/src/activities/site-auth-maintenance.ts +269 -0
  51. package/src/activities/types.ts +17 -0
  52. package/src/activities/video-generation-admission.ts +37 -4
  53. package/src/activities/video-generation-credential.ts +84 -6
  54. package/src/activities/video-generation-reconciliation.ts +212 -19
  55. package/src/activities/video-media-validation.ts +8 -2
  56. package/src/activities/video-reference-staging.ts +121 -34
  57. package/src/activities/xai-auth.ts +122 -0
  58. package/src/activities/xai-image-generation.ts +86 -0
  59. package/src/activities/xai-video-generation.ts +69 -0
  60. package/src/activities-control.ts +4 -0
  61. package/src/activities.ts +5 -0
  62. package/src/index.ts +51 -0
  63. package/src/model-checkpoint-memory-collector.ts +8 -1
  64. package/src/model-context-contributions.ts +159 -0
  65. package/src/observability-metrics.ts +98 -9
  66. package/src/sandbox-routing.ts +13 -0
  67. package/src/workflows/activities.ts +1 -0
  68. package/src/workflows/file-upload-reaper.ts +8 -2
  69. package/src/workflows/session.ts +20 -6
  70. package/src/workflows/site-auth-maintenance.ts +14 -0
  71. package/src/workflows.ts +1 -0
  72. package/dist/activities-control-44KBWLSM.js.map +0 -1
  73. package/dist/activities-turn-K4CEDEGJ.js.map +0 -1
  74. package/dist/chunk-E3RI3I33.js.map +0 -1
  75. package/dist/chunk-KKCRGAGZ.js.map +0 -1
@@ -0,0 +1,120 @@
1
+ import {
2
+ claimBrowserStateArtifactCleanup,
3
+ claimBrowserStateUploadCleanup,
4
+ completeBrowserStateArtifactCleanup,
5
+ completeBrowserStateUploadCleanup,
6
+ type BrowserStateArtifactCleanupClaim,
7
+ type BrowserStateUploadCleanupClaim,
8
+ } from "@opengeni/db";
9
+ import type { ObjectStorage } from "@opengeni/storage";
10
+ import type { ControlActivityServices } from "./types";
11
+
12
+ export const BROWSER_STATE_ARTIFACT_CLAIM_TIMEOUT_MS = 10 * 60 * 1_000;
13
+ export const BROWSER_STATE_ARTIFACT_CLEANUP_BATCH_SIZE = 100;
14
+
15
+ const SAFE_PROVIDER_ERROR_CODES = new Set([
16
+ "aborted",
17
+ "conflict",
18
+ "network",
19
+ "not_found",
20
+ "permission_denied",
21
+ "provider",
22
+ "timeout",
23
+ "unavailable",
24
+ ]);
25
+
26
+ export type MaintainBrowserStateArtifactsResult = {
27
+ claimed: number;
28
+ deleted: number;
29
+ retryable: number;
30
+ };
31
+
32
+ export type BrowserStateArtifactMaintenanceOptions = {
33
+ claimTimeoutMs?: number;
34
+ batchSize?: number;
35
+ claimArtifacts?: typeof claimBrowserStateArtifactCleanup;
36
+ completeArtifact?: typeof completeBrowserStateArtifactCleanup;
37
+ claimUploads?: typeof claimBrowserStateUploadCleanup;
38
+ completeUpload?: typeof completeBrowserStateUploadCleanup;
39
+ /** Failure-injection seam; production uses the configured provider delete. */
40
+ deleteObject?: (storage: ObjectStorage, key: string) => Promise<void>;
41
+ };
42
+
43
+ /**
44
+ * Reap retired encrypted private browser checkpoints. Provider deletion happens
45
+ * before terminal settlement; a crash or provider failure leaves the durable
46
+ * claim reclaimable and an already-deleted provider key is safe to retry.
47
+ */
48
+ export function createBrowserStateArtifactMaintenanceActivities(
49
+ services: () => Promise<ControlActivityServices>,
50
+ options: BrowserStateArtifactMaintenanceOptions = {},
51
+ ) {
52
+ const claimTimeoutMs = options.claimTimeoutMs ?? BROWSER_STATE_ARTIFACT_CLAIM_TIMEOUT_MS;
53
+ const batchSize = options.batchSize ?? BROWSER_STATE_ARTIFACT_CLEANUP_BATCH_SIZE;
54
+ const claimArtifacts = options.claimArtifacts ?? claimBrowserStateArtifactCleanup;
55
+ const completeArtifact = options.completeArtifact ?? completeBrowserStateArtifactCleanup;
56
+ const claimUploads = options.claimUploads ?? claimBrowserStateUploadCleanup;
57
+ const completeUpload = options.completeUpload ?? completeBrowserStateUploadCleanup;
58
+ const deleteObject = options.deleteObject ?? ((storage, key) => storage.deleteObject(key));
59
+
60
+ async function maintainBrowserStateArtifacts(): Promise<MaintainBrowserStateArtifactsResult> {
61
+ const { db, objectStorage, observability } = await services();
62
+ if (!objectStorage) return { claimed: 0, deleted: 0, retryable: 0 };
63
+
64
+ const [artifactClaims, uploadClaims] = await Promise.all([
65
+ claimArtifacts(db, { claimTimeoutMs, limit: batchSize }),
66
+ claimUploads(db, { claimTimeoutMs, limit: batchSize }),
67
+ ]);
68
+ const result: MaintainBrowserStateArtifactsResult = {
69
+ claimed: artifactClaims.length + uploadClaims.length,
70
+ deleted: 0,
71
+ retryable: 0,
72
+ };
73
+ for (const cleanup of artifactClaims) {
74
+ try {
75
+ await deleteObject(objectStorage, cleanup.objectKey);
76
+ if (!(await completeArtifact(db, cleanup))) {
77
+ throw new Error("browser state artifact cleanup claim was superseded");
78
+ }
79
+ result.deleted += 1;
80
+ } catch (error) {
81
+ result.retryable += 1;
82
+ observability.warn("browser state artifact cleanup failed; claim remains reclaimable", {
83
+ workspaceId: cleanup.workspaceId,
84
+ artifactId: cleanup.artifactId,
85
+ errorCategory: cleanupErrorCategory(error),
86
+ });
87
+ }
88
+ }
89
+ for (const cleanup of uploadClaims) {
90
+ try {
91
+ await deleteObject(objectStorage, cleanup.objectKey);
92
+ if (!(await completeUpload(db, cleanup))) {
93
+ throw new Error("browser state upload cleanup claim was superseded");
94
+ }
95
+ result.deleted += 1;
96
+ } catch (error) {
97
+ result.retryable += 1;
98
+ observability.warn("browser state upload cleanup failed; claim remains reclaimable", {
99
+ workspaceId: cleanup.workspaceId,
100
+ uploadId: cleanup.uploadId,
101
+ errorCategory: cleanupErrorCategory(error),
102
+ });
103
+ }
104
+ }
105
+ if (result.claimed > 0) {
106
+ observability.info("browser state artifact maintenance swept", result);
107
+ }
108
+ return result;
109
+ }
110
+
111
+ return { maintainBrowserStateArtifacts };
112
+ }
113
+
114
+ function cleanupErrorCategory(error: unknown): string {
115
+ if (!error || typeof error !== "object") return "unknown";
116
+ const code = (error as { code?: unknown }).code;
117
+ return typeof code === "string" && SAFE_PROVIDER_ERROR_CODES.has(code) ? code : "unknown";
118
+ }
119
+
120
+ export type { BrowserStateArtifactCleanupClaim, BrowserStateUploadCleanupClaim };
@@ -4,6 +4,7 @@ import {
4
4
  withCodexCatalogProvider,
5
5
  withWorkspaceGatewayCatalogProvider,
6
6
  withWorkspaceGatewayCredential,
7
+ withXaiSubscriptionCatalogProvider,
7
8
  } from "@opengeni/config";
8
9
  import { settingsWithEnabledCapabilityMcpServers } from "@opengeni/core";
9
10
  import {
@@ -114,6 +115,15 @@ export function withCodexProvider(settings: Settings): Settings {
114
115
  return withCodexCatalogProvider(settings);
115
116
  }
116
117
 
118
+ /**
119
+ * Pure: append the synthetic SuperGrok/xAI subscription provider,
120
+ * idempotently. The overlay is catalogue metadata only; the exact account,
121
+ * authority snapshot, and bearer remain frozen later at turn admission.
122
+ */
123
+ export function withXaiSubscriptionProvider(settings: Settings): Settings {
124
+ return withXaiSubscriptionCatalogProvider(settings);
125
+ }
126
+
117
127
  export async function settingsWithWorkspaceGatewayCredential(
118
128
  db: Database,
119
129
  workspaceId: string,
@@ -1,9 +1,11 @@
1
1
  import {
2
2
  fetchCodexUsageForAccount,
3
3
  getCodexCapacityWaitForSession,
4
+ getXaiCapacityWaitForSession,
4
5
  listCodexAccountStatuses,
5
6
  listPendingCodexCapacityWakeTargets,
6
7
  reconcileCodexCapacityWait as reconcileCodexCapacityWaitDb,
8
+ reconcileXaiCapacityWait as reconcileXaiCapacityWaitDb,
7
9
  type CodexCapacityWakeTarget,
8
10
  type CodexCapacitySelectionContext,
9
11
  } from "@opengeni/db";
@@ -154,9 +156,18 @@ async function refreshCapacityMetadata(
154
156
  export function createCodexCapacityActivities(services: () => Promise<ControlActivityServices>) {
155
157
  async function getCodexCapacityWait(input: GetCodexCapacityWaitInput) {
156
158
  const { db } = await services();
157
- const waiter = await getCodexCapacityWaitForSession(db, input.workspaceId, input.sessionId);
159
+ const codexWaiter = await getCodexCapacityWaitForSession(
160
+ db,
161
+ input.workspaceId,
162
+ input.sessionId,
163
+ );
164
+ const xaiWaiter = codexWaiter
165
+ ? null
166
+ : await getXaiCapacityWaitForSession(db, input.workspaceId, input.sessionId);
167
+ const waiter = codexWaiter ?? xaiWaiter;
158
168
  return waiter
159
169
  ? {
170
+ ...(xaiWaiter ? { provider: "xai" as const } : {}),
160
171
  waiterId: waiter.id,
161
172
  generation: waiter.generation,
162
173
  // A capacity mutation may have committed while its Temporal signal
@@ -176,6 +187,42 @@ export function createCodexCapacityActivities(services: () => Promise<ControlAct
176
187
  input: ReconcileCodexCapacityWaitInput,
177
188
  ): Promise<ReconcileCodexCapacityWaitResult> {
178
189
  const resolved = await services();
190
+ if (input.provider === "xai") {
191
+ const current = await getXaiCapacityWaitForSession(
192
+ resolved.db,
193
+ input.workspaceId,
194
+ input.sessionId,
195
+ );
196
+ if (!current || current.id !== input.waiterId || current.generation !== input.generation) {
197
+ return { action: "stale" };
198
+ }
199
+ const result = await reconcileXaiCapacityWaitDb(resolved.db, {
200
+ accountId: input.accountId,
201
+ workspaceId: input.workspaceId,
202
+ sessionId: input.sessionId,
203
+ waiterId: input.waiterId,
204
+ generation: input.generation,
205
+ });
206
+ if (result.events.length > 0) {
207
+ try {
208
+ await resolved.bus.publish(input.workspaceId, input.sessionId, result.events);
209
+ } catch {
210
+ // Postgres is authoritative; SSE replay/gap fill repairs missed fanout.
211
+ }
212
+ }
213
+ if (result.action === "resumed") return { action: "resumed" };
214
+ if (result.action === "waiting") {
215
+ return {
216
+ action: "waiting",
217
+ provider: "xai",
218
+ waiterId: result.waiter.id,
219
+ generation: result.waiter.generation,
220
+ nextCheckAt: result.waiter.nextCheckAt.toISOString(),
221
+ wakeRevision: result.waiter.wakeRevision,
222
+ };
223
+ }
224
+ return { action: result.action };
225
+ }
179
226
  const current = await getCodexCapacityWaitForSession(
180
227
  resolved.db,
181
228
  input.workspaceId,
@@ -209,7 +209,13 @@ export async function sandboxEnvironmentForRun(
209
209
  // value later. `= {}` default so the non-optional reads below are safe.
210
210
  options: RunGitCredentialOptions & {
211
211
  skipGitHubToken?: boolean;
212
- skipCodemode?: boolean;
212
+ /**
213
+ * Codemode credential delivery for this attempt. Managed sandboxes receive
214
+ * stable URL/file pointers in their manifest and the bearer through the
215
+ * lifecycle file writer. Connected Machines receive no manifest pointers;
216
+ * the worker injects the minted bearer only into exact exec requests.
217
+ */
218
+ codemodeDelivery?: "managed_file" | "transient_exec" | "none";
213
219
  deferGitHubToken?: boolean;
214
220
  codemodeAuthority?: SandboxCodemodeAuthority;
215
221
  } = {},
@@ -241,21 +247,21 @@ export async function sandboxEnvironmentForRun(
241
247
  // proactively renews every selected provider behind these stable pointers.
242
248
  const stableOptions = options.scope ? { workspaceId: options.scope.workspaceId } : {};
243
249
  const environment = stableSandboxEnvironmentForRun(settings, workspaceEnvironment, stableOptions);
244
- // Connected Machines own their environment and credentials. They do not
245
- // receive OpenGeni Codemode pointers, package hints, or delegated tokens.
246
- // Scrub the stable pointers as well as skipping the mint because a session
247
- // whose home backend is managed may be actively routed to selfhosted.
248
- if (options.skipCodemode) {
250
+ const codemodeDelivery = options.codemodeDelivery ?? "managed_file";
251
+ // Connected Machines keep their machine-wide environment untouched. Their
252
+ // URL, package hint, and direct bearer are projected only onto an exact child
253
+ // exec request by SelfhostedSession, never into the manifest or filesystem.
254
+ if (codemodeDelivery !== "managed_file") {
249
255
  delete environment.OPENGENI_CODEMODE_URL;
250
256
  delete environment.OPENGENI_CODEMODE_TOKEN_FILE;
251
257
  delete environment.OPENGENI_OGTOOL_PACKAGE_SPEC;
252
258
  }
253
259
  const codemodeScope = options.scope;
254
260
  const codemodeToken =
255
- !options.skipCodemode && codemodeScope && options.codemodeAuthority
261
+ codemodeDelivery !== "none" && codemodeScope && options.codemodeAuthority
256
262
  ? await mintSandboxCodemodeToken(settings, codemodeScope, options.codemodeAuthority)
257
263
  : undefined;
258
- if (codemodeToken && codemodeScope) {
264
+ if (codemodeDelivery === "managed_file" && codemodeToken && codemodeScope) {
259
265
  environment.OPENGENI_CODEMODE_URL ??= codemodeWorkspaceUrl(settings, codemodeScope.workspaceId);
260
266
  }
261
267
  const selections = gitCredentialSelections(resources);
@@ -166,10 +166,11 @@ export function goalContinuationPrompt(
166
166
  return [
167
167
  `[GOAL CONTINUATION ${counter}] The session goal is not done. Goal: ${goal.text}.`,
168
168
  `Success criteria: ${goal.successCriteria ?? "none specified"}.`,
169
+ `Objective revision: ${goal.objectiveRevision}. Mutation policy: ${goal.mutationPolicy}.`,
169
170
  "Continue from the existing conversation state. Do not repeat completed session setup, persistent metadata settings, or context checks merely because this is a new continuation turn.",
170
171
  "Continue working toward the goal now. If it is actually complete, call opengeni__goal_complete with concrete evidence.",
171
172
  "If you are blocked or continuing is not productive, call opengeni__goal_pause with your rationale.",
172
- "You may revise the goal with opengeni__goal_update. Do not stop without one of these explicit actions.",
173
+ "Record concrete progress with opengeni__goal_progress. Revise the goal only when explicit user direction or material new evidence justifies the declared change kind; use opengeni__goal_update with this objective revision and a rationale. A rewrite alone is not progress. Do not stop without goal_complete, goal_pause, or concrete continued work.",
173
174
  ].join("\n");
174
175
  }
175
176
 
@@ -3,16 +3,14 @@ import {
3
3
  getWorkspace,
4
4
  getWorkspacePack,
5
5
  listInstalledPortableSkills,
6
- listCapabilityInstallations,
7
6
  listPackInstallations,
8
7
  type Database,
9
8
  } from "@opengeni/db";
10
9
  import {
11
10
  buildPortableSkillArtifact,
12
- isSkillLibraryEntryId,
13
- loadSkillLibrarySkill,
14
- type EffectiveSkillSelection,
15
- type PackSkill,
11
+ type InstalledSkillActivation,
12
+ type PackSkillActivation,
13
+ type RuntimeSkillArtifact,
16
14
  } from "@opengeni/runtime";
17
15
  export {
18
16
  resolveRigProviderImageSelection,
@@ -29,26 +27,17 @@ export {
29
27
  export type WorkspacePackRuntime = {
30
28
  sandboxImage: string | null;
31
29
  sandboxProviderImages: CapabilityPack["sandboxProviderImages"] | null;
32
- skills: PackSkill[];
30
+ skillActivations: PackSkillActivation[];
33
31
  };
34
32
 
35
33
  const emptyPackRuntime: WorkspacePackRuntime = {
36
34
  sandboxImage: null,
37
35
  sandboxProviderImages: null,
38
- skills: [],
36
+ skillActivations: [],
39
37
  };
40
38
 
41
- export type WorkspaceSkillLibraryRuntime = {
42
- skillLibrarySkills: PackSkill[];
43
- skillLibrarySelections: EffectiveSkillSelection[];
44
- };
45
-
46
- type SkillLibraryInstallationMetadata = {
47
- libraryId: string;
48
- libraryVersion: string;
49
- contentSha256: string;
50
- sourceCommit: string;
51
- provenance: string;
39
+ export type WorkspaceInstalledSkillRuntime = {
40
+ activations: InstalledSkillActivation[];
52
41
  };
53
42
 
54
43
  /**
@@ -91,118 +80,46 @@ export function packInstallationUsesLegacyRuntime(
91
80
  }
92
81
 
93
82
  /**
94
- * Resolves active immutable curated skills separately from pack skills. The
95
- * capability installation is the workspace selection boundary; it carries
96
- * only secret-free exact identity metadata, and the runtime loader verifies
97
- * the pinned artifact hash before any content is materialized.
83
+ * Resolves every active immutable Skill through the normalized Plugin/Skill-
84
+ * Facet ledger. The data layer has already filtered ineffective owner edges;
85
+ * this boundary independently verifies exact files before runtime activation.
98
86
  */
99
- export async function resolveWorkspaceSkillLibraryRuntime(
87
+ export async function resolveWorkspaceInstalledSkillRuntime(
100
88
  db: Database,
101
89
  workspaceId: string,
102
- ): Promise<WorkspaceSkillLibraryRuntime> {
103
- const installations = await listCapabilityInstallations(db, workspaceId);
104
- const activeSkills = installations
105
- .filter(
106
- (installation) =>
107
- installation.status === "active" &&
108
- installation.kind === "skill" &&
109
- installation.capabilityId.startsWith("skill:") &&
110
- isSkillLibraryEntryId(installation.capabilityId.slice("skill:".length)),
111
- )
112
- .sort((a, b) => a.capabilityId.localeCompare(b.capabilityId));
113
- const skillLibrarySkills: PackSkill[] = [];
114
- const skillLibrarySelections: EffectiveSkillSelection[] = [];
115
- for (const installation of activeSkills) {
116
- const metadata = parseSkillLibraryInstallationMetadata(
117
- installation.metadata,
118
- installation.capabilityId,
119
- );
120
- if (installation.capabilityId !== `skill:${metadata.libraryId}`) {
121
- throw new Error(
122
- `Skill installation id does not match its library entry: ${installation.capabilityId} -> ${metadata.libraryId}`,
123
- );
124
- }
125
- const loaded = loadSkillLibrarySkill(metadata.libraryId, metadata.libraryVersion);
126
- if (installation.config.version !== metadata.libraryVersion) {
127
- throw new Error(
128
- `Skill installation version mismatch for ${metadata.libraryId}@${metadata.libraryVersion}: config has ${String(installation.config.version)}`,
129
- );
130
- }
131
- if (loaded.entry.contentSha256 !== metadata.contentSha256) {
132
- throw new Error(
133
- `Skill installation hash mismatch for ${metadata.libraryId}@${metadata.libraryVersion}: expected ${metadata.contentSha256}, catalog has ${loaded.entry.contentSha256}`,
134
- );
135
- }
136
- if (
137
- loaded.entry.sourceCommit !== metadata.sourceCommit ||
138
- loaded.entry.provenance !== metadata.provenance
139
- ) {
140
- throw new Error(
141
- `Skill installation provenance mismatch for ${metadata.libraryId}@${metadata.libraryVersion}; re-enable the skill from the current catalog`,
142
- );
143
- }
144
- skillLibrarySkills.push({
145
- name: loaded.skill.name,
146
- description: loaded.skill.description,
147
- files: loaded.skill.files.map((file) => ({ path: file.path, content: file.content })),
148
- });
149
- skillLibrarySelections.push({
150
- id: loaded.entry.id,
151
- name: loaded.entry.name,
152
- source: "library",
153
- version: loaded.entry.version,
154
- contentSha256: loaded.entry.contentSha256,
155
- reason: "enabled workspace capability installation",
156
- });
157
- }
158
- const importedSkills = await listInstalledPortableSkills(db, workspaceId);
159
- for (const imported of importedSkills) {
160
- const artifact = buildPortableSkillArtifact(imported.files);
90
+ ): Promise<WorkspaceInstalledSkillRuntime> {
91
+ const installedSkills = await listInstalledPortableSkills(db, workspaceId);
92
+ const activations: InstalledSkillActivation[] = [];
93
+ for (const installed of installedSkills) {
94
+ const artifact = buildPortableSkillArtifact(installed.files);
161
95
  if (
162
- artifact.name !== imported.name ||
163
- artifact.description !== imported.description ||
164
- artifact.contentSha256 !== imported.contentSha256
96
+ artifact.name !== installed.name ||
97
+ artifact.description !== installed.description ||
98
+ artifact.contentSha256 !== installed.contentSha256
165
99
  ) {
166
100
  throw new Error(
167
- `Imported Skill artifact verification failed for ${imported.capabilityId}; reinstall it from the pinned source`,
101
+ `Installed Skill artifact verification failed for ${installed.capabilityId}; reinstall it from the pinned source`,
168
102
  );
169
103
  }
170
- skillLibrarySkills.push({
171
- name: artifact.name,
172
- description: artifact.description,
173
- files: artifact.files.map((file) => ({ path: file.path, content: file.content })),
174
- });
175
- skillLibrarySelections.push({
176
- id: imported.capabilityId,
177
- name: artifact.name,
178
- source: "imported",
179
- version: imported.sourceCommit,
104
+ activations.push({
105
+ source: "installation",
106
+ id: installed.capabilityId,
107
+ artifact: {
108
+ name: artifact.name,
109
+ description: artifact.description,
110
+ files: artifact.files.map((file) => ({ path: file.path, content: file.content })),
111
+ },
112
+ version: installed.version,
180
113
  contentSha256: artifact.contentSha256,
181
- reason: `installed from ${imported.sourceUrl}`,
114
+ reason:
115
+ installed.source === "library"
116
+ ? "installed from the curated Skill library"
117
+ : installed.source === "pack"
118
+ ? "installed as a Pack-owned Skill"
119
+ : `installed from ${installed.sourceUrl}`,
182
120
  });
183
121
  }
184
- return { skillLibrarySkills, skillLibrarySelections };
185
- }
186
-
187
- function parseSkillLibraryInstallationMetadata(
188
- metadata: Record<string, unknown>,
189
- capabilityId: string,
190
- ): SkillLibraryInstallationMetadata {
191
- const libraryId = stringMetadata(metadata.libraryId);
192
- const libraryVersion = stringMetadata(metadata.libraryVersion);
193
- const contentSha256 = stringMetadata(metadata.contentSha256);
194
- const sourceCommit = stringMetadata(metadata.sourceCommit);
195
- const provenance = stringMetadata(metadata.provenance);
196
- if (!libraryId || !libraryVersion || !contentSha256 || !sourceCommit || !provenance) {
197
- throw new Error(
198
- `Skill installation ${capabilityId} is missing immutable library metadata; re-enable the skill from the current catalog`,
199
- );
200
- }
201
- return { libraryId, libraryVersion, contentSha256, sourceCommit, provenance };
202
- }
203
-
204
- function stringMetadata(value: unknown): string | null {
205
- return typeof value === "string" && value.trim().length > 0 ? value.trim() : null;
122
+ return { activations };
206
123
  }
207
124
 
208
125
  /**
@@ -223,7 +140,7 @@ export function workspacePackRuntimeFromPacks(packs: CapabilityPack[]): Workspac
223
140
  `Multiple enabled packs declare a sandbox image (${ids}). Only one enabled pack per workspace may declare sandboxImage; disable the others and retry.`,
224
141
  );
225
142
  }
226
- const skills: PackSkill[] = [];
143
+ const skillActivations: PackSkillActivation[] = [];
227
144
  // Keyed case-insensitively to match the per-pack uniqueness rule in the
228
145
  // CapabilityPack contract (and case-insensitive filesystems).
229
146
  const skillOwners = new Map<string, string>();
@@ -237,17 +154,23 @@ export function workspacePackRuntimeFromPacks(packs: CapabilityPack[]): Workspac
237
154
  );
238
155
  }
239
156
  skillOwners.set(key, pack.id);
240
- skills.push({
157
+ const artifact: RuntimeSkillArtifact = {
241
158
  name: skill.name,
242
159
  description: skill.description ?? null,
243
160
  files: skill.files.map((file) => ({ path: file.path, content: file.content })),
161
+ };
162
+ skillActivations.push({
163
+ source: "pack",
164
+ id: `pack:${pack.id}:${skill.name}`,
165
+ artifact,
166
+ reason: `active legacy Pack ${pack.id}`,
244
167
  });
245
168
  }
246
169
  }
247
170
  return {
248
171
  sandboxImage: imagePacks[0]?.sandboxImage?.trim() ?? null,
249
172
  sandboxProviderImages: imagePacks[0]?.sandboxProviderImages ?? null,
250
- skills,
173
+ skillActivations,
251
174
  };
252
175
  }
253
176
 
@@ -4,6 +4,7 @@ import {
4
4
  getSession,
5
5
  getSessionGoal,
6
6
  getSessionParentPersonalConnectionDelegations,
7
+ getSessionParentXaiProviderAccountAuthority,
7
8
  addSessionSystemUpdateWithSourceMutation,
8
9
  claimPendingSessionSystemUpdateOutbox,
9
10
  claimPendingSessionWorkflowWakes,
@@ -63,6 +64,11 @@ export async function notifyParentOfChildIdle(
63
64
  workspaceId,
64
65
  childSessionId,
65
66
  );
67
+ const xaiAuthority = await getSessionParentXaiProviderAccountAuthority(
68
+ svc.db,
69
+ workspaceId,
70
+ childSessionId,
71
+ );
66
72
  const outbox = await getOrCreateSessionSystemUpdateOutbox(svc.db, {
67
73
  accountId: child.accountId,
68
74
  workspaceId,
@@ -74,8 +80,13 @@ export async function notifyParentOfChildIdle(
74
80
  dedupeKey: clientEventId,
75
81
  summary: childCompletionSummary(child, goal, "idle"),
76
82
  payload,
77
- lineage: { childSessionId: child.id, parentSessionId: child.parentSessionId },
83
+ lineage: {
84
+ childSessionId: child.id,
85
+ parentSessionId: child.parentSessionId,
86
+ ...(xaiAuthority.subjectId ? { xaiAuthoritySubjectId: xaiAuthority.subjectId } : {}),
87
+ },
78
88
  personalConnectionDelegations,
89
+ xaiProviderAccountAuthoritySnapshot: xaiAuthority.snapshot,
79
90
  });
80
91
  if (outbox.status === "delivered") {
81
92
  return;
@@ -146,6 +157,7 @@ async function deliverParentSystemUpdateOutbox(
146
157
  payload: outbox.payload,
147
158
  lineage: outbox.lineage,
148
159
  personalConnectionDelegations: outbox.personalConnectionDelegations,
160
+ xaiProviderAccountAuthoritySnapshot: outbox.xaiProviderAccountAuthoritySnapshot,
149
161
  },
150
162
  async (tx) => {
151
163
  await markSessionSystemUpdateOutboxDeliveredInTransaction(tx, outbox);