skillar 0.2.1 → 0.3.1

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 (111) hide show
  1. package/NOTICE +280 -0
  2. package/README.md +37 -5
  3. package/dist/analysis/finding.js +8 -190
  4. package/dist/analysis/kernel.js +896 -0
  5. package/dist/analysis/tree.js +7 -154
  6. package/dist/analysis/usage.js +9 -394
  7. package/dist/api/flows.js +42 -212
  8. package/dist/api/report-kernel.js +1063 -0
  9. package/dist/api/routes.js +12 -2
  10. package/dist/catalog/fields.js +138 -146
  11. package/dist/catalog/watcher.js +7 -2
  12. package/dist/cli/init.js +45 -0
  13. package/dist/cli/main.js +76 -3
  14. package/dist/cli/private-skills.js +122 -0
  15. package/dist/cli/serve.js +15 -1
  16. package/dist/cli/sync.js +124 -0
  17. package/dist/dashboard/NOTICE +280 -0
  18. package/dist/dashboard/assets/app.js +737 -275
  19. package/dist/dashboard/assets/astryx-reset.css +407 -0
  20. package/dist/dashboard/assets/astryx.css +1077 -0
  21. package/dist/dashboard/assets/charts.css +54 -0
  22. package/dist/dashboard/assets/chunk-TPGDA2J4.js +1 -0
  23. package/dist/dashboard/assets/chunk-YLWHVDMP.js +36 -0
  24. package/dist/dashboard/assets/controls.css +207 -0
  25. package/dist/dashboard/assets/overlays.css +132 -0
  26. package/dist/dashboard/assets/p1.css +135 -0
  27. package/dist/dashboard/assets/shell.css +71 -0
  28. package/dist/dashboard/assets/skillar-theme.css +692 -0
  29. package/dist/dashboard/assets/styles.css +224 -121
  30. package/dist/dashboard/assets/tokens.css +278 -0
  31. package/dist/dashboard/assets/widgets.css +83 -0
  32. package/dist/dashboard/index.html +11 -2
  33. package/dist/dashboard/viewers/viewers.css +61 -0
  34. package/dist/ingest/attribution.js +5 -1
  35. package/dist/ingest/pipeline.js +2 -0
  36. package/dist/ingest/request-recorder.js +39 -0
  37. package/dist/mcp/dispatch.js +2 -2
  38. package/dist/mcp/http.js +43 -3
  39. package/dist/mcp/skills-extension.js +42 -15
  40. package/dist/mcp/stdio-proxy.js +24 -3
  41. package/dist/mcp/tools.js +38 -24
  42. package/dist/packs/claude-code.js +22 -11
  43. package/dist/packs/cursor.js +9 -4
  44. package/dist/packs/gemini.js +9 -4
  45. package/dist/packs/json-config.js +41 -0
  46. package/dist/packs/omo.js +15 -6
  47. package/dist/request-status.js +81 -0
  48. package/dist/search/fts.js +93 -58
  49. package/dist/search/fusion.js +49 -47
  50. package/dist/search/guidance.js +18 -6
  51. package/dist/search/index.js +291 -70
  52. package/dist/search/lexical.js +71 -63
  53. package/dist/server.js +12 -0
  54. package/dist/skills/apply.js +130 -0
  55. package/dist/skills/capture.js +54 -0
  56. package/dist/skills/cloud-plan.js +57 -0
  57. package/dist/skills/cloud.js +81 -0
  58. package/dist/skills/fs.js +133 -0
  59. package/dist/skills/package.js +734 -0
  60. package/dist/skills/plan.js +83 -0
  61. package/dist/skills/receipt.js +44 -0
  62. package/dist/skills/rollback.js +119 -0
  63. package/dist/skills/transfer.js +51 -0
  64. package/dist/store/db.js +7 -1
  65. package/dist/store/execution.js +2 -34
  66. package/dist/store/export.js +25 -4
  67. package/dist/store/migrations/007_sync.sql +49 -0
  68. package/dist/store/migrations/008_connector_commands.sql +12 -0
  69. package/dist/store/queries.js +33 -7
  70. package/dist/store/writes.js +38 -5
  71. package/dist/sync/cloud-blobs.js +175 -0
  72. package/dist/sync/cloud-commands.js +101 -0
  73. package/dist/sync/cloud-connection.js +105 -0
  74. package/dist/sync/cloud-delivery.js +114 -0
  75. package/dist/sync/cloud-documents.js +103 -0
  76. package/dist/sync/cloud-export.js +67 -0
  77. package/dist/sync/cloud-http.js +150 -0
  78. package/dist/sync/cloud-jobs.js +94 -0
  79. package/dist/sync/cloud-pending.js +143 -0
  80. package/dist/sync/cloud-prepare.js +101 -0
  81. package/dist/sync/cloud-restore.js +136 -0
  82. package/dist/sync/cloud-rollback.js +24 -0
  83. package/dist/sync/cloud-runner.js +86 -0
  84. package/dist/sync/cloud-runtime.js +293 -0
  85. package/dist/sync/cloud-schema.js +32 -0
  86. package/dist/sync/cloud-stage.js +112 -0
  87. package/dist/sync/cloud-wire.js +693 -0
  88. package/dist/sync/cloud-worker.js +57 -0
  89. package/dist/sync/cloud.js +157 -0
  90. package/dist/sync/command-apply.js +140 -0
  91. package/dist/sync/command-control.js +25 -0
  92. package/dist/sync/command-wire.js +437 -0
  93. package/dist/sync/consent.js +130 -0
  94. package/dist/sync/journal.js +43 -0
  95. package/dist/sync/outbox.js +134 -0
  96. package/dist/sync/restore-rows.js +125 -0
  97. package/dist/sync/restore.js +174 -0
  98. package/dist/sync/snapshot.js +78 -0
  99. package/dist/sync/spool-request.js +103 -0
  100. package/dist/sync/tables.js +27 -0
  101. package/dist/sync/triggers.js +34 -0
  102. package/dist/workflow/compare.js +3 -43
  103. package/docs/cloud-sync.md +94 -0
  104. package/docs/private-skills.md +75 -0
  105. package/docs/sync-p4.md +102 -0
  106. package/docs/sync-restore.md +167 -0
  107. package/package.json +18 -5
  108. package/src/store/migrations/007_sync.sql +49 -0
  109. package/src/store/migrations/008_connector_commands.sql +12 -0
  110. package/dist/dashboard/assets/chunk-5DFWNJC2.js +0 -1
  111. package/dist/dashboard/assets/chunk-S6B2HJQA.js +0 -17
