@nebutra/agent-runtime 0.2.1 → 2.0.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 (114) hide show
  1. package/LICENSE +21 -676
  2. package/README.md +33 -10
  3. package/dist/adapters/index.d.ts +24 -5
  4. package/dist/adapters/index.js +27 -0
  5. package/dist/adapters/index.js.map +1 -1
  6. package/dist/{chunk-KCNN4QUQ.js → chunk-5UGIUYJR.js} +4 -4
  7. package/dist/chunk-7ELA4SWE.js +73 -0
  8. package/dist/chunk-7ELA4SWE.js.map +1 -0
  9. package/dist/chunk-Q62VKHIT.js +178 -0
  10. package/dist/chunk-Q62VKHIT.js.map +1 -0
  11. package/dist/chunk-VXILZAXK.js +541 -0
  12. package/dist/chunk-VXILZAXK.js.map +1 -0
  13. package/dist/command-exec.d.ts +45 -0
  14. package/dist/command-exec.js +15 -0
  15. package/dist/command-exec.js.map +1 -0
  16. package/dist/index.d.ts +3 -2
  17. package/dist/index.js +81 -28
  18. package/dist/index.js.map +1 -1
  19. package/dist/orchestration.d.ts +42 -1
  20. package/dist/orchestration.js +7 -3
  21. package/dist/pulsar.js +2 -2
  22. package/dist/sandbox-DfcRttXt.d.ts +219 -0
  23. package/dist/sandbox.d.ts +2 -64
  24. package/dist/sandbox.js +25 -3
  25. package/package.json +81 -30
  26. package/.turbo/turbo-build.log +0 -130
  27. package/.turbo/turbo-test.log +0 -47
  28. package/.turbo/turbo-typecheck.log +0 -4
  29. package/CHANGELOG.md +0 -250
  30. package/dist/chunk-MUF7ZZTO.js +0 -57
  31. package/dist/chunk-MUF7ZZTO.js.map +0 -1
  32. package/dist/chunk-MX2WL43P.js +0 -90
  33. package/dist/chunk-MX2WL43P.js.map +0 -1
  34. package/examples/pulsar-quickstart.ts +0 -35
  35. package/examples/resume-branch.ts +0 -45
  36. package/examples/subagent-fanout.ts +0 -20
  37. package/src/adapters/dispatcher-sse.test.ts +0 -218
  38. package/src/adapters/dispatcher-sse.ts +0 -222
  39. package/src/adapters/index.ts +0 -18
  40. package/src/adapters/mcp-catalog.test.ts +0 -213
  41. package/src/adapters/mcp-catalog.ts +0 -188
  42. package/src/adapters/prisma-rollout.test.ts +0 -153
  43. package/src/adapters/prisma-rollout.ts +0 -104
  44. package/src/agent-runtime.test.ts +0 -176
  45. package/src/artifact-stream.test.ts +0 -330
  46. package/src/artifact-stream.ts +0 -453
  47. package/src/channel-gateway.test.ts +0 -432
  48. package/src/channel-gateway.ts +0 -357
  49. package/src/cli.ts +0 -49
  50. package/src/code-review.test.ts +0 -501
  51. package/src/code-review.ts +0 -495
  52. package/src/command-suggestions.test.ts +0 -251
  53. package/src/command-suggestions.ts +0 -338
  54. package/src/commands.test.ts +0 -184
  55. package/src/commands.ts +0 -140
  56. package/src/commit-message.test.ts +0 -249
  57. package/src/commit-message.ts +0 -180
  58. package/src/context-compaction.test.ts +0 -522
  59. package/src/context-compaction.ts +0 -438
  60. package/src/definitions.test.ts +0 -78
  61. package/src/definitions.ts +0 -190
  62. package/src/deployment-status.test.ts +0 -215
  63. package/src/deployment-status.ts +0 -227
  64. package/src/design-context.test.ts +0 -195
  65. package/src/design-context.ts +0 -198
  66. package/src/dispatcher.test.ts +0 -234
  67. package/src/dispatcher.ts +0 -189
  68. package/src/durable-turn.test.ts +0 -209
  69. package/src/durable-turn.ts +0 -135
  70. package/src/edit-planner.test.ts +0 -204
  71. package/src/edit-planner.ts +0 -325
  72. package/src/fuzzy-match.test.ts +0 -311
  73. package/src/fuzzy-match.ts +0 -444
  74. package/src/hook-pipeline.test.ts +0 -279
  75. package/src/hook-pipeline.ts +0 -373
  76. package/src/inbound-admission.test.ts +0 -394
  77. package/src/inbound-admission.ts +0 -246
  78. package/src/index.ts +0 -49
  79. package/src/loop.test.ts +0 -161
  80. package/src/loop.ts +0 -211
  81. package/src/mcp-bridge.test.ts +0 -165
  82. package/src/mcp-bridge.ts +0 -81
  83. package/src/memory-provider.test.ts +0 -232
  84. package/src/memory-provider.ts +0 -257
  85. package/src/model.ts +0 -168
  86. package/src/orchestration.test.ts +0 -53
  87. package/src/orchestration.ts +0 -146
  88. package/src/permission-ruleset.test.ts +0 -301
  89. package/src/permission-ruleset.ts +0 -1
  90. package/src/policy.ts +0 -151
  91. package/src/project-repo.test.ts +0 -232
  92. package/src/project-repo.ts +0 -311
  93. package/src/protocol.ts +0 -159
  94. package/src/pulsar.test.ts +0 -156
  95. package/src/pulsar.ts +0 -322
  96. package/src/rollout-store-persistent.test.ts +0 -217
  97. package/src/rollout-store-persistent.ts +0 -166
  98. package/src/rollout.ts +0 -150
  99. package/src/sandbox.ts +0 -113
  100. package/src/session-share.test.ts +0 -360
  101. package/src/session-share.ts +0 -310
  102. package/src/skill-distillation.test.ts +0 -177
  103. package/src/skill-distillation.ts +0 -369
  104. package/src/skills.test.ts +0 -277
  105. package/src/skills.ts +0 -277
  106. package/src/subagents.test.ts +0 -290
  107. package/src/subagents.ts +0 -332
  108. package/src/tools.test.ts +0 -12
  109. package/src/tools.ts +0 -129
  110. package/src/workbench.test.ts +0 -0
  111. package/src/workbench.ts +0 -0
  112. package/tsconfig.json +0 -12
  113. package/tsup.config.ts +0 -36
  114. /package/dist/{chunk-KCNN4QUQ.js.map → chunk-5UGIUYJR.js.map} +0 -0
