@fractaal/pi-agent-core 0.85.4 → 0.86.2

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 (139) hide show
  1. package/README.md +92 -38
  2. package/dist/agent-loop.d.ts +27 -2
  3. package/dist/agent-loop.d.ts.map +1 -1
  4. package/dist/agent-loop.js +183 -63
  5. package/dist/agent-loop.js.map +1 -1
  6. package/dist/agent.d.ts +23 -6
  7. package/dist/agent.d.ts.map +1 -1
  8. package/dist/agent.js +46 -19
  9. package/dist/agent.js.map +1 -1
  10. package/dist/index.d.ts +0 -18
  11. package/dist/index.d.ts.map +1 -1
  12. package/dist/index.js +0 -24
  13. package/dist/index.js.map +1 -1
  14. package/dist/proxy.d.ts +6 -3
  15. package/dist/proxy.d.ts.map +1 -1
  16. package/dist/proxy.js +42 -10
  17. package/dist/proxy.js.map +1 -1
  18. package/dist/stream-fn.d.ts.map +1 -1
  19. package/dist/stream-fn.js.map +1 -1
  20. package/dist/types.d.ts +122 -31
  21. package/dist/types.d.ts.map +1 -1
  22. package/dist/types.js.map +1 -1
  23. package/package.json +6 -17
  24. package/dist/harness/agent-harness.d.ts +0 -94
  25. package/dist/harness/agent-harness.d.ts.map +0 -1
  26. package/dist/harness/agent-harness.js +0 -965
  27. package/dist/harness/agent-harness.js.map +0 -1
  28. package/dist/harness/compaction/branch-summarization.d.ts +0 -55
  29. package/dist/harness/compaction/branch-summarization.d.ts.map +0 -1
  30. package/dist/harness/compaction/branch-summarization.js +0 -173
  31. package/dist/harness/compaction/branch-summarization.js.map +0 -1
  32. package/dist/harness/compaction/compaction.d.ts +0 -107
  33. package/dist/harness/compaction/compaction.d.ts.map +0 -1
  34. package/dist/harness/compaction/compaction.js +0 -583
  35. package/dist/harness/compaction/compaction.js.map +0 -1
  36. package/dist/harness/compaction/utils.d.ts +0 -25
  37. package/dist/harness/compaction/utils.d.ts.map +0 -1
  38. package/dist/harness/compaction/utils.js +0 -120
  39. package/dist/harness/compaction/utils.js.map +0 -1
  40. package/dist/harness/env/nodejs.d.ts +0 -45
  41. package/dist/harness/env/nodejs.d.ts.map +0 -1
  42. package/dist/harness/env/nodejs.js +0 -623
  43. package/dist/harness/env/nodejs.js.map +0 -1
  44. package/dist/harness/messages.d.ts +0 -51
  45. package/dist/harness/messages.d.ts.map +0 -1
  46. package/dist/harness/messages.js +0 -102
  47. package/dist/harness/messages.js.map +0 -1
  48. package/dist/harness/prompt-templates.d.ts +0 -48
  49. package/dist/harness/prompt-templates.d.ts.map +0 -1
  50. package/dist/harness/prompt-templates.js +0 -230
  51. package/dist/harness/prompt-templates.js.map +0 -1
  52. package/dist/harness/session/jsonl-repo.d.ts +0 -26
  53. package/dist/harness/session/jsonl-repo.d.ts.map +0 -1
  54. package/dist/harness/session/jsonl-repo.js +0 -103
  55. package/dist/harness/session/jsonl-repo.js.map +0 -1
  56. package/dist/harness/session/jsonl-storage.d.ts +0 -42
  57. package/dist/harness/session/jsonl-storage.d.ts.map +0 -1
  58. package/dist/harness/session/jsonl-storage.js +0 -293
  59. package/dist/harness/session/jsonl-storage.js.map +0 -1
  60. package/dist/harness/session/memory-repo.d.ts +0 -18
  61. package/dist/harness/session/memory-repo.d.ts.map +0 -1
  62. package/dist/harness/session/memory-repo.js +0 -42
  63. package/dist/harness/session/memory-repo.js.map +0 -1
  64. package/dist/harness/session/memory-storage.d.ts +0 -33
  65. package/dist/harness/session/memory-storage.d.ts.map +0 -1
  66. package/dist/harness/session/memory-storage.js +0 -168
  67. package/dist/harness/session/memory-storage.js.map +0 -1
  68. package/dist/harness/session/repo-utils.d.ts +0 -11
  69. package/dist/harness/session/repo-utils.d.ts.map +0 -1
  70. package/dist/harness/session/repo-utils.js +0 -39
  71. package/dist/harness/session/repo-utils.js.map +0 -1
  72. package/dist/harness/session/session.d.ts +0 -49
  73. package/dist/harness/session/session.d.ts.map +0 -1
  74. package/dist/harness/session/session.js +0 -263
  75. package/dist/harness/session/session.js.map +0 -1
  76. package/dist/harness/skills.d.ts +0 -44
  77. package/dist/harness/skills.d.ts.map +0 -1
  78. package/dist/harness/skills.js +0 -311
  79. package/dist/harness/skills.js.map +0 -1
  80. package/dist/harness/system-prompt.d.ts +0 -3
  81. package/dist/harness/system-prompt.d.ts.map +0 -1
  82. package/dist/harness/system-prompt.js +0 -30
  83. package/dist/harness/system-prompt.js.map +0 -1
  84. package/dist/harness/tools/bash.d.ts +0 -27
  85. package/dist/harness/tools/bash.d.ts.map +0 -1
  86. package/dist/harness/tools/bash.js +0 -132
  87. package/dist/harness/tools/bash.js.map +0 -1
  88. package/dist/harness/tools/edit-diff.d.ts +0 -89
  89. package/dist/harness/tools/edit-diff.d.ts.map +0 -1
  90. package/dist/harness/tools/edit-diff.js +0 -386
  91. package/dist/harness/tools/edit-diff.js.map +0 -1
  92. package/dist/harness/tools/edit.d.ts +0 -19
  93. package/dist/harness/tools/edit.d.ts.map +0 -1
  94. package/dist/harness/tools/edit.js +0 -95
  95. package/dist/harness/tools/edit.js.map +0 -1
  96. package/dist/harness/tools/file-mutation-queue.d.ts +0 -4
  97. package/dist/harness/tools/file-mutation-queue.d.ts.map +0 -1
  98. package/dist/harness/tools/file-mutation-queue.js +0 -46
  99. package/dist/harness/tools/file-mutation-queue.js.map +0 -1
  100. package/dist/harness/tools/image.d.ts +0 -3
  101. package/dist/harness/tools/image.d.ts.map +0 -1
  102. package/dist/harness/tools/image.js +0 -106
  103. package/dist/harness/tools/image.js.map +0 -1
  104. package/dist/harness/tools/index.d.ts +0 -6
  105. package/dist/harness/tools/index.d.ts.map +0 -1
  106. package/dist/harness/tools/index.js +0 -5
  107. package/dist/harness/tools/index.js.map +0 -1
  108. package/dist/harness/tools/path-utils.d.ts +0 -4
  109. package/dist/harness/tools/path-utils.d.ts.map +0 -1
  110. package/dist/harness/tools/path-utils.js +0 -26
  111. package/dist/harness/tools/path-utils.js.map +0 -1
  112. package/dist/harness/tools/read.d.ts +0 -34
  113. package/dist/harness/tools/read.d.ts.map +0 -1
  114. package/dist/harness/tools/read.js +0 -110
  115. package/dist/harness/tools/read.js.map +0 -1
  116. package/dist/harness/tools/tool-context.d.ts +0 -6
  117. package/dist/harness/tools/tool-context.d.ts.map +0 -1
  118. package/dist/harness/tools/tool-context.js +0 -2
  119. package/dist/harness/tools/tool-context.js.map +0 -1
  120. package/dist/harness/tools/write.d.ts +0 -11
  121. package/dist/harness/tools/write.d.ts.map +0 -1
  122. package/dist/harness/tools/write.js +0 -31
  123. package/dist/harness/tools/write.js.map +0 -1
  124. package/dist/harness/types.d.ts +0 -681
  125. package/dist/harness/types.d.ts.map +0 -1
  126. package/dist/harness/types.js +0 -94
  127. package/dist/harness/types.js.map +0 -1
  128. package/dist/harness/utils/shell-output.d.ts +0 -22
  129. package/dist/harness/utils/shell-output.d.ts.map +0 -1
  130. package/dist/harness/utils/shell-output.js +0 -181
  131. package/dist/harness/utils/shell-output.js.map +0 -1
  132. package/dist/harness/utils/truncate.d.ts +0 -70
  133. package/dist/harness/utils/truncate.d.ts.map +0 -1
  134. package/dist/harness/utils/truncate.js +0 -296
  135. package/dist/harness/utils/truncate.js.map +0 -1
  136. package/dist/node.d.ts +0 -3
  137. package/dist/node.d.ts.map +0 -1
  138. package/dist/node.js +0 -3
  139. package/dist/node.js.map +0 -1