@@ -0,0 +1,734 @@
1
+ // ../shared/dist/private-skills.js
2
+ import { z as z4 } from "zod";
3
+
4
+ // ../shared/dist/activity-schema.js
5
+ import { z } from "zod";
6
+ var identity = z.string().min(1).max(512).refine((value) => !value.includes("\0"));
7
+ var accountIdSchema = identity.brand();
8
+ var deviceIdSchema = identity.brand();
9
+ var sourceDomainSchema = identity.brand();
10
+ var sourceIdSchema = identity.brand();
11
+ var revisionSchema = z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER);
12
+ var timestampSchema = z.number().int().min(-864e13).max(864e13);
13
+ var recordingOrdersSchema = z.record(sourceDomainSchema, revisionSchema).readonly();
14
+ var timeRangeSchema = z.strictObject({
15
+ fromMs: timestampSchema,
16
+ toMs: timestampSchema
17
+ }).refine((value) => value.toMs > value.fromMs).readonly();
18
+ var backfillReferenceSchema = z.strictObject({
19
+ version: revisionSchema.min(1),
20
+ snapshotId: identity,
21
+ journalCut: revisionSchema
22
+ }).readonly();
23
+ var count = z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER).nullable();
24
+ var runtime = z.enum(["claude-code", "codex", "gemini", "cursor", "omo", "gajae", "openclaw", "unknown"]);
25
+ var sessionFactsSchema = z.strictObject({
26
+ runtime,
27
+ startedMs: timestampSchema,
28
+ endedMs: timestampSchema.nullable(),
29
+ automated: z.boolean().nullable()
30
+ }).readonly();
31
+ var eventFactsSchema = z.strictObject({
32
+ sessionId: sourceIdSchema,
33
+ kind: z.enum([
34
+ "session_start",
35
+ "session_end",
36
+ "prompt",
37
+ "search",
38
+ "load",
39
+ "read_file",
40
+ "native_skill",
41
+ "tool_call",
42
+ "llm_call",
43
+ "error",
44
+ "skill_request"
45
+ ]),
46
+ timestampMs: timestampSchema,
47
+ sourceOrder: revisionSchema.nullable(),
48
+ recordingOrders: recordingOrdersSchema,
49
+ sourceKey: sourceIdSchema.nullable(),
50
+ status: z.enum(["in_progress", "succeeded", "failed", "cancelled", "unknown"]),
51
+ inputTokens: count,
52
+ outputTokens: count
53
+ }).readonly();
54
+ var spanFactsSchema = z.strictObject({
55
+ traceId: sourceIdSchema,
56
+ spanId: sourceIdSchema,
57
+ parentSpanId: sourceIdSchema.nullable(),
58
+ sessionId: sourceIdSchema.nullable(),
59
+ startMs: timestampSchema.nullable(),
60
+ endMs: timestampSchema.nullable(),
61
+ recordingOrders: recordingOrdersSchema,
62
+ inputTokens: count,
63
+ outputTokens: count
64
+ }).readonly();
65
+ var mutation = {
66
+ key: sourceIdSchema,
67
+ revision: revisionSchema
68
+ };
69
+ var metadataMutationSchema = z.discriminatedUnion("entity", [
70
+ z.strictObject({ ...mutation, entity: z.literal("session"), facts: sessionFactsSchema }),
71
+ z.strictObject({ ...mutation, entity: z.literal("event"), facts: eventFactsSchema }),
72
+ z.strictObject({ ...mutation, entity: z.literal("span"), facts: spanFactsSchema }),
73
+ z.strictObject({
74
+ ...mutation,
75
+ entity: z.literal("tombstone"),
76
+ target: z.enum(["session", "event", "span"])
77
+ })
78
+ ]).readonly();
79
+ var activityBatchSchema = z.strictObject({
80
+ schemaVersion: z.literal(1),
81
+ batchId: identity,
82
+ // Account identity comes only from the verified principal, never this payload.
83
+ deviceId: deviceIdSchema,
84
+ sourceDomain: sourceDomainSchema,
85
+ generation: revisionSchema.min(1),
86
+ consentVersion: revisionSchema.min(1),
87
+ projectId: identity,
88
+ rootId: identity.nullable(),
89
+ range: timeRangeSchema,
90
+ backfill: backfillReferenceSchema.nullable(),
91
+ sequence: revisionSchema.min(1),
92
+ journal: z.strictObject({ from: revisionSchema, through: revisionSchema }).refine((range) => range.through >= range.from).readonly(),
93
+ mutations: z.array(metadataMutationSchema).min(1).max(100).readonly()
94
+ }).readonly();
95
+ var contentKinds = [
96
+ "prompt",
97
+ "query",
98
+ "args",
99
+ "error",
100
+ "path",
101
+ "span-attributes",
102
+ "private-skills"
103
+ ];
104
+ var contentKindSchema = z.enum(contentKinds);
105
+ var MAX_BATCH_BYTES = 256 * 1024;
106
+ function parseActivityBatch(input, options = {}) {
107
+ const parser = options.allowEmptyMetadata === true ? activityBatchSchema.unwrap().extend({
108
+ mutations: z.array(metadataMutationSchema).max(100).readonly()
109
+ }).readonly() : activityBatchSchema;
110
+ const value = parser.parse(input);
111
+ if (new TextEncoder().encode(JSON.stringify(value)).byteLength > MAX_BATCH_BYTES) {
112
+ throw new ActivityContractError("batch_too_large");
113
+ }
114
+ for (const mutation2 of value.mutations) {
115
+ let times;
116
+ switch (mutation2.entity) {
117
+ case "event":
118
+ times = [mutation2.facts.timestampMs];
119
+ break;
120
+ case "session":
121
+ times = [mutation2.facts.startedMs, mutation2.facts.endedMs];
122
+ break;
123
+ case "span":
124
+ times = [mutation2.facts.startMs, mutation2.facts.endMs];
125
+ break;
126
+ case "tombstone":
127
+ times = [];
128
+ break;
129
+ default: {
130
+ const exhaustive = mutation2;
131
+ return exhaustive;
132
+ }
133
+ }
134
+ if (times.some((time) => time !== null && (time < value.range.fromMs || time >= value.range.toMs))) {
135
+ throw new ActivityContractError("range_not_allowed");
136
+ }
137
+ }
138
+ return value;
139
+ }
140
+ var ActivityContractError = class extends Error {
141
+ code;
142
+ constructor(code) {
143
+ super(code);
144
+ this.code = code;
145
+ this.name = "ActivityContractError";
146
+ }
147
+ };
148
+
149
+ // ../shared/dist/deployment-origin.js
150
+ import { z as z2 } from "zod";
151
+ var deploymentOriginSchema = z2.url().refine((value) => {
152
+ const url = new URL(value);
153
+ return value === url.origin && (url.protocol === "https:" || value === "http://localhost:8788");
154
+ });
155
+
156
+ // ../shared/dist/mcp-auth.js
157
+ import { z as z3 } from "zod";
158
+ var mcpScopes = ["skills:read", "activity:record", "offline_access"];
159
+ var mcpScopeSchema = z3.enum(mcpScopes);
160
+ var mcpConnectionIdSchema = z3.string().uuid().brand();
161
+ var mcpPrivatePrincipalSchema = z3.strictObject({
162
+ kind: z3.literal("mcp"),
163
+ accountId: accountIdSchema,
164
+ generation: z3.number().int().positive().safe(),
165
+ shardId: z3.literal("activity-00"),
166
+ issuer: deploymentOriginSchema,
167
+ scopes: z3.array(z3.enum(["skills:read", "skills:write"])).max(2).readonly(),
168
+ sessionId: z3.null(),
169
+ deviceId: deviceIdSchema,
170
+ tokenHash: z3.string().regex(/^[a-f0-9]{64}$/),
171
+ connectionId: mcpConnectionIdSchema
172
+ }).readonly();
173
+ var mcpContextSchema = z3.strictObject({
174
+ principal: mcpPrivatePrincipalSchema,
175
+ recordActivity: z3.boolean(),
176
+ clientName: z3.string().min(1).max(200)
177
+ }).readonly();
178
+ var mcpClaimsSchema = z3.strictObject({
179
+ connectionId: mcpConnectionIdSchema,
180
+ accountId: accountIdSchema,
181
+ generation: z3.number().int().positive().safe()
182
+ }).readonly();
183
+ var mcpConnectionSummarySchema = z3.strictObject({
184
+ connectionId: mcpConnectionIdSchema,
185
+ kind: z3.enum(["oauth", "pat"]),
186
+ name: z3.string().min(1).max(200),
187
+ scopes: z3.array(mcpScopeSchema).readonly(),
188
+ recordActivity: z3.boolean(),
189
+ createdAt: z3.number().int().nonnegative().safe(),
190
+ expiresAt: z3.number().int().positive().safe(),
191
+ revokedAt: z3.number().int().nonnegative().safe().nullable()
192
+ }).readonly();
193
+ var mcpConnectionsSchema = z3.strictObject({
194
+ resource: z3.url(),
195
+ connections: z3.array(mcpConnectionSummarySchema).readonly()
196
+ }).readonly();
197
+ var mcpPatRequestSchema = z3.strictObject({
198
+ name: z3.string().trim().min(1).max(80),
199
+ expiresInDays: z3.number().int().min(1).max(30),
200
+ recordActivity: z3.boolean()
201
+ }).readonly();
202
+ var mcpPatResponseSchema = z3.strictObject({
203
+ connection: mcpConnectionSummarySchema,
204
+ token: z3.string().regex(/^skm_[A-Za-z0-9_-]{43}$/)
205
+ }).readonly();
206
+
207
+ // ../shared/dist/private-skills.js
208
+ var PRIVATE_SKILL_MAX_BYTES = 16 * 1024 * 1024;
209
+ var PRIVATE_SKILL_MAX_RESOURCE_BYTES = PRIVATE_SKILL_MAX_BYTES;
210
+ var PRIVATE_SKILL_MAX_RESOURCES = 512;
211
+ var PRIVATE_SKILL_MAX_REQUEST_BYTES = 24 * 1024 * 1024;
212
+ var PRIVATE_SKILL_MAX_URI_LENGTH = 8192;
213
+ var privateSkillIdSchema = z4.string().uuid().toLowerCase().brand();
214
+ var privateSkillDigestSchema = z4.string().regex(/^[a-f0-9]{64}$/).brand();
215
+ var privateSkillPathSchema = z4.string().min(1).max(512).refine((value) => {
216
+ if (value !== value.normalize("NFC") || /[%\\:\0]/u.test(value) || /\.(?:zip|tar|tgz|gz|bz2|xz|7z|rar)$/i.test(value))
217
+ return false;
218
+ return value.split("/").every((segment) => segment !== "" && segment !== "." && segment !== ".." && segment === segment.trim() && !segment.endsWith(".") && /^[\p{L}\p{N}._ -]+$/u.test(segment) && !/^\.(?:git|svn|hg)$/i.test(segment) && !/^(?:con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\.|$)/i.test(segment));
219
+ }).brand();
220
+ var privateSkillResourceSchema = z4.strictObject({
221
+ path: privateSkillPathSchema,
222
+ mediaType: z4.string().min(3).max(128).regex(/^[a-z0-9!#$&^_.+-]+\/[a-z0-9!#$&^_.+-]+$/),
223
+ bytes: z4.number().int().min(0).max(PRIVATE_SKILL_MAX_RESOURCE_BYTES),
224
+ digest: privateSkillDigestSchema
225
+ }).readonly();
226
+ var privateSkillManifestSchema = z4.strictObject({
227
+ schemaVersion: z4.literal(1),
228
+ entrypoint: z4.literal("SKILL.md"),
229
+ resources: z4.array(privateSkillResourceSchema).min(1).max(PRIVATE_SKILL_MAX_RESOURCES).readonly()
230
+ }).superRefine((manifest, context) => {
231
+ const paths = manifest.resources.map((resource) => resource.path);
232
+ const folded = paths.map((path) => path.toLowerCase());
233
+ if (!paths.some((path) => path === "SKILL.md") || new Set(folded).size !== paths.length || folded.some((path) => folded.some((other) => other.startsWith(`${path}/`))) || paths.some((path, index) => index > 0 && path <= (paths[index - 1] ?? "")) || manifest.resources.reduce((sum, resource) => sum + resource.bytes, 0) > PRIVATE_SKILL_MAX_BYTES) {
234
+ context.addIssue({ code: "custom", message: "invalid resource membership, order or total" });
235
+ }
236
+ }).readonly();
237
+ var privateSkillBodySchema = z4.string().max(4 * Math.ceil(PRIVATE_SKILL_MAX_RESOURCE_BYTES / 3)).refine((body) => body.length <= 4 * Math.ceil(PRIVATE_SKILL_MAX_RESOURCE_BYTES / 3) && body.length % 4 === 0 && /^[A-Za-z0-9+/]*={0,2}$/.test(body));
238
+ var privateSkillPackageSchema = z4.strictObject({
239
+ manifest: privateSkillManifestSchema,
240
+ manifestDigest: privateSkillDigestSchema,
241
+ contents: z4.array(z4.strictObject({
242
+ path: privateSkillPathSchema,
243
+ body: privateSkillBodySchema
244
+ }).readonly()).min(1).max(PRIVATE_SKILL_MAX_RESOURCES).readonly()
245
+ }).superRefine((packet, context) => {
246
+ if (packet.contents.reduce((sum, content) => sum + content.body.length, 0) > 4 * Math.ceil(PRIVATE_SKILL_MAX_BYTES / 3) + 4 * PRIVATE_SKILL_MAX_RESOURCES) {
247
+ context.addIssue({ code: "custom", message: "encoded resources exceed package quota" });
248
+ }
249
+ }).readonly();
250
+ var privateSkillHeadSchema = z4.strictObject({
251
+ digest: privateSkillDigestSchema,
252
+ revision: z4.number().int().positive().safe()
253
+ }).readonly();
254
+ var privateSkillPublishSchema = z4.strictObject({
255
+ base: privateSkillHeadSchema.nullable(),
256
+ acknowledgePrivateUpload: z4.literal(true),
257
+ package: privateSkillPackageSchema
258
+ }).readonly();
259
+ var privateSkillHeadChangeSchema = z4.strictObject({
260
+ base: privateSkillHeadSchema,
261
+ targetDigest: privateSkillDigestSchema
262
+ }).readonly();
263
+ var privateSkillDeleteSchema = z4.strictObject({
264
+ base: privateSkillHeadSchema
265
+ }).readonly();
266
+ var privateSkillPinSchema = z4.strictObject({
267
+ base: privateSkillHeadSchema,
268
+ targetDigest: privateSkillDigestSchema,
269
+ pinned: z4.boolean()
270
+ }).readonly();
271
+ var privateSkillSummarySchema = z4.strictObject({
272
+ skillId: privateSkillIdSchema,
273
+ name: z4.string().min(1).max(128),
274
+ description: z4.string().min(1).max(4096),
275
+ head: privateSkillHeadSchema,
276
+ updatedAt: z4.number().int().nonnegative().safe()
277
+ }).readonly();
278
+ var privateSkillCatalogSchema = z4.strictObject({
279
+ revision: z4.number().int().nonnegative().safe(),
280
+ skills: z4.array(privateSkillSummarySchema).readonly()
281
+ }).readonly();
282
+ var privateSkillVersionSchema = z4.strictObject({
283
+ digest: privateSkillDigestSchema,
284
+ createdAt: z4.number().int().nonnegative().safe(),
285
+ pinned: z4.boolean()
286
+ }).readonly();
287
+ var privateSkillDetailSchema = z4.strictObject({
288
+ skill: privateSkillSummarySchema,
289
+ versions: z4.array(privateSkillVersionSchema).readonly()
290
+ }).readonly();
291
+ var privateSkillExportSchema = z4.strictObject({
292
+ skillId: privateSkillIdSchema,
293
+ version: privateSkillVersionSchema,
294
+ package: privateSkillPackageSchema
295
+ }).readonly();
296
+ var privateSkillReadSchema = privateSkillResourceSchema.unwrap().omit({ path: true }).extend({
297
+ uri: z4.string().min(1).max(PRIVATE_SKILL_MAX_URI_LENGTH),
298
+ body: privateSkillBodySchema
299
+ }).readonly();
300
+ var privateSkillSearchResultSchema = z4.strictObject({
301
+ traceId: z4.string().uuid(),
302
+ query: z4.string().max(4096),
303
+ mode: z4.enum(["discovery", "automatic", "explicit"]),
304
+ candidates: z4.array(z4.strictObject({
305
+ uri: z4.string().max(PRIVATE_SKILL_MAX_URI_LENGTH),
306
+ name: z4.string(),
307
+ description: z4.string(),
308
+ score: z4.number().finite(),
309
+ rank: z4.number().int().positive(),
310
+ invocation: z4.enum(["automatic", "explicit"]),
311
+ digest: z4.string(),
312
+ matched: z4.array(z4.string()).readonly()
313
+ }).readonly()).max(50).readonly(),
314
+ abstained: z4.strictObject({
315
+ reason: z4.enum(["empty_query", "no_overlap", "below_threshold", "explicit_only"]),
316
+ hint: z4.string()
317
+ }).readonly().optional(),
318
+ elapsedMs: z4.number().finite().nonnegative()
319
+ }).readonly();
320
+ var privateSkillScopes = ["skills:read", "skills:write"];
321
+ var privateSkillIdentitySchema = z4.strictObject({
322
+ accountId: accountIdSchema,
323
+ generation: z4.number().int().positive().safe(),
324
+ deviceId: deviceIdSchema.nullable(),
325
+ scopes: z4.array(z4.enum(privateSkillScopes)).min(1).max(2).readonly()
326
+ }).readonly();
327
+ var principal = {
328
+ accountId: accountIdSchema,
329
+ generation: z4.number().int().positive().safe(),
330
+ shardId: z4.literal("activity-00"),
331
+ issuer: deploymentOriginSchema,
332
+ scopes: z4.array(z4.enum(privateSkillScopes)).min(1).max(2).readonly()
333
+ };
334
+ var privateSkillPrincipalSchema = z4.discriminatedUnion("kind", [
335
+ z4.strictObject({
336
+ ...principal,
337
+ kind: z4.literal("browser"),
338
+ sessionId: z4.string().min(32).max(128),
339
+ deviceId: z4.null(),
340
+ tokenHash: z4.null()
341
+ }),
342
+ z4.strictObject({
343
+ ...principal,
344
+ kind: z4.literal("device"),
345
+ sessionId: z4.null(),
346
+ deviceId: deviceIdSchema,
347
+ tokenHash: z4.string().regex(/^[A-Za-z0-9_-]{43}$/)
348
+ }),
349
+ mcpPrivatePrincipalSchema
350
+ ]).readonly();
351
+ var PrivateSkillContractError = class extends Error {
352
+ code;
353
+ name = "PrivateSkillContractError";
354
+ constructor(code) {
355
+ super(code);
356
+ this.code = code;
357
+ }
358
+ };
359
+
360
+ // ../shared/dist/activity-content.js
361
+ import { z as z6 } from "zod";
362
+
363
+ // ../shared/dist/activity-consent.js
364
+ import { z as z5 } from "zod";
365
+ var retentionSchema = z5.strictObject({
366
+ contentDays: revisionSchema.min(1).default(30),
367
+ projectionDays: revisionSchema.min(1).default(30),
368
+ backupDays: z5.number().int().min(0).max(30).default(30)
369
+ }).readonly();
370
+ var scopeSchema = z5.strictObject({
371
+ deviceId: deviceIdSchema,
372
+ projectIds: z5.array(z5.string().min(1).max(512)).min(1).max(1e3).readonly(),
373
+ rootIds: z5.array(z5.string().min(1).max(512)).max(1e3).readonly()
374
+ }).readonly();
375
+ var common = {
376
+ version: revisionSchema.min(1),
377
+ scope: scopeSchema,
378
+ retention: retentionSchema.default({ contentDays: 30, projectionDays: 30, backupDays: 30 }),
379
+ // Explicit historical consent applies independently to metadata and content.
380
+ backfill: backfillReferenceSchema.unwrap().extend({ range: timeRangeSchema }).readonly().optional()
381
+ };
382
+ var consentSchema = z5.discriminatedUnion("mode", [
383
+ z5.strictObject({ mode: z5.literal("local-only") }),
384
+ z5.strictObject({
385
+ ...common,
386
+ mode: z5.literal("metadata"),
387
+ grantedAtMs: timestampSchema
388
+ }),
389
+ z5.strictObject({
390
+ ...common,
391
+ mode: z5.literal("managed-content"),
392
+ grantedAtMs: timestampSchema,
393
+ serverProcessingAcknowledged: z5.literal(true),
394
+ contentKinds: z5.array(contentKindSchema).min(1).max(7).readonly(),
395
+ externalModelTransfer: z5.literal(false).default(false)
396
+ })
397
+ ]).readonly();
398
+ var defaultConsent = consentSchema.parse({ mode: "local-only" });
399
+
400
+ // ../shared/dist/activity-content.js
401
+ var MAX_CONTENT_CHUNK_BYTES = 128 * 1024;
402
+ var MAX_CONTENT_BYTES = 16 * 1024 * 1024;
403
+ var MAX_CONTENT_CHUNKS = 128;
404
+ var encoder = new TextEncoder();
405
+ var plaintextHashSchema = z6.string().regex(/^[a-f0-9]{64}$/);
406
+ var byteCount = z6.number().int().min(1).max(MAX_CONTENT_CHUNK_BYTES);
407
+ var wireSize = (value) => encoder.encode(JSON.stringify(value)).byteLength <= MAX_BATCH_BYTES;
408
+ var identity2 = activityBatchSchema.unwrap().pick({
409
+ batchId: true,
410
+ deviceId: true,
411
+ sourceDomain: true,
412
+ generation: true,
413
+ consentVersion: true,
414
+ projectId: true,
415
+ rootId: true,
416
+ range: true,
417
+ backfill: true
418
+ }).shape;
419
+ var contentChunkRefSchema = z6.strictObject({
420
+ index: z6.number().int().min(0).max(MAX_CONTENT_CHUNKS - 1),
421
+ plaintextHash: plaintextHashSchema,
422
+ bytes: byteCount,
423
+ revision: revisionSchema
424
+ }).readonly();
425
+ var contentChunkUploadSchema = z6.strictObject({
426
+ ...identity2,
427
+ schemaVersion: z6.literal(2),
428
+ ...contentChunkRefSchema.unwrap().shape,
429
+ body: z6.string().min(4).max(4 * Math.ceil(MAX_CONTENT_CHUNK_BYTES / 3)).regex(/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/)
430
+ }).refine(wireSize, "chunk JSON exceeds 256 KiB").readonly();
431
+ var contentBatchSchema = z6.strictObject({
432
+ ...identity2,
433
+ schemaVersion: z6.literal(2),
434
+ sequence: activityBatchSchema.unwrap().shape.sequence,
435
+ journal: activityBatchSchema.unwrap().shape.journal,
436
+ metadataMutations: z6.array(metadataMutationSchema).max(100).readonly(),
437
+ chunks: z6.array(contentChunkRefSchema).min(1).max(MAX_CONTENT_CHUNKS).readonly(),
438
+ contentHash: plaintextHashSchema,
439
+ totalBytes: z6.number().int().min(1).max(MAX_CONTENT_BYTES)
440
+ }).superRefine((batch, ctx) => {
441
+ if (batch.chunks.some((chunk, index) => chunk.index !== index)) {
442
+ ctx.addIssue({ code: "custom", message: "chunk indexes must be ordered and contiguous" });
443
+ }
444
+ if (batch.chunks.reduce((total, chunk) => total + chunk.bytes, 0) !== batch.totalBytes) {
445
+ ctx.addIssue({ code: "custom", message: "chunk byte totals do not match" });
446
+ }
447
+ if (!wireSize(batch))
448
+ ctx.addIssue({ code: "custom", message: "batch JSON exceeds 256 KiB" });
449
+ if (batch.metadataMutations.length > 0) {
450
+ const { chunks, contentHash, totalBytes, metadataMutations, ...common2 } = batch;
451
+ parseActivityBatch({ ...common2, schemaVersion: 1, mutations: metadataMutations });
452
+ }
453
+ }).readonly();
454
+ async function hashContent(bytes) {
455
+ const digest = await globalThis.crypto.subtle.digest("SHA-256", new Uint8Array(bytes));
456
+ return Array.from(new Uint8Array(digest), (byte) => byte.toString(16).padStart(2, "0")).join("");
457
+ }
458
+ var contentTables = [
459
+ "skills",
460
+ "sessions",
461
+ "events",
462
+ "loads",
463
+ "eval_cases",
464
+ "otel_spans",
465
+ "herdr_workspaces",
466
+ "herdr_tabs",
467
+ "herdr_panes",
468
+ "pane_sessions",
469
+ "workflow_specs",
470
+ "flows",
471
+ "flow_steps",
472
+ "load_candidates",
473
+ "recording_clock"
474
+ ];
475
+ var contentTableSchema = z6.enum(contentTables);
476
+ var contentScalarSchema = z6.union([z6.string().max(MAX_CONTENT_BYTES), z6.number().finite(), z6.null()]);
477
+ var contentValuesSchema = z6.record(z6.string(), contentScalarSchema).readonly();
478
+ var numericColumns = {
479
+ skills: ["mtime_ms", "removed_at"],
480
+ sessions: ["started_at", "ended_at"],
481
+ events: ["ts", "text_length"],
482
+ loads: ["created_at"],
483
+ eval_cases: ["created_at"],
484
+ otel_spans: ["start_ms", "end_ms", "received_at"],
485
+ herdr_workspaces: ["created_ms", "closed_ms"],
486
+ herdr_tabs: ["created_ms", "closed_ms"],
487
+ herdr_panes: ["created_ms", "closed_ms", "last_seen_ms"],
488
+ pane_sessions: ["first_seen_ms", "last_seen_ms"],
489
+ workflow_specs: ["version", "created_ms"],
490
+ flows: ["registered_ms", "ended_ms", "start_order", "end_order"],
491
+ flow_steps: ["registered_ms"],
492
+ load_candidates: ["ts"],
493
+ recording_clock: ["singleton", "position"]
494
+ };
495
+ var textColumns = {
496
+ skills: [
497
+ "uri",
498
+ "root_id",
499
+ "name",
500
+ "description",
501
+ "tags_json",
502
+ "when_to_use",
503
+ "examples_json",
504
+ "aliases_ko_json",
505
+ "group_id",
506
+ "group_stage",
507
+ "invocation",
508
+ "body_head",
509
+ "digest",
510
+ "manifest_digest",
511
+ "resources_json"
512
+ ],
513
+ sessions: [
514
+ "id",
515
+ "runtime",
516
+ "runtime_session_id",
517
+ "conversation_id",
518
+ "client_name",
519
+ "cwd",
520
+ "first_prompt",
521
+ "end_orders_json"
522
+ ],
523
+ events: [
524
+ "id",
525
+ "kind",
526
+ "source",
527
+ "session_id",
528
+ "attribution_method",
529
+ "attribution_reason",
530
+ "runtime",
531
+ "trace_id",
532
+ "load_id",
533
+ "skill_uri",
534
+ "tool_use_id",
535
+ "text",
536
+ "text_digest",
537
+ "data_json",
538
+ "source_key",
539
+ "turn_key",
540
+ "call_id",
541
+ "span_id",
542
+ "recording_orders_json"
543
+ ],
544
+ loads: ["load_id", "trace_id", "uri", "manifest_digest", "resources_json"],
545
+ eval_cases: ["id", "query", "expected_uri", "from_trace_id"],
546
+ otel_spans: [
547
+ "trace_id",
548
+ "span_id",
549
+ "parent_span_id",
550
+ "name",
551
+ "runtime",
552
+ "conversation_id",
553
+ "turn_key",
554
+ "call_id",
555
+ "recording_orders_json"
556
+ ],
557
+ herdr_workspaces: ["id", "label"],
558
+ herdr_tabs: ["id", "workspace_id", "label"],
559
+ herdr_panes: ["id", "workspace_id", "tab_id", "label", "cwd", "agent"],
560
+ pane_sessions: ["pane_id", "agent", "source", "agent_session_value", "session_id"],
561
+ workflow_specs: ["id", "name", "body_json", "digest"],
562
+ flows: [
563
+ "id",
564
+ "workspace_id",
565
+ "tab_id",
566
+ "spec_id",
567
+ "label",
568
+ "start_event_ids_json",
569
+ "end_event_ids_json",
570
+ "end_sessions_json",
571
+ "end_spans_json",
572
+ "start_order_domain",
573
+ "end_order_domain"
574
+ ],
575
+ flow_steps: ["flow_id", "pane_id", "step_id"],
576
+ load_candidates: ["load_id", "session_id"],
577
+ recording_clock: ["domain"]
578
+ };
579
+ var nonTimeColumns = /* @__PURE__ */ new Set(["text_length", "version", "start_order", "end_order", "singleton", "position"]);
580
+ var contentRowSchema = z6.strictObject({
581
+ table: contentTableSchema,
582
+ key: z6.string().max(MAX_CONTENT_BYTES),
583
+ revision: revisionSchema,
584
+ operation: z6.enum(["upsert", "delete"]),
585
+ sourceOrder: z6.number().int().min(Number.MIN_SAFE_INTEGER).max(Number.MAX_SAFE_INTEGER).nullable(),
586
+ values: contentValuesSchema.nullable()
587
+ }).superRefine((row, ctx) => {
588
+ if (row.operation === "delete" !== (row.values === null)) {
589
+ ctx.addIssue({ code: "custom", message: "delete requires null values; upsert requires values" });
590
+ }
591
+ for (const [column, value] of Object.entries(row.values ?? {})) {
592
+ const numeric = numericColumns[row.table].includes(column);
593
+ if (!numeric && !textColumns[row.table].includes(column)) {
594
+ ctx.addIssue({ code: "custom", path: ["values", column], message: "unknown source column" });
595
+ } else if (value !== null && typeof value !== (numeric ? "number" : "string")) {
596
+ ctx.addIssue({ code: "custom", path: ["values", column], message: "incorrect source column type" });
597
+ } else if (numeric && !nonTimeColumns.has(column) && !timestampSchema.nullable().safeParse(value).success) {
598
+ ctx.addIssue({ code: "custom", path: ["values", column], message: "invalid source timestamp" });
599
+ }
600
+ }
601
+ }).readonly();
602
+ var contentDocumentSchema = z6.strictObject({
603
+ schemaVersion: z6.literal(2),
604
+ rows: z6.array(contentRowSchema).max(1e4).readonly()
605
+ }).refine((document) => encoder.encode(JSON.stringify(document)).byteLength <= MAX_CONTENT_BYTES, "document exceeds 16 MiB").readonly();
606
+ var localRowSchema = z6.strictObject({
607
+ ...contentRowSchema.unwrap().shape,
608
+ beforeValues: contentValuesSchema.nullable().optional()
609
+ }).readonly();
610
+
611
+ // ../shared/dist/private-skill-package.js
612
+ var encoder2 = new TextEncoder();
613
+ var archiveSignatures = [
614
+ [80, 75, 3, 4],
615
+ [80, 75, 5, 6],
616
+ [80, 75, 7, 8],
617
+ [31, 139],
618
+ [66, 90, 104],
619
+ [55, 122, 188, 175, 39, 28],
620
+ [82, 97, 114, 33],
621
+ [253, 55, 122, 88, 90, 0]
622
+ ];
623
+ function rejectArchive(bytes) {
624
+ if (archiveSignatures.some((signature) => signature.every((byte, index) => bytes[index] === byte)) || bytes.length >= 262 && new TextDecoder().decode(bytes.subarray(257, 262)) === "ustar") {
625
+ throw new PrivateSkillContractError("archive_not_supported");
626
+ }
627
+ }
628
+ function encodePrivateSkillBytes(bytes) {
629
+ const parts = [];
630
+ for (let offset = 0; offset < bytes.length; offset += 32768) {
631
+ parts.push(String.fromCharCode(...bytes.subarray(offset, offset + 32768)));
632
+ }
633
+ return btoa(parts.join(""));
634
+ }
635
+ function decodePrivateSkillBytes(body) {
636
+ const binary = atob(body);
637
+ if (btoa(binary) !== body)
638
+ throw new PrivateSkillContractError("package_integrity");
639
+ const bytes = new Uint8Array(binary.length);
640
+ for (let index = 0; index < binary.length; index++)
641
+ bytes[index] = binary.charCodeAt(index);
642
+ return bytes;
643
+ }
644
+ async function createPrivateSkillPackage(files) {
645
+ if (files.length < 1 || files.length > PRIVATE_SKILL_MAX_RESOURCES || files.some((file) => file.bytes.length > PRIVATE_SKILL_MAX_RESOURCE_BYTES) || files.reduce((sum, file) => sum + file.bytes.length, 0) > PRIVATE_SKILL_MAX_BYTES) {
646
+ throw new PrivateSkillContractError("invalid_resource");
647
+ }
648
+ const ordered = [...files].sort((a, b) => a.path < b.path ? -1 : a.path > b.path ? 1 : 0);
649
+ const resources = [];
650
+ const contents = [];
651
+ for (const file of ordered) {
652
+ rejectArchive(file.bytes);
653
+ const path = privateSkillPathSchema.parse(file.path);
654
+ resources.push({
655
+ path,
656
+ mediaType: file.mediaType,
657
+ bytes: file.bytes.length,
658
+ digest: privateSkillDigestSchema.parse(await hashContent(file.bytes))
659
+ });
660
+ contents.push({ path, body: encodePrivateSkillBytes(file.bytes) });
661
+ }
662
+ const manifest = privateSkillManifestSchema.parse({ schemaVersion: 1, entrypoint: "SKILL.md", resources });
663
+ return privateSkillPackageSchema.parse({
664
+ manifest,
665
+ contents,
666
+ manifestDigest: await hashContent(encoder2.encode(JSON.stringify(manifest)))
667
+ });
668
+ }
669
+ async function verifyPrivateSkillPackage(input) {
670
+ const value = privateSkillPackageSchema.parse(input);
671
+ if (await hashContent(encoder2.encode(JSON.stringify(value.manifest))) !== value.manifestDigest || value.contents.length !== value.manifest.resources.length) {
672
+ throw new PrivateSkillContractError("package_integrity");
673
+ }
674
+ const files = /* @__PURE__ */ new Map();
675
+ for (const [index, resource] of value.manifest.resources.entries()) {
676
+ const content = value.contents[index];
677
+ if (content === void 0 || content.path !== resource.path) {
678
+ throw new PrivateSkillContractError("package_integrity");
679
+ }
680
+ const bytes = decodePrivateSkillBytes(content.body);
681
+ rejectArchive(bytes);
682
+ if (bytes.length !== resource.bytes || await hashContent(bytes) !== resource.digest) {
683
+ throw new PrivateSkillContractError("package_integrity");
684
+ }
685
+ files.set(resource.path, bytes);
686
+ }
687
+ return { package: value, files };
688
+ }
689
+
690
+ // ../shared/dist/private-skill-media.js
691
+ var TEXT_TYPES = {
692
+ md: "text/markdown",
693
+ markdown: "text/markdown",
694
+ txt: "text/plain",
695
+ json: "application/json",
696
+ yaml: "application/yaml",
697
+ yml: "application/yaml",
698
+ toml: "application/toml",
699
+ csv: "text/csv",
700
+ html: "text/html",
701
+ css: "text/css",
702
+ js: "text/javascript",
703
+ mjs: "text/javascript",
704
+ ts: "text/plain",
705
+ py: "text/x-python",
706
+ sh: "application/x-sh",
707
+ svg: "image/svg+xml"
708
+ };
709
+ function privateSkillMediaType(path, reportedType = "") {
710
+ const extension = /\.([a-z0-9]+)$/i.exec(path)?.[1]?.toLowerCase();
711
+ const known = extension === void 0 ? void 0 : TEXT_TYPES[extension];
712
+ if (known !== void 0)
713
+ return known;
714
+ const reported = reportedType.split(";")[0]?.trim().toLowerCase() ?? "";
715
+ return /^[a-z0-9!#$&^_.+-]+\/[a-z0-9!#$&^_.+-]+$/.test(reported) && reported.length <= 128 ? reported : "application/octet-stream";
716
+ }
717
+ export {
718
+ PRIVATE_SKILL_MAX_BYTES,
719
+ PRIVATE_SKILL_MAX_REQUEST_BYTES,
720
+ PRIVATE_SKILL_MAX_RESOURCES,
721
+ PRIVATE_SKILL_MAX_RESOURCE_BYTES,
722
+ createPrivateSkillPackage,
723
+ privateSkillBodySchema,
724
+ privateSkillDetailSchema,
725
+ privateSkillDigestSchema,
726
+ privateSkillExportSchema,
727
+ privateSkillHeadSchema,
728
+ privateSkillIdSchema,
729
+ privateSkillIdentitySchema,
730
+ privateSkillMediaType,
731
+ privateSkillPackageSchema,
732
+ privateSkillPathSchema,
733
+ verifyPrivateSkillPackage
734
+ };