@@ -1,277 +0,0 @@
1
- import { describe, expect, it, vi } from "vitest";
2
- import { DefinitionResolver } from "./definitions";
3
- import { buildSkillListing, expandSkill, type SkillRecord } from "./skills";
4
-
5
- const skill = (
6
- over: Partial<SkillRecord> &
7
- Pick<SkillRecord, "slug" | "tenantId" | "sourceTier"> & {
8
- name?: string;
9
- description?: string;
10
- whenToUse?: string;
11
- allowedTools?: string[];
12
- model?: string;
13
- effort?: "low" | "medium" | "high";
14
- executionMode?: "inline" | "fork";
15
- paths?: string[];
16
- },
17
- ): SkillRecord => ({
18
- bodyRef: over.bodyRef ?? `${over.slug}.body`,
19
- ...over,
20
- frontmatter: {
21
- name: over.name ?? over.slug,
22
- description: over.description ?? "",
23
- allowedTools: over.allowedTools ?? [],
24
- disallowedTools: [],
25
- argNames: [],
26
- modelInvocable: true,
27
- userInvocable: true,
28
- executionMode: over.executionMode ?? "inline",
29
- paths: over.paths ?? [],
30
- whenToUse: over.whenToUse,
31
- model: over.model,
32
- effort: over.effort,
33
- },
34
- });
35
-
36
- describe("buildSkillListing", () => {
37
- it("lists only name/description/whenToUse per skill", () => {
38
- const r = new DefinitionResolver<SkillRecord>([
39
- skill({
40
- slug: "deploy",
41
- tenantId: "t",
42
- sourceTier: "workspace",
43
- description: "ship it",
44
- whenToUse: "when releasing",
45
- }),
46
- ]);
47
- const out = buildSkillListing(r, { tenantId: "t" });
48
- expect(out.entries).toHaveLength(1);
49
- expect(out.entries[0]).toMatchObject({
50
- name: "deploy",
51
- description: "ship it",
52
- whenToUse: "when releasing",
53
- });
54
- expect(out.text).toContain("deploy");
55
- expect(out.text).toContain("ship it");
56
- });
57
-
58
- it("truncates per-entry description to maxListingDescChars", () => {
59
- const long = "x".repeat(500);
60
- const r = new DefinitionResolver<SkillRecord>([
61
- skill({ slug: "a", tenantId: "t", sourceTier: "workspace", description: long }),
62
- ]);
63
- const out = buildSkillListing(r, { tenantId: "t" }, { maxListingDescChars: 10 });
64
- expect(out.entries[0]?.description.length).toBeLessThanOrEqual(10);
65
- });
66
-
67
- it("first-party (bundled/builtin) is never truncated and always included even past budget", () => {
68
- const long = "y".repeat(400);
69
- const r = new DefinitionResolver<SkillRecord>([
70
- skill({ slug: "fp", tenantId: "t", sourceTier: "bundled", description: long }),
71
- skill({ slug: "lo", tenantId: "t", sourceTier: "workspace", description: long }),
72
- ]);
73
- const out = buildSkillListing(
74
- r,
75
- { tenantId: "t" },
76
- { contextWindowTokens: 1, budgetPercent: 0.01, maxListingDescChars: 1000 },
77
- );
78
- const fp = out.entries.find((e) => e.name === "fp");
79
- expect(fp).toBeDefined();
80
- expect(fp?.description).toBe(long);
81
- expect(fp?.degraded).toBe(false);
82
- });
83
-
84
- it("lower-tier skills degrade to names-only then drop when budget exceeded", () => {
85
- const long = "z".repeat(400);
86
- const r = new DefinitionResolver<SkillRecord>([
87
- skill({ slug: "s1", tenantId: "t", sourceTier: "workspace", description: long }),
88
- skill({ slug: "s2", tenantId: "t", sourceTier: "workspace", description: long }),
89
- skill({ slug: "s3", tenantId: "t", sourceTier: "workspace", description: long }),
90
- ]);
91
- const tight = buildSkillListing(
92
- r,
93
- { tenantId: "t" },
94
- { contextWindowTokens: 100, budgetPercent: 0.01, maxListingDescChars: 1000 },
95
- );
96
- // some degrade to names-only (no description)
97
- expect(tight.entries.some((e) => e.degraded && e.description === "")).toBe(true);
98
-
99
- const veryTight = buildSkillListing(
100
- r,
101
- { tenantId: "t" },
102
- { contextWindowTokens: 1, budgetPercent: 0.01, maxListingDescChars: 1000 },
103
- );
104
- // beyond names-only, lower-tier entries drop entirely
105
- expect(veryTight.entries.length).toBeLessThan(3);
106
- expect(tight.entries.length).toBeGreaterThanOrEqual(veryTight.entries.length);
107
- });
108
-
109
- it("suppresses skills whose slug is in ctx.loadedSlugs", () => {
110
- const r = new DefinitionResolver<SkillRecord>([
111
- skill({ slug: "loaded", tenantId: "t", sourceTier: "workspace" }),
112
- skill({ slug: "fresh", tenantId: "t", sourceTier: "workspace" }),
113
- ]);
114
- const out = buildSkillListing(r, {
115
- tenantId: "t",
116
- loadedSlugs: new Set(["loaded"]),
117
- });
118
- expect(out.entries.map((e) => e.name)).toEqual(["fresh"]);
119
- });
120
-
121
- it("path-activated skills hidden until a touched path matches its glob", () => {
122
- const r = new DefinitionResolver<SkillRecord>([
123
- skill({
124
- slug: "gated",
125
- tenantId: "t",
126
- sourceTier: "workspace",
127
- paths: ["src/**/*.ts"],
128
- }),
129
- skill({ slug: "always", tenantId: "t", sourceTier: "workspace" }),
130
- ]);
131
- const hidden = buildSkillListing(r, { tenantId: "t" });
132
- expect(hidden.entries.map((e) => e.name)).toEqual(["always"]);
133
-
134
- const shown = buildSkillListing(r, { tenantId: "t" }, { touchedPaths: ["src/foo/bar.ts"] });
135
- expect(shown.entries.map((e) => e.name).sort()).toEqual(["always", "gated"]);
136
- });
137
-
138
- it("glob supports *, ** and exact match", () => {
139
- const r = new DefinitionResolver<SkillRecord>([
140
- skill({ slug: "star", tenantId: "t", sourceTier: "workspace", paths: ["*.md"] }),
141
- skill({ slug: "exact", tenantId: "t", sourceTier: "workspace", paths: ["a/b.txt"] }),
142
- ]);
143
- const a = buildSkillListing(r, { tenantId: "t" }, { touchedPaths: ["README.md"] });
144
- expect(a.entries.map((e) => e.name)).toEqual(["star"]);
145
- const b = buildSkillListing(r, { tenantId: "t" }, { touchedPaths: ["a/b.txt"] });
146
- expect(b.entries.map((e) => e.name)).toEqual(["exact"]);
147
- const none = buildSkillListing(r, { tenantId: "t" }, { touchedPaths: ["a/c.txt"] });
148
- expect(none.entries).toHaveLength(0);
149
- });
150
-
151
- it("empty tenant fails closed", () => {
152
- const r = new DefinitionResolver<SkillRecord>([]);
153
- expect(() => buildSkillListing(r, { tenantId: "" })).toThrow(/tenant/i);
154
- });
155
-
156
- it("cross-tenant isolation (resolver enforced)", () => {
157
- const r = new DefinitionResolver<SkillRecord>([
158
- skill({ slug: "a", tenantId: "t_a", sourceTier: "workspace" }),
159
- ]);
160
- expect(buildSkillListing(r, { tenantId: "t_b" }).entries).toHaveLength(0);
161
- });
162
-
163
- it("is deterministic — same inputs produce same output", () => {
164
- const r = new DefinitionResolver<SkillRecord>([
165
- skill({ slug: "a", tenantId: "t", sourceTier: "workspace", description: "aa" }),
166
- skill({ slug: "b", tenantId: "t", sourceTier: "workspace", description: "bb" }),
167
- ]);
168
- const o1 = buildSkillListing(r, { tenantId: "t" });
169
- const o2 = buildSkillListing(r, { tenantId: "t" });
170
- expect(o1.text).toBe(o2.text);
171
- });
172
- });
173
-
174
- describe("expandSkill", () => {
175
- const base = (slug: string) => `/skills/${slug}`;
176
-
177
- it("expands body, prepends resource base line, substitutes args + vars", async () => {
178
- const s = skill({
179
- slug: "deploy",
180
- tenantId: "t",
181
- sourceTier: "workspace",
182
- allowedTools: ["Bash", "Edit"],
183
- });
184
- const bodyLoader = vi.fn(async () => "deploy ${env} via ${SESSION}");
185
- const out = await expandSkill(s, {
186
- tenantId: "t",
187
- args: { env: "prod" },
188
- vars: { SESSION: "s1" },
189
- bodyLoader,
190
- skillResourceBase: base,
191
- });
192
- expect(bodyLoader).toHaveBeenCalledTimes(1);
193
- expect(bodyLoader).toHaveBeenCalledWith("deploy.body");
194
- const content = out.messages.map((m) => m.content).join("\n");
195
- expect(content).toContain("Base directory for this skill: /skills/deploy");
196
- expect(content).toContain("deploy prod via s1");
197
- expect(out.allowedTools).toEqual(["Bash", "Edit"]);
198
- expect(out.executionMode).toBe("inline");
199
- });
200
-
201
- it("returns model override + effort + fork mode", async () => {
202
- const s = skill({
203
- slug: "heavy",
204
- tenantId: "t",
205
- sourceTier: "workspace",
206
- model: "big-model",
207
- effort: "high",
208
- executionMode: "fork",
209
- });
210
- const out = await expandSkill(s, {
211
- tenantId: "t",
212
- args: {},
213
- vars: {},
214
- bodyLoader: async () => "body",
215
- skillResourceBase: base,
216
- });
217
- expect(out.modelOverride).toBe("big-model");
218
- expect(out.effort).toBe("high");
219
- expect(out.executionMode).toBe("fork");
220
- });
221
-
222
- it("body loader is lazy — only invoked on expand", async () => {
223
- const r = new DefinitionResolver<SkillRecord>([
224
- skill({ slug: "lazy", tenantId: "t", sourceTier: "workspace" }),
225
- ]);
226
- const bodyLoader = vi.fn(async () => "b");
227
- buildSkillListing(r, { tenantId: "t" });
228
- expect(bodyLoader).not.toHaveBeenCalled();
229
- await expandSkill(r.resolveOne("lazy", { tenantId: "t" })!, {
230
- tenantId: "t",
231
- args: {},
232
- vars: {},
233
- bodyLoader,
234
- skillResourceBase: base,
235
- });
236
- expect(bodyLoader).toHaveBeenCalledTimes(1);
237
- });
238
-
239
- it("empty tenant fails closed on expand", async () => {
240
- const s = skill({ slug: "x", tenantId: "t", sourceTier: "workspace" });
241
- await expect(
242
- expandSkill(s, {
243
- tenantId: "",
244
- args: {},
245
- vars: {},
246
- bodyLoader: async () => "b",
247
- skillResourceBase: base,
248
- }),
249
- ).rejects.toThrow(/tenant/i);
250
- });
251
-
252
- it("cross-tenant expand fails closed", async () => {
253
- const s = skill({ slug: "x", tenantId: "t_a", sourceTier: "workspace" });
254
- await expect(
255
- expandSkill(s, {
256
- tenantId: "t_b",
257
- args: {},
258
- vars: {},
259
- bodyLoader: async () => "b",
260
- skillResourceBase: base,
261
- }),
262
- ).rejects.toThrow(/tenant/i);
263
- });
264
-
265
- it("does not execute any shell from the body (no command substitution)", async () => {
266
- const s = skill({ slug: "x", tenantId: "t", sourceTier: "workspace" });
267
- const out = await expandSkill(s, {
268
- tenantId: "t",
269
- args: {},
270
- vars: {},
271
- bodyLoader: async () => "literal !`rm -rf /` stays literal",
272
- skillResourceBase: base,
273
- });
274
- const content = out.messages.map((m) => m.content).join("\n");
275
- expect(content).toContain("!`rm -rf /`");
276
- });
277
- });
package/src/skills.ts DELETED
@@ -1,277 +0,0 @@
1
- /**
2
- * Skills system (WRAP — progressive-disclosure capability).
3
- *
4
- * Faithful re-expression of the source harness's two-phase skill model:
5
- *
6
- * Phase 1 — Listing (cheap, always in context): a budget-bounded catalog
7
- * exposing only {name, description, whenToUse} per skill. First-party
8
- * skills (bundled/builtin tier) are never truncated and never dropped;
9
- * lower-tier skills degrade to names-only, then drop, as the context
10
- * budget is exhausted. Path-activated skills stay hidden until a touched
11
- * file matches one of their globs.
12
- *
13
- * Phase 2 — Invocation (lazy, on demand): expand the chosen skill's body
14
- * into turn messages, with arg/var substitution and a merged tool
15
- * allowlist contributed to the permission context.
16
- *
17
- * A skill IS a `Definition` — the same tenant-scoped layered resolver backs
18
- * the command registry and the subagent registry (see ./definitions).
19
- *
20
- * SECURITY: this re-expression intentionally drops the source's body-side
21
- * command-substitution (the upstream "!`…`" inline-shell facility). Skill
22
- * bodies are inert text; they NEVER trigger host shell execution here. All
23
- * entry points require a non-empty `tenantId` and fail closed; cross-tenant
24
- * inputs are rejected by the underlying `DefinitionResolver`. Pure data/logic
25
- * — no host filesystem access (resource base is an injected indirection).
26
- */
27
-
28
- import { estimateTokens as estimatePrimitiveTokens } from "@nebutra/ai-primitives";
29
- import { z } from "zod";
30
- import {
31
- type Definition,
32
- type DefinitionResolver,
33
- type ResolveContext,
34
- substituteArguments,
35
- } from "./definitions";
36
-
37
- /** A skill is just a resolvable `Definition`. */
38
- export type SkillRecord = Definition;
39
-
40
- /** Tiers treated as first-party (never truncated, never dropped). */
41
- const FIRST_PARTY_TIERS: ReadonlySet<string> = new Set(["bundled", "builtin"]);
42
- const REGEX_META_CHARS = new Set([
43
- ".",
44
- "+",
45
- "?",
46
- "^",
47
- "$",
48
- "{",
49
- "}",
50
- "(",
51
- ")",
52
- "|",
53
- "[",
54
- "]",
55
- "\\",
56
- ]);
57
-
58
- const isFirstParty = (s: SkillRecord): boolean => FIRST_PARTY_TIERS.has(s.sourceTier);
59
-
60
- /**
61
- * Listing budgets preserve the catalog degradation contract: very tight lower-
62
- * tier budgets should still degrade to names-only before dropping. Context
63
- * compaction uses the corrected 1.3 estimate; this listing surface deliberately
64
- * uses the shared primitive with no correction.
65
- */
66
- const estimateListingTokens = (text: string): number =>
67
- estimatePrimitiveTokens(text, { correction: 1 });
68
-
69
- // ── Phase 1: listing ─────────────────────────────────────────────────────────
70
-
71
- /** One catalog entry — only the cheap, always-in-context surface. */
72
- export interface SkillListingEntry {
73
- readonly name: string;
74
- readonly description: string;
75
- readonly whenToUse?: string | undefined;
76
- /** True when this entry was degraded to names-only by the budget. */
77
- readonly degraded: boolean;
78
- readonly firstParty: boolean;
79
- }
80
-
81
- export interface SkillListing {
82
- readonly entries: readonly SkillListingEntry[];
83
- readonly text: string;
84
- }
85
-
86
- const listingOptionsSchema = z.object({
87
- maxListingDescChars: z.number().int().positive().default(250),
88
- contextWindowTokens: z.number().int().positive().default(200_000),
89
- budgetPercent: z.number().positive().max(1).default(0.01),
90
- touchedPaths: z.array(z.string()).default([]),
91
- });
92
- export type SkillListingOptions = z.input<typeof listingOptionsSchema>;
93
-
94
- /** Minimal glob: `**` = any chars, `*` = any chars except `/`, else exact. */
95
- function globToRegExp(glob: string): RegExp {
96
- let out = "^";
97
- for (let i = 0; i < glob.length; i++) {
98
- const c = glob.charAt(i);
99
- if (c === "*") {
100
- if (glob[i + 1] === "*") {
101
- out += ".*";
102
- i++;
103
- } else {
104
- out += "[^/]*";
105
- }
106
- } else if (REGEX_META_CHARS.has(c)) {
107
- out += `\\${c}`;
108
- } else {
109
- out += c;
110
- }
111
- }
112
- return new RegExp(`${out}$`);
113
- }
114
-
115
- const pathMatches = (globs: readonly string[], touched: readonly string[]): boolean =>
116
- globs.some((g) => {
117
- const re = globToRegExp(g);
118
- return touched.some((p) => re.test(p));
119
- });
120
-
121
- /** Stable order: first-party first, then by slug — deterministic output. */
122
- function orderSkills(skills: readonly SkillRecord[]): SkillRecord[] {
123
- return [...skills].sort((a, b) => {
124
- const fa = isFirstParty(a) ? 0 : 1;
125
- const fb = isFirstParty(b) ? 0 : 1;
126
- if (fa !== fb) return fa - fb;
127
- return a.slug.localeCompare(b.slug);
128
- });
129
- }
130
-
131
- const truncate = (s: string, max: number): string => (s.length <= max ? s : s.slice(0, max));
132
-
133
- function renderEntry(e: SkillListingEntry): string {
134
- const head = e.whenToUse ? `- ${e.name} — ${e.whenToUse}` : `- ${e.name}`;
135
- return e.description ? `${head}\n ${e.description}` : head;
136
- }
137
-
138
- /**
139
- * Phase 1 — build the always-in-context skill catalog. Pure & deterministic.
140
- *
141
- * Budget = `contextWindowTokens * budgetPercent`. First-party skills are
142
- * emitted in full and do NOT consume budget against being dropped. Each
143
- * remaining skill is tried at full description; if it would overflow it is
144
- * degraded to names-only; if even that overflows it is dropped. Skills in
145
- * `ctx.loadedSlugs` and unactivated path-gated skills are suppressed.
146
- */
147
- export function buildSkillListing(
148
- resolver: DefinitionResolver<SkillRecord>,
149
- ctx: ResolveContext,
150
- options: SkillListingOptions = {},
151
- ): SkillListing {
152
- if (!ctx.tenantId) throw new Error("buildSkillListing: tenantId is required");
153
- const opts = listingOptionsSchema.parse(options);
154
-
155
- const loaded = ctx.loadedSlugs ?? new Set<string>();
156
- const visible = resolver
157
- .resolve(ctx)
158
- .filter((s) => !loaded.has(s.slug))
159
- .filter((s) => {
160
- const paths = s.frontmatter.paths;
161
- return paths.length === 0 || pathMatches(paths, opts.touchedPaths);
162
- });
163
-
164
- const budget = Math.max(1, Math.floor(opts.contextWindowTokens * opts.budgetPercent));
165
-
166
- const entries: SkillListingEntry[] = [];
167
- let used = 0;
168
-
169
- for (const s of orderSkills(visible)) {
170
- const fp = isFirstParty(s);
171
- const fm = s.frontmatter;
172
- const fullDesc = fp ? fm.description : truncate(fm.description, opts.maxListingDescChars);
173
-
174
- if (fp) {
175
- const entry: SkillListingEntry = {
176
- name: fm.name,
177
- description: fm.description,
178
- whenToUse: fm.whenToUse,
179
- degraded: false,
180
- firstParty: true,
181
- };
182
- entries.push(entry);
183
- used += estimateListingTokens(renderEntry(entry));
184
- continue;
185
- }
186
-
187
- const full: SkillListingEntry = {
188
- name: fm.name,
189
- description: fullDesc,
190
- whenToUse: fm.whenToUse,
191
- degraded: false,
192
- firstParty: false,
193
- };
194
- const fullCost = estimateListingTokens(renderEntry(full));
195
- if (used + fullCost <= budget) {
196
- entries.push(full);
197
- used += fullCost;
198
- continue;
199
- }
200
-
201
- const nameOnly: SkillListingEntry = {
202
- name: fm.name,
203
- description: "",
204
- whenToUse: undefined,
205
- degraded: true,
206
- firstParty: false,
207
- };
208
- const nameCost = estimateListingTokens(renderEntry(nameOnly));
209
- if (used + nameCost <= budget) {
210
- entries.push(nameOnly);
211
- used += nameCost;
212
- }
213
- // else: drop entirely.
214
- }
215
-
216
- const text = entries.map(renderEntry).join("\n");
217
- return { entries, text };
218
- }
219
-
220
- // ── Phase 2: invocation ──────────────────────────────────────────────────────
221
-
222
- export interface SkillMessage {
223
- readonly role: "system" | "user";
224
- readonly content: string;
225
- }
226
-
227
- export interface ExpandedSkill {
228
- readonly messages: readonly SkillMessage[];
229
- readonly allowedTools: readonly string[];
230
- readonly modelOverride?: string | undefined;
231
- readonly effort?: "low" | "medium" | "high" | undefined;
232
- readonly executionMode: "inline" | "fork";
233
- }
234
-
235
- export interface ExpandContext {
236
- readonly tenantId: string;
237
- readonly args: Record<string, string>;
238
- readonly vars: Record<string, string>;
239
- /** Lazy body fetch — host supplies; called only here, only once. */
240
- readonly bodyLoader: (bodyRef: string) => Promise<string>;
241
- /** Host-injected resource-base indirection (NO host FS access here). */
242
- readonly skillResourceBase: (slug: string) => string;
243
- }
244
-
245
- /**
246
- * Phase 2 — expand a skill into turn messages. Body is loaded lazily via the
247
- * injected `bodyLoader` (never during listing). A `Base directory…` line is
248
- * prepended via the injected `skillResourceBase` indirection. Args + vars are
249
- * substituted with `substituteArguments`. The skill's `allowedTools` are
250
- * returned for the caller to merge into the permission context — this never
251
- * mutates global state and never executes anything from the body.
252
- */
253
- export async function expandSkill(skill: SkillRecord, ctx: ExpandContext): Promise<ExpandedSkill> {
254
- if (!ctx.tenantId) throw new Error("expandSkill: tenantId is required");
255
- if (skill.tenantId !== ctx.tenantId) {
256
- throw new Error("expandSkill: cross-tenant skill access rejected");
257
- }
258
-
259
- const rawBody = await ctx.bodyLoader(skill.bodyRef);
260
- const body = substituteArguments(rawBody, ctx.args, ctx.vars);
261
- const baseLine = `Base directory for this skill: ${ctx.skillResourceBase(skill.slug)}`;
262
-
263
- const messages: readonly SkillMessage[] = [
264
- { role: "system", content: baseLine },
265
- { role: "user", content: body },
266
- ];
267
-
268
- const allowedTools = [...skill.frontmatter.allowedTools];
269
-
270
- return {
271
- messages,
272
- allowedTools,
273
- modelOverride: skill.frontmatter.model,
274
- effort: skill.frontmatter.effort,
275
- executionMode: skill.frontmatter.executionMode,
276
- };
277
- }