@@ -1,263 +0,0 @@
1
- import { createBranchSummaryMessage, createCompactionSummaryMessage, createCustomMessage } from "../messages.js";
2
- import { SessionError } from "../types.js";
3
- function deriveSessionContextState(pathEntries) {
4
- let thinkingLevel = "off";
5
- let model = null;
6
- let activeToolNames = null;
7
- for (const entry of pathEntries) {
8
- if (entry.type === "thinking_level_change") {
9
- thinkingLevel = entry.thinkingLevel;
10
- }
11
- else if (entry.type === "model_change") {
12
- model = { provider: entry.provider, modelId: entry.modelId };
13
- }
14
- else if (entry.type === "message" && entry.message.role === "assistant") {
15
- model = { provider: entry.message.provider, modelId: entry.message.model };
16
- }
17
- else if (entry.type === "active_tools_change") {
18
- activeToolNames = [...entry.activeToolNames];
19
- }
20
- }
21
- return { thinkingLevel, model, activeToolNames };
22
- }
23
- export function defaultContextEntryTransform(pathEntries) {
24
- let compaction = null;
25
- for (const entry of pathEntries) {
26
- if (entry.type === "compaction") {
27
- compaction = entry;
28
- }
29
- }
30
- if (!compaction) {
31
- return [...pathEntries];
32
- }
33
- const entries = [compaction];
34
- const compactionIdx = pathEntries.findIndex((entry) => entry.type === "compaction" && entry.id === compaction.id);
35
- if (compaction.retainedTail) {
36
- for (let i = compactionIdx + 1; i < pathEntries.length; i++) {
37
- entries.push(pathEntries[i]);
38
- }
39
- return entries;
40
- }
41
- if (compaction.firstKeptEntryId) {
42
- let foundFirstKept = false;
43
- for (let i = 0; i < compactionIdx; i++) {
44
- const entry = pathEntries[i];
45
- if (entry.id === compaction.firstKeptEntryId)
46
- foundFirstKept = true;
47
- if (foundFirstKept)
48
- entries.push(entry);
49
- }
50
- }
51
- for (let i = compactionIdx + 1; i < pathEntries.length; i++) {
52
- entries.push(pathEntries[i]);
53
- }
54
- return entries;
55
- }
56
- export function buildContextEntries(pathEntries, options = {}) {
57
- let entries = defaultContextEntryTransform(pathEntries);
58
- for (const transform of options.entryTransforms ?? []) {
59
- entries = [...transform(entries)];
60
- }
61
- return entries;
62
- }
63
- export function sessionEntryToContextMessages(entry, index, entries, options = {}) {
64
- if (entry.type === "message") {
65
- return [entry.message];
66
- }
67
- if (entry.type === "custom_message") {
68
- return [
69
- createCustomMessage(entry.customType, entry.content, entry.display, entry.details, entry.timestamp),
70
- ];
71
- }
72
- if (entry.type === "compaction") {
73
- return [
74
- createCompactionSummaryMessage(entry.summary, entry.tokensBefore, entry.timestamp),
75
- ...(entry.retainedTail ?? []),
76
- ];
77
- }
78
- if (entry.type === "branch_summary" && entry.summary) {
79
- return [createBranchSummaryMessage(entry.summary, entry.fromId, entry.timestamp)];
80
- }
81
- if (entry.type === "custom") {
82
- return [...(options.entryProjectors?.[entry.customType]?.(entry, index, entries) ?? [])];
83
- }
84
- return [];
85
- }
86
- export function buildSessionContext(pathEntries, options = {}) {
87
- const state = deriveSessionContextState(pathEntries);
88
- const contextEntries = buildContextEntries(pathEntries, options);
89
- const messages = contextEntries.flatMap((entry, index) => sessionEntryToContextMessages(entry, index, contextEntries, options));
90
- return { ...state, messages };
91
- }
92
- export class Session {
93
- storage;
94
- contextBuildOptions;
95
- constructor(storage, contextBuildOptions = {}) {
96
- this.storage = storage;
97
- this.contextBuildOptions = contextBuildOptions;
98
- }
99
- getMetadata() {
100
- return this.storage.getMetadata();
101
- }
102
- getStorage() {
103
- return this.storage;
104
- }
105
- getLeafId() {
106
- return this.storage.getLeafId();
107
- }
108
- getEntry(id) {
109
- return this.storage.getEntry(id);
110
- }
111
- getEntries(options) {
112
- return this.storage.getEntries(options);
113
- }
114
- async getBranch(fromId) {
115
- const leafId = fromId ?? (await this.storage.getLeafId());
116
- return this.storage.getPathToRootOrCompaction(leafId);
117
- }
118
- async buildContextEntries(options = {}) {
119
- return buildContextEntries(await this.getBranch(), this.mergeContextBuildOptions(options));
120
- }
121
- async buildContext(options = {}) {
122
- return buildSessionContext(await this.getBranch(), this.mergeContextBuildOptions(options));
123
- }
124
- mergeContextBuildOptions(options) {
125
- return {
126
- entryTransforms: [...(this.contextBuildOptions.entryTransforms ?? []), ...(options.entryTransforms ?? [])],
127
- entryProjectors: {
128
- ...(this.contextBuildOptions.entryProjectors ?? {}),
129
- ...(options.entryProjectors ?? {}),
130
- },
131
- };
132
- }
133
- getLabel(id) {
134
- return this.storage.getLabel(id);
135
- }
136
- getSessionStats() {
137
- return this.storage.getSessionStats();
138
- }
139
- async getSessionName() {
140
- return this.storage.getSessionName();
141
- }
142
- async appendTypedEntry(entry) {
143
- await this.storage.appendEntry(entry);
144
- return entry.id;
145
- }
146
- async appendMessage(message) {
147
- return this.appendTypedEntry({
148
- type: "message",
149
- id: await this.storage.createEntryId(),
150
- parentId: await this.storage.getLeafId(),
151
- timestamp: new Date().toISOString(),
152
- message,
153
- });
154
- }
155
- async appendThinkingLevelChange(thinkingLevel) {
156
- return this.appendTypedEntry({
157
- type: "thinking_level_change",
158
- id: await this.storage.createEntryId(),
159
- parentId: await this.storage.getLeafId(),
160
- timestamp: new Date().toISOString(),
161
- thinkingLevel,
162
- });
163
- }
164
- async appendModelChange(provider, modelId) {
165
- return this.appendTypedEntry({
166
- type: "model_change",
167
- id: await this.storage.createEntryId(),
168
- parentId: await this.storage.getLeafId(),
169
- timestamp: new Date().toISOString(),
170
- provider,
171
- modelId,
172
- });
173
- }
174
- async appendActiveToolsChange(activeToolNames) {
175
- return this.appendTypedEntry({
176
- type: "active_tools_change",
177
- id: await this.storage.createEntryId(),
178
- parentId: await this.storage.getLeafId(),
179
- timestamp: new Date().toISOString(),
180
- activeToolNames: [...activeToolNames],
181
- });
182
- }
183
- async appendCompaction(summary, firstKeptEntryId, tokensBefore, details, fromHook, usage, retainedTail) {
184
- return this.appendTypedEntry({
185
- type: "compaction",
186
- id: await this.storage.createEntryId(),
187
- parentId: await this.storage.getLeafId(),
188
- timestamp: new Date().toISOString(),
189
- summary,
190
- firstKeptEntryId,
191
- tokensBefore,
192
- retainedTail,
193
- details,
194
- usage,
195
- fromHook,
196
- });
197
- }
198
- async appendCustomEntry(customType, data) {
199
- return this.appendTypedEntry({
200
- type: "custom",
201
- id: await this.storage.createEntryId(),
202
- parentId: await this.storage.getLeafId(),
203
- timestamp: new Date().toISOString(),
204
- customType,
205
- data,
206
- });
207
- }
208
- async appendCustomMessageEntry(customType, content, display, details) {
209
- return this.appendTypedEntry({
210
- type: "custom_message",
211
- id: await this.storage.createEntryId(),
212
- parentId: await this.storage.getLeafId(),
213
- timestamp: new Date().toISOString(),
214
- customType,
215
- content,
216
- display,
217
- details,
218
- });
219
- }
220
- async appendLabel(targetId, label) {
221
- if (!(await this.storage.getEntry(targetId))) {
222
- throw new SessionError("not_found", `Entry ${targetId} not found`);
223
- }
224
- return this.appendTypedEntry({
225
- type: "label",
226
- id: await this.storage.createEntryId(),
227
- parentId: await this.storage.getLeafId(),
228
- timestamp: new Date().toISOString(),
229
- targetId,
230
- label,
231
- });
232
- }
233
- async appendSessionName(name) {
234
- const sanitizedName = name.replace(/[\r\n]+/g, " ").trim();
235
- return this.appendTypedEntry({
236
- type: "session_info",
237
- id: await this.storage.createEntryId(),
238
- parentId: await this.storage.getLeafId(),
239
- timestamp: new Date().toISOString(),
240
- name: sanitizedName,
241
- });
242
- }
243
- async moveTo(entryId, summary) {
244
- if (entryId !== null && !(await this.storage.getEntry(entryId))) {
245
- throw new SessionError("not_found", `Entry ${entryId} not found`);
246
- }
247
- await this.storage.setLeafId(entryId);
248
- if (!summary)
249
- return undefined;
250
- return this.appendTypedEntry({
251
- type: "branch_summary",
252
- id: await this.storage.createEntryId(),
253
- parentId: entryId,
254
- timestamp: new Date().toISOString(),
255
- fromId: entryId ?? "root",
256
- summary: summary.summary,
257
- details: summary.details,
258
- usage: summary.usage,
259
- fromHook: summary.fromHook,
260
- });
261
- }
262
- }
263
- //# sourceMappingURL=session.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"session.js","sourceRoot":"","sources":["../../../src/harness/session/session.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,0BAA0B,EAAE,8BAA8B,EAAE,mBAAmB,EAAE,MAAM,gBAAgB,CAAC;AAmBjH,OAAO,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AAiB3C,SAAS,yBAAyB,CAAC,WAAwC,EAAoC;IAC9G,IAAI,aAAa,GAAG,KAAK,CAAC;IAC1B,IAAI,KAAK,GAAiD,IAAI,CAAC;IAC/D,IAAI,eAAe,GAAoB,IAAI,CAAC;IAE5C,KAAK,MAAM,KAAK,IAAI,WAAW,EAAE,CAAC;QACjC,IAAI,KAAK,CAAC,IAAI,KAAK,uBAAuB,EAAE,CAAC;YAC5C,aAAa,GAAG,KAAK,CAAC,aAAa,CAAC;QACrC,CAAC;aAAM,IAAI,KAAK,CAAC,IAAI,KAAK,cAAc,EAAE,CAAC;YAC1C,KAAK,GAAG,EAAE,QA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tC,IAAI,CAAC,OAAO;YAAE,OAAO,SAAS,CAAC;QAC/B,OAAO,IAAI,CAAC,gBAAgB,CAAC;YAC5B,IAAI,EAAE,gBAAgB;YACtB,EAAE,EAAE,MAAM,IAAI,CAAC,OAAO,CAAC,aAAa,EAAE;YACtC,QAAQ,EAAE,OAAO;YACjB,SAAS,EAAE,IAAI,IAAI,EAAE,CAAC,WAAW,EAAE;YACnC,MAAM,EAAE,OAAO,IAAI,MAAM;YACzB,OAAO,EAAE,OAAO,CAAC,OAAO;YACxB,OAAO,EAAE,OAAO,CAAC,OAAO;YACxB,KAAK,EAAE,OAAO,CAAC,KAAK;YACpB,QAAQ,EAAE,OAAO,CAAC,QAAQ;SACG,CAAC,CAAC;IAAA,CAChC;CACD","sourcesContent":["import type { ImageContent, TextContent, Usage } from \"@earendil-works/pi-ai\";\nimport type { AgentMessage } from \"../../types.ts\";\nimport { createBranchSummaryMessage, createCompactionSummaryMessage, createCustomMessage } from \"../messages.ts\";\nimport type {\n\tActiveToolsChangeEntry,\n\tBranchSummaryEntry,\n\tCompactionEntry,\n\tCustomEntry,\n\tCustomMessageEntry,\n\tLabelEntry,\n\tMessageEntry,\n\tModelChangeEntry,\n\tSessionContext,\n\tSessionEntryCursorOptions,\n\tSessionInfoEntry,\n\tSessionMetadata,\n\tSessionStats,\n\tSessionStorage,\n\tSessionTreeEntry,\n\tThinkingLevelChangeEntry,\n} from \"../types.ts\";\nimport { SessionError } from \"../types.ts\";\n\nexport type ContextEntryTransform = (entries: readonly SessionTreeEntry[]) => readonly SessionTreeEntry[];\n\nexport type CustomEntryContextMessageProjector = (\n\tentry: CustomEntry,\n\tindex: number,\n\tentries: readonly SessionTreeEntry[],\n) => readonly AgentMessage[] | undefined;\n\nexport interface SessionContextBuildOptions {\n\t/** Additional entry transforms applied after the default compaction transform. */\n\tentryTransforms?: readonly ContextEntryTransform[];\n\t/** Optional custom-entry projectors. Custom entries are omitted from model context by default. */\n\tentryProjectors?: Readonly<Record<string, CustomEntryContextMessageProjector>>;\n}\n\nfunction deriveSessionContextState(pathEntries: readonly SessionTreeEntry[]): Omit<SessionContext, \"messages\"> {\n\tlet thinkingLevel = \"off\";\n\tlet model: { provider: string; modelId: string } | null = null;\n\tlet activeToolNames: string[] | null = null;\n\n\tfor (const entry of pathEntries) {\n\t\tif (entry.type === \"thinking_level_change\") {\n\t\t\tthinkingLevel = entry.thinkingLevel;\n\t\t} else if (entry.type === \"model_change\") {\n\t\t\tmodel = { provider: entry.provider, modelId: entry.modelId };\n\t\t} else if (entry.type === \"message\" && entry.message.role === \"assistant\") {\n\t\t\tmodel = { provider: entry.message.provider, modelId: entry.message.model };\n\t\t} else if (entry.type === \"active_tools_change\") {\n\t\t\tactiveToolNames = [...entry.activeToolNames];\n\t\t}\n\t}\n\n\treturn { thinkingLevel, model, activeToolNames };\n}\n\nexport function defaultContextEntryTransform(pathEntries: readonly SessionTreeEntry[]): SessionTreeEntry[] {\n\tlet compaction: CompactionEntry | null = null;\n\tfor (const entry of pathEntries) {\n\t\tif (entry.type === \"compaction\") {\n\t\t\tcompaction = entry;\n\t\t}\n\t}\n\tif (!compaction) {\n\t\treturn [...pathEntries];\n\t}\n\n\tconst entries: SessionTreeEntry[] = [compaction];\n\tconst compactionIdx = pathEntries.findIndex((entry) => entry.type === \"compaction\" && entry.id === compaction.id);\n\tif (compaction.retainedTail) {\n\t\tfor (let i = compactionIdx + 1; i < pathEntries.length; i++) {\n\t\t\tentries.push(pathEntries[i]!);\n\t\t}\n\t\treturn entries;\n\t}\n\tif (compaction.firstKeptEntryId) {\n\t\tlet foundFirstKept = false;\n\t\tfor (let i = 0; i < compactionIdx; i++) {\n\t\t\tconst entry = pathEntries[i]!;\n\t\t\tif (entry.id === compaction.firstKeptEntryId) foundFirstKept = true;\n\t\t\tif (foundFirstKept) entries.push(entry);\n\t\t}\n\t}\n\tfor (let i = compactionIdx + 1; i < pathEntries.length; i++) {\n\t\tentries.push(pathEntries[i]!);\n\t}\n\treturn entries;\n}\n\nexport function buildContextEntries(\n\tpathEntries: readonly SessionTreeEntry[],\n\toptions: SessionContextBuildOptions = {},\n): SessionTreeEntry[] {\n\tlet entries = defaultContextEntryTransform(pathEntries);\n\tfor (const transform of options.entryTransforms ?? []) {\n\t\tentries = [...transform(entries)];\n\t}\n\treturn entries;\n}\n\nexport function sessionEntryToContextMessages(\n\tentry: SessionTreeEntry,\n\tindex: number,\n\tentries: readonly SessionTreeEntry[],\n\toptions: SessionContextBuildOptions = {},\n): AgentMessage[] {\n\tif (entry.type === \"message\") {\n\t\treturn [entry.message as AgentMessage];\n\t}\n\tif (entry.type === \"custom_message\") {\n\t\treturn [\n\t\t\tcreateCustomMessage(\n\t\t\t\tentry.customType,\n\t\t\t\tentry.content as string | (TextContent | ImageContent)[],\n\t\t\t\tentry.display,\n\t\t\t\tentry.details,\n\t\t\t\tentry.timestamp,\n\t\t\t),\n\t\t];\n\t}\n\tif (entry.type === \"compaction\") {\n\t\treturn [\n\t\t\tcreateCompactionSummaryMessage(entry.summary, entry.tokensBefore, entry.timestamp),\n\t\t\t...(entry.retainedTail ?? []),\n\t\t];\n\t}\n\tif (entry.type === \"branch_summary\" && entry.summary) {\n\t\treturn [createBranchSummaryMessage(entry.summary, entry.fromId, entry.timestamp)];\n\t}\n\tif (entry.type === \"custom\") {\n\t\treturn [...(options.entryProjectors?.[entry.customType]?.(entry, index, entries) ?? [])];\n\t}\n\treturn [];\n}\n\nexport function buildSessionContext(\n\tpathEntries: readonly SessionTreeEntry[],\n\toptions: SessionContextBuildOptions = {},\n): SessionContext {\n\tconst state = deriveSessionContextState(pathEntries);\n\tconst contextEntries = buildContextEntries(pathEntries, options);\n\tconst messages = contextEntries.flatMap((entry, index) =>\n\t\tsessionEntryToContextMessages(entry, index, contextEntries, options),\n\t);\n\treturn { ...state, messages };\n}\n\nexport class Session<TMetadata extends SessionMetadata = SessionMetadata> {\n\tprivate storage: SessionStorage<TMetadata>;\n\tprivate contextBuildOptions: SessionContextBuildOptions;\n\n\tconstructor(storage: SessionStorage<TMetadata>, contextBuildOptions: SessionContextBuildOptions = {}) {\n\t\tthis.storage = storage;\n\t\tthis.contextBuildOptions = contextBuildOptions;\n\t}\n\n\tgetMetadata(): Promise<TMetadata> {\n\t\treturn this.storage.getMetadata();\n\t}\n\n\tgetStorage(): SessionStorage<TMetadata> {\n\t\treturn this.storage;\n\t}\n\n\tgetLeafId(): Promise<string | null> {\n\t\treturn this.storage.getLeafId();\n\t}\n\n\tgetEntry(id: string): Promise<SessionTreeEntry | undefined> {\n\t\treturn this.storage.getEntry(id);\n\t}\n\n\tgetEntries(options?: SessionEntryCursorOptions): Promise<SessionTreeEntry[]> {\n\t\treturn this.storage.getEntries(options);\n\t}\n\n\tasync getBranch(fromId?: string): Promise<SessionTreeEntry[]> {\n\t\tconst leafId = fromId ?? (await this.storage.getLeafId());\n\t\treturn this.storage.getPathToRootOrCompaction(leafId);\n\t}\n\n\tasync buildContextEntries(options: SessionContextBuildOptions = {}): Promise<SessionTreeEntry[]> {\n\t\treturn buildContextEntries(await this.getBranch(), this.mergeContextBuildOptions(options));\n\t}\n\n\tasync buildContext(options: SessionContextBuildOptions = {}): Promise<SessionContext> {\n\t\treturn buildSessionContext(await this.getBranch(), this.mergeContextBuildOptions(options));\n\t}\n\n\tprivate mergeContextBuildOptions(options: SessionContextBuildOptions): SessionContextBuildOptions {\n\t\treturn {\n\t\t\tentryTransforms: [...(this.contextBuildOptions.entryTransforms ?? []), ...(options.entryTransforms ?? [])],\n\t\t\tentryProjectors: {\n\t\t\t\t...(this.contextBuildOptions.entryProjectors ?? {}),\n\t\t\t\t...(options.entryProjectors ?? {}),\n\t\t\t},\n\t\t};\n\t}\n\n\tgetLabel(id: string): Promise<string | undefined> {\n\t\treturn this.storage.getLabel(id);\n\t}\n\n\tgetSessionStats(): Promise<SessionStats> {\n\t\treturn this.storage.getSessionStats();\n\t}\n\n\tasync getSessionName(): Promise<string | undefined> {\n\t\treturn this.storage.getSessionName();\n\t}\n\n\tprivate async appendTypedEntry<TEntry extends SessionTreeEntry>(entry: TEntry): Promise<string> {\n\t\tawait this.storage.appendEntry(entry);\n\t\treturn entry.id;\n\t}\n\n\tasync appendMessage(message: AgentMessage): Promise<string> {\n\t\treturn this.appendTypedEntry({\n\t\t\ttype: \"message\",\n\t\t\tid: await this.storage.createEntryId(),\n\t\t\tparentId: await this.storage.getLeafId(),\n\t\t\ttimestamp: new Date().toISOString(),\n\t\t\tmessage,\n\t\t} satisfies MessageEntry);\n\t}\n\n\tasync appendThinkingLevelChange(thinkingLevel: string): Promise<string> {\n\t\treturn this.appendTypedEntry({\n\t\t\ttype: \"thinking_level_change\",\n\t\t\tid: await this.storage.createEntryId(),\n\t\t\tparentId: await this.storage.getLeafId(),\n\t\t\ttimestamp: new Date().toISOString(),\n\t\t\tthinkingLevel,\n\t\t} satisfies ThinkingLevelChangeEntry);\n\t}\n\n\tasync appendModelChange(provider: string, modelId: string): Promise<string> {\n\t\treturn this.appendTypedEntry({\n\t\t\ttype: \"model_change\",\n\t\t\tid: await this.storage.createEntryId(),\n\t\t\tparentId: await this.storage.getLeafId(),\n\t\t\ttimestamp: new Date().toISOString(),\n\t\t\tprovider,\n\t\t\tmodelId,\n\t\t} satisfies ModelChangeEntry);\n\t}\n\n\tasync appendActiveToolsChange(activeToolNames: string[]): Promise<string> {\n\t\treturn this.appendTypedEntry({\n\t\t\ttype: \"active_tools_change\",\n\t\t\tid: await this.storage.createEntryId(),\n\t\t\tparentId: await this.storage.getLeafId(),\n\t\t\ttimestamp: new Date().toISOString(),\n\t\t\tactiveToolNames: [...activeToolNames],\n\t\t} satisfies ActiveToolsChangeEntry);\n\t}\n\n\tasync appendCompaction<T = unknown>(\n\t\tsummary: string,\n\t\tfirstKeptEntryId: string | undefined,\n\t\ttokensBefore: number,\n\t\tdetails?: T,\n\t\tfromHook?: boolean,\n\t\tusage?: Usage,\n\t\tretainedTail?: AgentMessage[],\n\t): Promise<string> {\n\t\treturn this.appendTypedEntry({\n\t\t\ttype: \"compaction\",\n\t\t\tid: await this.storage.createEntryId(),\n\t\t\tparentId: await this.storage.getLeafId(),\n\t\t\ttimestamp: new Date().toISOString(),\n\t\t\tsummary,\n\t\t\tfirstKeptEntryId,\n\t\t\ttokensBefore,\n\t\t\tretainedTail,\n\t\t\tdetails,\n\t\t\tusage,\n\t\t\tfromHook,\n\t\t} satisfies CompactionEntry<T>);\n\t}\n\n\tasync appendCustomEntry(customType: string, data?: unknown): Promise<string> {\n\t\treturn this.appendTypedEntry({\n\t\t\ttype: \"custom\",\n\t\t\tid: await this.storage.createEntryId(),\n\t\t\tparentId: await this.storage.getLeafId(),\n\t\t\ttimestamp: new Date().toISOString(),\n\t\t\tcustomType,\n\t\t\tdata,\n\t\t} satisfies CustomEntry);\n\t}\n\n\tasync appendCustomMessageEntry<T = unknown>(\n\t\tcustomType: string,\n\t\tcontent: string | (TextContent | ImageContent)[],\n\t\tdisplay: boolean,\n\t\tdetails?: T,\n\t): Promise<string> {\n\t\treturn this.appendTypedEntry({\n\t\t\ttype: \"custom_message\",\n\t\t\tid: await this.storage.createEntryId(),\n\t\t\tparentId: await this.storage.getLeafId(),\n\t\t\ttimestamp: new Date().toISOString(),\n\t\t\tcustomType,\n\t\t\tcontent,\n\t\t\tdisplay,\n\t\t\tdetails,\n\t\t} satisfies CustomMessageEntry<T>);\n\t}\n\n\tasync appendLabel(targetId: string, label: string | undefined): Promise<string> {\n\t\tif (!(await this.storage.getEntry(targetId))) {\n\t\t\tthrow new SessionError(\"not_found\", `Entry ${targetId} not found`);\n\t\t}\n\t\treturn this.appendTypedEntry({\n\t\t\ttype: \"label\",\n\t\t\tid: await this.storage.createEntryId(),\n\t\t\tparentId: await this.storage.getLeafId(),\n\t\t\ttimestamp: new Date().toISOString(),\n\t\t\ttargetId,\n\t\t\tlabel,\n\t\t} satisfies LabelEntry);\n\t}\n\n\tasync appendSessionName(name: string): Promise<string> {\n\t\tconst sanitizedName = name.replace(/[\\r\\n]+/g, \" \").trim();\n\t\treturn this.appendTypedEntry({\n\t\t\ttype: \"session_info\",\n\t\t\tid: await this.storage.createEntryId(),\n\t\t\tparentId: await this.storage.getLeafId(),\n\t\t\ttimestamp: new Date().toISOString(),\n\t\t\tname: sanitizedName,\n\t\t} satisfies SessionInfoEntry);\n\t}\n\n\tasync moveTo(\n\t\tentryId: string | null,\n\t\tsummary?: { summary: string; details?: unknown; usage?: Usage; fromHook?: boolean },\n\t): Promise<string | undefined> {\n\t\tif (entryId !== null && !(await this.storage.getEntry(entryId))) {\n\t\t\tthrow new SessionError(\"not_found\", `Entry ${entryId} not found`);\n\t\t}\n\t\tawait this.storage.setLeafId(entryId);\n\t\tif (!summary) return undefined;\n\t\treturn this.appendTypedEntry({\n\t\t\ttype: \"branch_summary\",\n\t\t\tid: await this.storage.createEntryId(),\n\t\t\tparentId: entryId,\n\t\t\ttimestamp: new Date().toISOString(),\n\t\t\tfromId: entryId ?? \"root\",\n\t\t\tsummary: summary.summary,\n\t\t\tdetails: summary.details,\n\t\t\tusage: summary.usage,\n\t\t\tfromHook: summary.fromHook,\n\t\t} satisfies BranchSummaryEntry);\n\t}\n}\n"]}
@@ -1,44 +0,0 @@
1
- import { type ExecutionEnv, type Skill } from "./types.ts";
2
- export type SkillDiagnosticCode = "file_info_failed" | "list_failed" | "read_failed" | "parse_failed" | "invalid_metadata";
3
- /** Warning produced while loading skills. */
4
- export interface SkillDiagnostic {
5
- /** Diagnostic severity. Currently only warnings are emitted. */
6
- type: "warning";
7
- /** Stable diagnostic code. */
8
- code: SkillDiagnosticCode;
9
- /** Human-readable diagnostic message. */
10
- message: string;
11
- /** Path associated with the diagnostic. */
12
- path: string;
13
- }
14
- /** Format a skill invocation prompt, optionally appending additional user instructions. */
15
- export declare function formatSkillInvocation(skill: Skill, additionalInstructions?: string): string;
16
- /**
17
- * Load skills from one or more directories.
18
- *
19
- * Traverses directories recursively, loads `SKILL.md` files, loads direct root `.md` files as skills, honors ignore files,
20
- * and returns diagnostics for invalid skill files. Missing input directories are skipped.
21
- */
22
- export declare function loadSkills(env: ExecutionEnv, dirs: string | string[]): Promise<{
23
- skills: Skill[];
24
- diagnostics: SkillDiagnostic[];
25
- }>;
26
- /**
27
- * Load skills from source-tagged directories.
28
- *
29
- * Source values are preserved exactly and attached to every loaded skill and diagnostic. The agent package does not
30
- * interpret source values; applications define their own provenance shape.
31
- */
32
- export declare function loadSourcedSkills<TSource, TSkill extends Skill = Skill>(env: ExecutionEnv, inputs: Array<{
33
- path: string;
34
- source: TSource;
35
- }>, mapSkill?: (skill: Skill, source: TSource) => TSkill): Promise<{
36
- skills: Array<{
37
- skill: TSkill;
38
- source: TSource;
39
- }>;
40
- diagnostics: Array<SkillDiagnostic & {
41
- source: TSource;
42
- }>;
43
- }>;
44
- //# sourceMappingURL=skills.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"skills.d.ts","sourceRoot":"","sources":["../../src/harness/skills.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,KAAK,YAAY,EAA8B,KAAK,KAAK,EAAW,MAAM,YAAY,CAAC;AAQhG,MAAM,MAAM,mBAAmB,GAC5B,kBAAkB,GAClB,aAAa,GACb,aAAa,GACb,cAAc,GACd,kBAAkB,CAAC;AAEtB,6CAA6C;AAC7C,MAAM,WAAW,eAAe;IAC/B,gEAAgE;IAChE,IAAI,EAAE,SAAS,CAAC;IAChB,8BAA8B;IAC9B,IAAI,EAAE,mBAAmB,CAAC;IAC1B,yCAAyC;IACzC,OAAO,EAAE,MAAM,CAAC;IAChB,2CAA2C;IAC3C,IAAI,EAAE,MAAM,CAAC;CACb;AASD,2FAA2F;AAC3F,wBAAgB,qBAAqB,CAAC,KAAK,EAAE,KAAK,EAAE,sBAAsB,CAAC,EAAE,MAAM,GAAG,MAAM,CAG3F;AAED;;;;;GAKG;AACH,wBAAsB,UAAU,CAC/B,GAAG,EAAE,YAAY,EACjB,IAAI,EAAE,MAAM,GAAG,MAAM,EAAE,GACrB,OAAO,CAAC;IAAE,MAAM,EAAE,KAAK,EAAE,CAAC;IAAC,WAAW,EAAE,eAAe,EAAE,CAAA;CAAE,CAAC,CAuB9D;AAED;;;;;GAKG;AACH,wBAAsB,iBAAiB,CAAC,OAAO,EAAE,MAAM,SAAS,KAAK,GAAG,KAAK,EAC5E,GAAG,EAAE,YAAY,EACjB,MAAM,EAAE,KAAK,CAAC;IAAE,IAAI,EAAE,MAAM,CAAC;IAAC,MAAM,EAAE,OAAO,CAAA;CAAE,CAAC,EAChD,QAAQ,CAAC,EAAE,CAAC,KAAK,EAAE,KAAK,EAAE,MAAM,EAAE,OAAO,KAAK,MAAM,GAClD,OAAO,CAAC;IACV,MAAM,EAAE,KAAK,CAAC;QAAE,KAAK,EAAE,MAAM,CAAC;QAAC,MAAM,EAAE,OAAO,CAAA;KAAE,CAAC,CAAC;IAClD,WAAW,EAAE,KAAK,CAAC,eAAe,GAAG;QAAE,MAAM,EAAE,OAAO,CAAA;KAAE,CAAC,CAAC;CAC1D,CAAC,CAWD","sourcesContent":["import ignore from \"ignore\";\nimport { parse } from \"yaml\";\nimport { type ExecutionEnv, type FileInfo, type Result, type Skill, toError } from \"./types.ts\";\n\nconst MAX_NAME_LENGTH = 64;\nconst MAX_DESCRIPTION_LENGTH = 1024;\nconst IGNORE_FILE_NAMES = [\".gitignore\", \".ignore\", \".fdignore\"];\n\ntype IgnoreMatcher = ReturnType<typeof ignore>;\n\nexport type SkillDiagnosticCode =\n\t| \"file_info_failed\"\n\t| \"list_failed\"\n\t| \"read_failed\"\n\t| \"parse_failed\"\n\t| \"invalid_metadata\";\n\n/** Warning produced while loading skills. */\nexport interface SkillDiagnostic {\n\t/** Diagnostic severity. Currently only warnings are emitted. */\n\ttype: \"warning\";\n\t/** Stable diagnostic code. */\n\tcode: SkillDiagnosticCode;\n\t/** Human-readable diagnostic message. */\n\tmessage: string;\n\t/** Path associated with the diagnostic. */\n\tpath: string;\n}\n\ninterface SkillFrontmatter {\n\tname?: string;\n\tdescription?: string;\n\t\"disable-model-invocation\"?: boolean;\n\t[key: string]: unknown;\n}\n\n/** Format a skill invocation prompt, optionally appending additional user instructions. */\nexport function formatSkillInvocation(skill: Skill, additionalInstructions?: string): string {\n\tconst skillBlock = `<skill name=\"${skill.name}\" location=\"${skill.filePath}\">\\nReferences are relative to ${dirnameEnvPath(skill.filePath)}.\\n\\n${skill.content}\\n</skill>`;\n\treturn additionalInstructions ? `${skillBlock}\\n\\n${additionalInstructions}` : skillBlock;\n}\n\n/**\n * Load skills from one or more directories.\n *\n * Traverses directories recursively, loads `SKILL.md` files, loads direct root `.md` files as skills, honors ignore files,\n * and returns diagnostics for invalid skill files. Missing input directories are skipped.\n */\nexport async function loadSkills(\n\tenv: ExecutionEnv,\n\tdirs: string | string[],\n): Promise<{ skills: Skill[]; diagnostics: SkillDiagnostic[] }> {\n\tconst skills: Skill[] = [];\n\tconst diagnostics: SkillDiagnostic[] = [];\n\tfor (const dir of Array.isArray(dirs) ? dirs : [dirs]) {\n\t\tconst rootInfoResult = await env.fileInfo(dir);\n\t\tif (!rootInfoResult.ok) {\n\t\t\tif (rootInfoResult.error.code !== \"not_found\") {\n\t\t\t\tdiagnostics.push({\n\t\t\t\t\ttype: \"warning\",\n\t\t\t\t\tcode: \"file_info_failed\",\n\t\t\t\t\tmessage: rootInfoResult.error.message,\n\t\t\t\t\tpath: dir,\n\t\t\t\t});\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\t\tconst rootInfo = rootInfoResult.value;\n\t\tif ((await resolveKind(env, rootInfo, diagnostics)) !== \"directory\") continue;\n\t\tconst result = await loadSkillsFromDirInternal(env, rootInfo.path, true, ignore(), rootInfo.path);\n\t\tskills.push(...result.skills);\n\t\tdiagnostics.push(...result.diagnostics);\n\t}\n\treturn { skills, diagnostics };\n}\n\n/**\n * Load skills from source-tagged directories.\n *\n * Source values are preserved exactly and attached to every loaded skill and diagnostic. The agent package does not\n * interpret source values; applications define their own provenance shape.\n */\nexport async function loadSourcedSkills<TSource, TSkill extends Skill = Skill>(\n\tenv: ExecutionEnv,\n\tinputs: Array<{ path: string; source: TSource }>,\n\tmapSkill?: (skill: Skill, source: TSource) => TSkill,\n): Promise<{\n\tskills: Array<{ skill: TSkill; source: TSource }>;\n\tdiagnostics: Array<SkillDiagnostic & { source: TSource }>;\n}> {\n\tconst skills: Array<{ skill: TSkill; source: TSource }> = [];\n\tconst diagnostics: Array<SkillDiagnostic & { source: TSource }> = [];\n\tfor (const input of inputs) {\n\t\tconst result = await loadSkills(env, input.path);\n\t\tfor (const skill of result.skills) {\n\t\t\tskills.push({ skill: mapSkill ? mapSkill(skill, input.source) : (skill as TSkill), source: input.source });\n\t\t}\n\t\tfor (const diagnostic of result.diagnostics) diagnostics.push({ ...diagnostic, source: input.source });\n\t}\n\treturn { skills, diagnostics };\n}\n\nasync function loadSkillsFromDirInternal(\n\tenv: ExecutionEnv,\n\tdir: string,\n\tincludeRootFiles: boolean,\n\tignoreMatcher: IgnoreMatcher,\n\trootDir: string,\n): Promise<{ skills: Skill[]; diagnostics: SkillDiagnostic[] }> {\n\tconst skills: Skill[] = [];\n\tconst diagnostics: SkillDiagnostic[] = [];\n\n\tconst dirInfoResult = await env.fileInfo(dir);\n\tif (!dirInfoResult.ok) {\n\t\tif (dirInfoResult.error.code !== \"not_found\") {\n\t\t\tdiagnostics.push({\n\t\t\t\ttype: \"warning\",\n\t\t\t\tcode: \"file_info_failed\",\n\t\t\t\tmessage: dirInfoResult.error.message,\n\t\t\t\tpath: dir,\n\t\t\t});\n\t\t}\n\t\treturn { skills, diagnostics };\n\t}\n\tconst dirInfo = dirInfoResult.value;\n\tif ((await resolveKind(env, dirInfo, diagnostics)) !== \"directory\") return { skills, diagnostics };\n\n\tawait addIgnoreRules(env, ignoreMatcher, dir, rootDir, diagnostics);\n\n\tconst entriesResult = await env.listDir(dir);\n\tif (!entriesResult.ok) {\n\t\tdiagnostics.push({ type: \"warning\", code: \"list_failed\", message: entriesResult.error.message, path: dir });\n\t\treturn { skills, diagnostics };\n\t}\n\tconst entries = entriesResult.value;\n\n\tfor (const entry of entries) {\n\t\tif (entry.name !== \"SKILL.md\") continue;\n\t\tconst fullPath = entry.path;\n\t\tconst kind = await resolveKind(env, entry, diagnostics);\n\t\tif (kind !== \"file\") continue;\n\t\tconst relPath = relativeEnvPath(rootDir, fullPath);\n\t\tif (ignoreMatcher.ignores(relPath)) continue;\n\n\t\tconst result = await loadSkillFromFile(env, fullPath);\n\t\tif (result.skill) skills.push(result.skill);\n\t\tdiagnostics.push(...result.diagnostics);\n\t\treturn { skills, diagnostics };\n\t}\n\n\tfor (const entry of entries.sort((a, b) => a.name.localeCompare(b.name))) {\n\t\tif (entry.name.startsWith(\".\") || entry.name === \"node_modules\") continue;\n\t\tconst fullPath = entry.path;\n\t\tconst kind = await resolveKind(env, entry, diagnostics);\n\t\tif (!kind) continue;\n\n\t\tconst relPath = relativeEnvPath(rootDir, fullPath);\n\t\tconst ignorePath = kind === \"directory\" ? `${relPath}/` : relPath;\n\t\tif (ignoreMatcher.ignores(ignorePath)) continue;\n\n\t\tif (kind === \"directory\") {\n\t\t\tconst result = await loadSkillsFromDirInternal(env, fullPath, false, ignoreMatcher, rootDir);\n\t\t\tskills.push(...result.skills);\n\t\t\tdiagnostics.push(...result.diagnostics);\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (kind !== \"file\" || !includeRootFiles || !entry.name.endsWith(\".md\")) continue;\n\t\tconst result = await loadSkillFromFile(env, fullPath);\n\t\tif (result.skill) skills.push(result.skill);\n\t\tdiagnostics.push(...result.diagnostics);\n\t}\n\n\treturn { skills, diagnostics };\n}\n\nasync function addIgnoreRules(\n\tenv: ExecutionEnv,\n\tig: IgnoreMatcher,\n\tdir: string,\n\trootDir: string,\n\tdiagnostics: SkillDiagnostic[],\n): Promise<void> {\n\tconst relativeDir = relativeEnvPath(rootDir, dir);\n\tconst prefix = relativeDir ? `${relativeDir}/` : \"\";\n\n\tfor (const filename of IGNORE_FILE_NAMES) {\n\t\tconst ignorePath = joinEnvPath(dir, filename);\n\t\tconst info = await env.fileInfo(ignorePath);\n\t\tif (!info.ok) {\n\t\t\tif (info.error.code !== \"not_found\") {\n\t\t\t\tdiagnostics.push({\n\t\t\t\t\ttype: \"warning\",\n\t\t\t\t\tcode: \"file_info_failed\",\n\t\t\t\t\tmessage: info.error.message,\n\t\t\t\t\tpath: ignorePath,\n\t\t\t\t});\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\t\tif (info.value.kind !== \"file\") continue;\n\t\tconst content = await env.readTextFile(ignorePath);\n\t\tif (!content.ok) {\n\t\t\tdiagnostics.push({ type: \"warning\", code: \"read_failed\", message: content.error.message, path: ignorePath });\n\t\t\tcontinue;\n\t\t}\n\t\tconst patterns = content.value\n\t\t\t.split(/\\r?\\n/)\n\t\t\t.map((line) => prefixIgnorePattern(line, prefix))\n\t\t\t.filter((line): line is string => Boolean(line));\n\t\tif (patterns.length > 0) ig.add(patterns);\n\t}\n}\n\nfunction prefixIgnorePattern(line: string, prefix: string): string | null {\n\tconst trimmed = line.trim();\n\tif (!trimmed) return null;\n\tif (trimmed.startsWith(\"#\") && !trimmed.startsWith(\"\\\\#\")) return null;\n\n\tlet pattern = line;\n\tlet negated = false;\n\tif (pattern.startsWith(\"!\")) {\n\t\tnegated = true;\n\t\tpattern = pattern.slice(1);\n\t} else if (pattern.startsWith(\"\\\\!\")) {\n\t\tpattern = pattern.slice(1);\n\t}\n\tif (pattern.startsWith(\"/\")) pattern = pattern.slice(1);\n\tconst prefixed = prefix ? `${prefix}${pattern}` : pattern;\n\treturn negated ? `!${prefixed}` : prefixed;\n}\n\nasync function loadSkillFromFile(\n\tenv: ExecutionEnv,\n\tfilePath: string,\n): Promise<{ skill: Skill | null; diagnostics: SkillDiagnostic[] }> {\n\tconst diagnostics: SkillDiagnostic[] = [];\n\tconst rawContent = await env.readTextFile(filePath);\n\tif (!rawContent.ok) {\n\t\tdiagnostics.push({ type: \"warning\", code: \"read_failed\", message: rawContent.error.message, path: filePath });\n\t\treturn { skill: null, diagnostics };\n\t}\n\n\tconst parsed = parseFrontmatter<SkillFrontmatter>(rawContent.value);\n\tif (!parsed.ok) {\n\t\tdiagnostics.push({ type: \"warning\", code: \"parse_failed\", message: parsed.error.message, path: filePath });\n\t\treturn { skill: null, diagnostics };\n\t}\n\n\tconst { frontmatter, body } = parsed.value;\n\tconst skillDir = dirnameEnvPath(filePath);\n\tconst parentDirName = basenameEnvPath(skillDir);\n\tconst description = typeof frontmatter.description === \"string\" ? frontmatter.description : undefined;\n\n\tfor (const error of validateDescription(description)) {\n\t\tdiagnostics.push({ type: \"warning\", code: \"invalid_metadata\", message: error, path: filePath });\n\t}\n\n\tconst frontmatterName = typeof frontmatter.name === \"string\" ? frontmatter.name : undefined;\n\tconst name = frontmatterName || parentDirName;\n\tfor (const error of validateName(name, parentDirName)) {\n\t\tdiagnostics.push({ type: \"warning\", code: \"invalid_metadata\", message: error, path: filePath });\n\t}\n\n\tif (!description || description.trim() === \"\") {\n\t\treturn { skill: null, diagnostics };\n\t}\n\n\treturn {\n\t\tskill: {\n\t\t\tname,\n\t\t\tdescription,\n\t\t\tcontent: body,\n\t\t\tfilePath,\n\t\t\tdisableModelInvocation: frontmatter[\"disable-model-invocation\"] === true,\n\t\t},\n\t\tdiagnostics,\n\t};\n}\n\nfunction validateName(name: string, parentDirName: string): string[] {\n\tconst errors: string[] = [];\n\tif (name !== parentDirName) errors.push(`name \"${name}\" does not match parent directory \"${parentDirName}\"`);\n\tif (name.length > MAX_NAME_LENGTH) errors.push(`name exceeds ${MAX_NAME_LENGTH} characters (${name.length})`);\n\tif (!/^[a-z0-9-]+$/.test(name)) {\n\t\terrors.push(\"name contains invalid characters (must be lowercase a-z, 0-9, hyphens only)\");\n\t}\n\tif (name.startsWith(\"-\") || name.endsWith(\"-\")) errors.push(\"name must not start or end with a hyphen\");\n\tif (name.includes(\"--\")) errors.push(\"name must not contain consecutive hyphens\");\n\treturn errors;\n}\n\nfunction validateDescription(description: string | undefined): string[] {\n\tconst errors: string[] = [];\n\tif (!description || description.trim() === \"\") {\n\t\terrors.push(\"description is required\");\n\t} else if (description.length > MAX_DESCRIPTION_LENGTH) {\n\t\terrors.push(`description exceeds ${MAX_DESCRIPTION_LENGTH} characters (${description.length})`);\n\t}\n\treturn errors;\n}\n\nfunction parseFrontmatter<T extends Record<string, unknown>>(\n\tcontent: string,\n): Result<{ frontmatter: T; body: string }, Error> {\n\ttry {\n\t\tconst normalized = content.replace(/\\r\\n/g, \"\\n\").replace(/\\r/g, \"\\n\");\n\t\tif (!normalized.startsWith(\"---\")) return { ok: true, value: { frontmatter: {} as T, body: normalized } };\n\t\tconst endIndex = normalized.indexOf(\"\\n---\", 3);\n\t\tif (endIndex === -1) return { ok: true, value: { frontmatter: {} as T, body: normalized } };\n\t\tconst yamlString = normalized.slice(4, endIndex);\n\t\tconst body = normalized.slice(endIndex + 4).trim();\n\t\treturn { ok: true, value: { frontmatter: (parse(yamlString) ?? {}) as T, body } };\n\t} catch (error) {\n\t\treturn { ok: false, error: toError(error) };\n\t}\n}\n\nasync function resolveKind(\n\tenv: ExecutionEnv,\n\tinfo: FileInfo,\n\tdiagnostics: SkillDiagnostic[],\n): Promise<\"file\" | \"directory\" | undefined> {\n\tif (info.kind === \"file\" || info.kind === \"directory\") return info.kind;\n\tconst canonicalPath = await env.canonicalPath(info.path);\n\tif (!canonicalPath.ok) {\n\t\tif (canonicalPath.error.code !== \"not_found\") {\n\t\t\tdiagnostics.push({\n\t\t\t\ttype: \"warning\",\n\t\t\t\tcode: \"file_info_failed\",\n\t\t\t\tmessage: canonicalPath.error.message,\n\t\t\t\tpath: info.path,\n\t\t\t});\n\t\t}\n\t\treturn undefined;\n\t}\n\tconst target = await env.fileInfo(canonicalPath.value);\n\tif (!target.ok) {\n\t\tif (target.error.code !== \"not_found\") {\n\t\t\tdiagnostics.push({\n\t\t\t\ttype: \"warning\",\n\t\t\t\tcode: \"file_info_failed\",\n\t\t\t\tmessage: target.error.message,\n\t\t\t\tpath: info.path,\n\t\t\t});\n\t\t}\n\t\treturn undefined;\n\t}\n\treturn target.value.kind === \"file\" || target.value.kind === \"directory\" ? target.value.kind : undefined;\n}\n\nfunction joinEnvPath(base: string, child: string): string {\n\treturn `${base.replace(/\\/+$/, \"\")}/${child.replace(/^\\/+/, \"\")}`;\n}\n\nfunction dirnameEnvPath(path: string): string {\n\tconst normalized = path.replace(/\\/+$/, \"\");\n\tconst slashIndex = normalized.lastIndexOf(\"/\");\n\treturn slashIndex <= 0 ? \"/\" : normalized.slice(0, slashIndex);\n}\n\nfunction basenameEnvPath(path: string): string {\n\tconst normalized = path.replace(/\\/+$/, \"\");\n\tconst slashIndex = normalized.lastIndexOf(\"/\");\n\treturn slashIndex === -1 ? normalized : normalized.slice(slashIndex + 1);\n}\n\nfunction relativeEnvPath(root: string, path: string): string {\n\tconst normalizedRoot = root.replace(/\\/+$/, \"\");\n\tconst normalizedPath = path.replace(/\\/+$/, \"\");\n\tif (normalizedPath === normalizedRoot) return \"\";\n\treturn normalizedPath.startsWith(`${normalizedRoot}/`)\n\t\t? normalizedPath.slice(normalizedRoot.length + 1)\n\t\t: normalizedPath.replace(/^\\/+/, \"\");\n}\n"]}