@qilin-agent/tool-skill 0.0.0-stage → 3.1.3

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.
package/lib/index.js ADDED
@@ -0,0 +1,1032 @@
1
+ import { createHash } from "node:crypto";
2
+ import z from "@qilin-agent/schemastery";
3
+ import { defineTool } from "@qilin-agent/tools";
4
+ import { createUserMessage } from "@qilin-agent/llm";
5
+ import "@qilin-agent/kylin";
6
+ import { escapeText, isModelInvocable, isSkillName, isUserInvocable, renderSkillContent } from "@qilin-agent/skill";
7
+ //#region ../../util/brand/src/index.ts
8
+ /**
9
+ * Apply a compile-time number brand without changing the value.
10
+ * @param value - number admitted by the domain that owns the target brand.
11
+ * @returns the same number with the requested compile-time brand.
12
+ */
13
+ function brandNumber(value) {
14
+ return value;
15
+ }
16
+ //#endregion
17
+ //#region ../../util/values/src/partial-json.ts
18
+ /**
19
+ * Lazily scanned view of one JSON object's top-level fields, built from text
20
+ * that may still be streaming or from an already parsed object. Nothing is
21
+ * scanned until a reader asks; the view remembers every question it answered
22
+ * and reports changed answers when the owner refreshes for publication.
23
+ * Used for model tool-call arguments: a row reads the fields it
24
+ * cares about at whatever granularity it displays, at every stage of the call.
25
+ * @module @qilin-agent/util-values/src/partial-json
26
+ */
27
+ const SIMPLE_ESCAPES = {
28
+ "\"": "\"",
29
+ "\\": "\\",
30
+ "/": "/",
31
+ b: "\b",
32
+ f: "\f",
33
+ n: "\n",
34
+ r: "\r",
35
+ t: " "
36
+ };
37
+ const CONTENT_ESCAPE = /[\\\u0000-\u001f]/u;
38
+ function isWhitespace(c) {
39
+ return c === " " || c === "\n" || c === "\r" || c === " ";
40
+ }
41
+ function isHex(c) {
42
+ return c >= "0" && c <= "9" || c >= "a" && c <= "f" || c >= "A" && c <= "F";
43
+ }
44
+ (class PartialArguments {
45
+ /** The view of a call with no arguments available. */
46
+ static EMPTY = PartialArguments.fromObject({});
47
+ /**
48
+ * View finished argument text without scanning it until a reader asks.
49
+ * @param text - the complete argument JSON text.
50
+ * @returns a sealed view.
51
+ */
52
+ static fromText(text) {
53
+ const view = new PartialArguments();
54
+ view.append(text);
55
+ view.sealed = true;
56
+ return view;
57
+ }
58
+ /**
59
+ * View an already parsed argument payload, such as a PTC dispatch object.
60
+ * @param value - the parsed argument value.
61
+ * @returns a sealed view; a non-object payload has no fields.
62
+ */
63
+ static fromObject(value) {
64
+ const view = new PartialArguments();
65
+ view.object = typeof value === "object" && value !== null && !Array.isArray(value) ? value : {};
66
+ view.sealed = true;
67
+ return view;
68
+ }
69
+ /**
70
+ * The source: text so far or a parsed object, plus whether it can still grow.
71
+ * These are the only enumerable fields, so two views over the same source
72
+ * compare equal structurally however far each has been read.
73
+ */
74
+ chunks = [];
75
+ object;
76
+ sealed = false;
77
+ #ends = [];
78
+ #size = 0;
79
+ #consumed = 0;
80
+ #mode = "root";
81
+ #escape = false;
82
+ #keyStart = 0;
83
+ #keyEscaped = false;
84
+ #key = "";
85
+ #current = null;
86
+ #nestedEnds = [];
87
+ #nestedInString = false;
88
+ #invalidAt;
89
+ #invalidValue = false;
90
+ #entries = /* @__PURE__ */ new Map();
91
+ #order = [];
92
+ #reads = /* @__PURE__ */ new Map();
93
+ /** Whether this view rejects further appends; does not scan text or register reads. */
94
+ get isSealed() {
95
+ return this.sealed;
96
+ }
97
+ /** Whether indexing or a content read found invalid JSON; unread value contents are not validated. */
98
+ get invalid() {
99
+ this.scan();
100
+ return this.#mode === "invalid" || this.#invalidValue;
101
+ }
102
+ /**
103
+ * Retain streamed argument text without scanning or comparing observed answers.
104
+ * @param fragment - the text following every fragment appended before.
105
+ */
106
+ append(fragment) {
107
+ if (this.sealed) throw new Error("PartialArguments: cannot append to a sealed view");
108
+ if (fragment.length === 0) return;
109
+ this.chunks.push(fragment);
110
+ this.#size += fragment.length;
111
+ this.#ends.push(this.#size);
112
+ }
113
+ /**
114
+ * Reconcile a streamed prefix with authoritative complete text without joining the fragments.
115
+ * @param text - the final argument text, which replaces missing or conflicting deltas.
116
+ * @returns this view sealed with its caches retained when every character matches; otherwise a new sealed view.
117
+ */
118
+ settle(text) {
119
+ if (this.object !== void 0 || text.length !== this.#size) return PartialArguments.fromText(text);
120
+ let offset = 0;
121
+ for (const chunk of this.chunks) {
122
+ if (!text.startsWith(chunk, offset)) return PartialArguments.fromText(text);
123
+ offset += chunk.length;
124
+ }
125
+ this.chunks = text.length === 0 ? [] : [text];
126
+ this.#ends = text.length === 0 ? [] : [text.length];
127
+ this.sealed = true;
128
+ return this;
129
+ }
130
+ /**
131
+ * Compare observed answers and advance their publication baseline. Unread views remain unscanned.
132
+ * @returns whether any observed answer changed since its first read or the preceding refresh.
133
+ */
134
+ refresh() {
135
+ if (this.#reads.size === 0) return false;
136
+ this.scan();
137
+ let changed = false;
138
+ let completions = false;
139
+ for (const read of this.#reads.values()) {
140
+ if (read.completion) {
141
+ completions = true;
142
+ continue;
143
+ }
144
+ changed = this.refreshRead(read) || changed;
145
+ }
146
+ if (completions) {
147
+ for (const read of this.#reads.values()) if (read.completion) changed = this.refreshRead(read) || changed;
148
+ }
149
+ if (this.sealed) this.#reads.clear();
150
+ return changed;
151
+ }
152
+ refreshRead(read) {
153
+ const now = read.answer();
154
+ if (Object.is(now, read.last)) return false;
155
+ read.last = now;
156
+ return true;
157
+ }
158
+ /**
159
+ * Check whether no further fields can arrive.
160
+ * @returns whether the outer object closed, indexing failed, or the view is sealed; unread values are not validated.
161
+ */
162
+ closed() {
163
+ return this.remember("closed", "", () => this.closedNow());
164
+ }
165
+ /**
166
+ * List discovered fields in first-appearance order.
167
+ * @returns top-level keys seen so far, in first-appearance order.
168
+ */
169
+ keys() {
170
+ return this.remember("keys", "", () => this.keysNow(), (keys) => keys.length);
171
+ }
172
+ /**
173
+ * Check whether a top-level field has appeared.
174
+ * @param key - argument name.
175
+ * @returns whether the field has appeared (a string opened or another value began).
176
+ */
177
+ has(key) {
178
+ return this.remember("has", key, () => this.hasNow(key));
179
+ }
180
+ /**
181
+ * Check whether a field's closing delimiter has arrived, without validating its contents.
182
+ * @param key - argument name.
183
+ * @returns whether its delimiter arrived and no content reader has reported an error for this value.
184
+ */
185
+ complete(key) {
186
+ return this.remember("complete", key, () => this.completeNow(key));
187
+ }
188
+ /**
189
+ * Read string length without materializing its text.
190
+ * @param key - argument name.
191
+ * @param options - change granularity for a streaming string.
192
+ * @returns decoded UTF-16 length of the string field so far; undefined when absent or not a string.
193
+ */
194
+ stringLength(key, options) {
195
+ const step = Math.max(1, Math.floor(options?.step ?? 1));
196
+ const offset = options?.offset ?? 0;
197
+ return this.remember(`length:${step}:${offset}`, key, () => this.lengthNow(key), (length) => length === void 0 ? void 0 : Math.ceil((length + offset) / step));
198
+ }
199
+ /**
200
+ * Check a string against a decoded UTF-16 length limit without materializing it.
201
+ * @param key - argument name.
202
+ * @param maxLength - decoded UTF-16 limit, floored to at least zero.
203
+ * @returns whether the string is longer than the limit; false when absent or not a string.
204
+ */
205
+ stringExceeds(key, maxLength) {
206
+ const limit = Math.max(0, Math.floor(maxLength));
207
+ return this.remember(`exceeds:${limit}`, key, () => (this.lengthNow(key, limit + 1) ?? 0) > limit);
208
+ }
209
+ /**
210
+ * Read a decoded string, including a streaming prefix.
211
+ * @param key - argument name.
212
+ * @returns the string field's decoded text so far; undefined when absent or not a string.
213
+ */
214
+ text(key) {
215
+ return this.remember("text", key, () => this.textNow(key));
216
+ }
217
+ /**
218
+ * Read at most the first decoded UTF-16 units of a string.
219
+ * @param key - argument name.
220
+ * @param maxLength - maximum decoded UTF-16 length, floored to at least one.
221
+ * @returns the bounded string prefix; undefined when absent or not a string.
222
+ */
223
+ textPrefix(key, maxLength) {
224
+ const limit = Math.max(1, Math.floor(maxLength));
225
+ return this.remember(`prefix:${limit}`, key, () => this.textPrefixNow(key, limit));
226
+ }
227
+ /**
228
+ * Read a completed non-string argument.
229
+ * @param key - argument name.
230
+ * @returns the parsed non-string value once it closed; undefined while open, absent, or a string.
231
+ */
232
+ value(key) {
233
+ return this.remember("value", key, () => this.valueNow(key));
234
+ }
235
+ /** Answer a question and, on a streaming view, remember it for change detection. */
236
+ remember(kind, key, read, comparison) {
237
+ this.scan();
238
+ const result = read();
239
+ if (!this.sealed) {
240
+ const id = `${kind}/${key}`;
241
+ if (!this.#reads.has(id)) this.#reads.set(id, {
242
+ completion: kind === "complete",
243
+ answer: comparison === void 0 ? read : () => comparison(read()),
244
+ last: comparison === void 0 ? result : comparison(result)
245
+ });
246
+ }
247
+ return result;
248
+ }
249
+ closedNow() {
250
+ return this.sealed || this.#mode === "closed" || this.#mode === "invalid";
251
+ }
252
+ keysNow() {
253
+ return this.object === void 0 ? this.#order : Object.keys(this.object);
254
+ }
255
+ hasNow(key) {
256
+ return this.object === void 0 ? this.#entries.has(key) : Object.hasOwn(this.object, key);
257
+ }
258
+ completeNow(key) {
259
+ if (this.object !== void 0) return Object.hasOwn(this.object, key);
260
+ const entry = this.#entries.get(key);
261
+ return entry !== void 0 && entry.end >= 0 && (entry.kind === "string" ? entry.invalidAt === void 0 : !entry.invalid);
262
+ }
263
+ lengthNow(key, limit = Number.POSITIVE_INFINITY) {
264
+ if (this.object !== void 0) {
265
+ const field = Object.hasOwn(this.object, key) ? this.object[key] : void 0;
266
+ return typeof field === "string" ? field.length : void 0;
267
+ }
268
+ const entry = this.#entries.get(key);
269
+ if (entry?.kind !== "string") return void 0;
270
+ if (entry.text !== void 0 && entry.text.at === entry.end) return entry.text.length;
271
+ const read = entry.length ??= {
272
+ at: entry.start,
273
+ length: 0,
274
+ text: ""
275
+ };
276
+ this.readString(entry, read, limit, false);
277
+ return read.length;
278
+ }
279
+ textNow(key) {
280
+ if (this.object !== void 0) {
281
+ const field = Object.hasOwn(this.object, key) ? this.object[key] : void 0;
282
+ return typeof field === "string" ? field : void 0;
283
+ }
284
+ const entry = this.#entries.get(key);
285
+ if (entry?.kind !== "string") return void 0;
286
+ if (entry.text === void 0 && entry.end >= 0 && entry.needsDecoding && entry.invalidAt === void 0) {
287
+ let text;
288
+ try {
289
+ text = JSON.parse(`"${this.slice(entry.start, entry.end)}"`);
290
+ } catch (_error) {}
291
+ if (text !== void 0) entry.text = {
292
+ at: entry.end,
293
+ length: text.length,
294
+ text
295
+ };
296
+ }
297
+ const read = entry.text ??= {
298
+ at: entry.start,
299
+ length: 0,
300
+ text: ""
301
+ };
302
+ this.readString(entry, read, Number.POSITIVE_INFINITY, true);
303
+ return read.text;
304
+ }
305
+ textPrefixNow(key, maxLength) {
306
+ if (this.object !== void 0) {
307
+ const field = Object.hasOwn(this.object, key) ? this.object[key] : void 0;
308
+ return typeof field === "string" ? field.slice(0, maxLength) : void 0;
309
+ }
310
+ const entry = this.#entries.get(key);
311
+ if (entry?.kind !== "string") return void 0;
312
+ const prefixes = entry.prefixes ??= /* @__PURE__ */ new Map();
313
+ let read = prefixes.get(maxLength);
314
+ if (read === void 0) {
315
+ read = {
316
+ at: entry.start,
317
+ length: 0,
318
+ text: ""
319
+ };
320
+ prefixes.set(maxLength, read);
321
+ }
322
+ this.readString(entry, read, maxLength, true);
323
+ return read.text;
324
+ }
325
+ valueNow(key) {
326
+ if (this.object !== void 0) {
327
+ if (!Object.hasOwn(this.object, key)) return void 0;
328
+ const field = this.object[key];
329
+ return typeof field === "string" ? void 0 : field;
330
+ }
331
+ const entry = this.#entries.get(key);
332
+ if (entry?.kind !== "value" || entry.end < 0 || entry.invalid) return void 0;
333
+ if (entry.parsed === void 0) try {
334
+ entry.parsed = JSON.parse(this.slice(entry.start, entry.end));
335
+ } catch (_error) {
336
+ entry.invalid = true;
337
+ this.#invalidValue = true;
338
+ }
339
+ return entry.parsed;
340
+ }
341
+ chunkAt(at) {
342
+ let low = 0;
343
+ let high = this.#ends.length;
344
+ while (low < high) {
345
+ const mid = low + high >>> 1;
346
+ if (this.#ends[mid] <= at) low = mid + 1;
347
+ else high = mid;
348
+ }
349
+ return low;
350
+ }
351
+ /** Materialize only a requested range, never the cumulative source. */
352
+ slice(start, end) {
353
+ if (start >= end) return "";
354
+ const first = this.chunkAt(start);
355
+ const last = this.chunkAt(end - 1);
356
+ const base = first === 0 ? 0 : this.#ends[first - 1];
357
+ if (first === last) return this.chunks[first].slice(start - base, end - base);
358
+ const parts = [this.chunks[first].slice(start - base)];
359
+ for (let i = first + 1; i < last; i++) parts.push(this.chunks[i]);
360
+ parts.push(this.chunks[last].slice(0, end - this.#ends[last - 1]));
361
+ return parts.join("");
362
+ }
363
+ readString(entry, read, limit, materialize) {
364
+ const end = Math.min(entry.end < 0 ? this.#consumed : entry.end, entry.invalidAt ?? Number.POSITIVE_INFINITY, this.#invalidAt ?? Number.POSITIVE_INFINITY);
365
+ if (!entry.needsDecoding) {
366
+ const length = Math.min(end - read.at, limit - read.length);
367
+ if (length <= 0) return;
368
+ if (materialize) read.text += this.slice(read.at, read.at + length);
369
+ read.at += length;
370
+ read.length += length;
371
+ return;
372
+ }
373
+ let chunkIndex = this.chunkAt(read.at);
374
+ while (read.at < end && read.length < limit) {
375
+ const base = chunkIndex === 0 ? 0 : this.#ends[chunkIndex - 1];
376
+ const chunk = this.chunks[chunkIndex];
377
+ const remaining = chunk.slice(read.at - base, Math.min(chunk.length, end - base));
378
+ const boundary = remaining.search(CONTENT_ESCAPE);
379
+ const length = Math.min(boundary < 0 ? remaining.length : boundary, limit - read.length);
380
+ if (length > 0) {
381
+ if (materialize) read.text += remaining.slice(0, length);
382
+ read.at += length;
383
+ read.length += length;
384
+ if (read.at === base + chunk.length) chunkIndex++;
385
+ continue;
386
+ }
387
+ const type = remaining.length > 1 ? remaining[1] : read.at + 1 < end ? this.chunks[chunkIndex + 1][0] : void 0;
388
+ let decoded;
389
+ let width = 2;
390
+ if (remaining[0] === "\\" && type === void 0 && entry.end < 0) return;
391
+ if (remaining[0] === "\\" && type === "u") {
392
+ const hex = this.slice(read.at + 2, Math.min(end, read.at + 6));
393
+ let valid = true;
394
+ for (let i = 0; i < hex.length; i++) if (!isHex(hex[i])) valid = false;
395
+ if (valid) {
396
+ if (hex.length < 4 && entry.end < 0) return;
397
+ if (hex.length === 4) decoded = String.fromCharCode(Number.parseInt(hex, 16));
398
+ }
399
+ width = 6;
400
+ } else if (remaining[0] === "\\" && type !== void 0) decoded = SIMPLE_ESCAPES[type];
401
+ if (decoded === void 0) {
402
+ entry.invalidAt = read.at;
403
+ this.#invalidValue = true;
404
+ return;
405
+ }
406
+ if (materialize) read.text += decoded;
407
+ read.length++;
408
+ read.at += width;
409
+ while (chunkIndex < this.chunks.length && read.at >= this.#ends[chunkIndex]) chunkIndex++;
410
+ }
411
+ }
412
+ /** Locate new field ranges without decoding or parsing their contents. */
413
+ scan() {
414
+ if (this.object !== void 0 || this.#consumed === this.#size) return;
415
+ for (let i = this.chunkAt(this.#consumed); i < this.chunks.length && this.#invalidAt === void 0; i++) {
416
+ const pending = this.chunks[i];
417
+ const base = i === 0 ? 0 : this.#ends[i - 1];
418
+ for (let index = this.#consumed - base; index < pending.length && this.#mode !== "invalid"; index++) {
419
+ if (this.#mode === "string" || this.#mode === "nested" && this.#nestedInString) {
420
+ const end = this.stringBoundary(pending, index);
421
+ this.#consumed += end - index;
422
+ index = end;
423
+ if (index === pending.length) break;
424
+ }
425
+ this.step(pending[index], this.#consumed);
426
+ this.#consumed++;
427
+ }
428
+ }
429
+ }
430
+ /** Only raw quotes and their preceding backslash runs can terminate a string. */
431
+ stringBoundary(fragment, start) {
432
+ let at = start;
433
+ while (true) {
434
+ const quote = fragment.indexOf("\"", at);
435
+ const end = quote < 0 ? fragment.length : quote;
436
+ if (this.#mode === "string") {
437
+ const entry = this.#current;
438
+ if (!entry.needsDecoding && CONTENT_ESCAPE.test(fragment.slice(at, end))) entry.needsDecoding = true;
439
+ }
440
+ let slashStart = end;
441
+ while (slashStart > at && fragment[slashStart - 1] === "\\") slashStart--;
442
+ const escaped = (end - slashStart) % 2 === 1 !== (slashStart === at && this.#escape);
443
+ this.#escape = quote < 0 && escaped;
444
+ if (quote < 0 || !escaped) return end;
445
+ at = quote + 1;
446
+ }
447
+ }
448
+ step(c, at) {
449
+ switch (this.#mode) {
450
+ case "root":
451
+ if (isWhitespace(c)) return;
452
+ if (c === "{") {
453
+ this.#mode = "key-or-end";
454
+ return;
455
+ }
456
+ this.fail();
457
+ return;
458
+ case "key-or-end":
459
+ if (isWhitespace(c)) return;
460
+ if (c === "}") {
461
+ this.#mode = "closed";
462
+ return;
463
+ }
464
+ if (c === "\"") {
465
+ this.beginKey(at);
466
+ return;
467
+ }
468
+ this.fail();
469
+ return;
470
+ case "key-only":
471
+ if (isWhitespace(c)) return;
472
+ if (c === "\"") {
473
+ this.beginKey(at);
474
+ return;
475
+ }
476
+ this.fail();
477
+ return;
478
+ case "key":
479
+ this.stepKey(c, at);
480
+ return;
481
+ case "colon":
482
+ if (isWhitespace(c)) return;
483
+ if (c === ":") {
484
+ this.#mode = "value";
485
+ return;
486
+ }
487
+ this.fail();
488
+ return;
489
+ case "value":
490
+ this.beginValue(c, at);
491
+ return;
492
+ case "string": {
493
+ const entry = this.#current;
494
+ entry.end = at;
495
+ this.#current = null;
496
+ this.#mode = "comma-or-end";
497
+ return;
498
+ }
499
+ case "scalar":
500
+ this.stepScalar(c, at);
501
+ return;
502
+ case "nested":
503
+ this.stepNested(c, at);
504
+ return;
505
+ case "comma-or-end":
506
+ if (isWhitespace(c)) return;
507
+ if (c === ",") {
508
+ this.#mode = "key-only";
509
+ return;
510
+ }
511
+ if (c === "}") {
512
+ this.#mode = "closed";
513
+ return;
514
+ }
515
+ this.fail();
516
+ return;
517
+ case "closed":
518
+ if (isWhitespace(c)) return;
519
+ this.fail();
520
+ return;
521
+ /* v8 ignore next 2 -- scan() stops stepping once the view is invalid. */
522
+ case "invalid": return;
523
+ /* v8 ignore next 2 -- Every scanner mode has a handler above. */
524
+ default: assertNever(this.#mode);
525
+ }
526
+ }
527
+ fail() {
528
+ this.#invalidAt = this.#consumed;
529
+ this.#mode = "invalid";
530
+ this.#current = null;
531
+ }
532
+ beginKey(at) {
533
+ this.#mode = "key";
534
+ this.#keyStart = at + 1;
535
+ this.#keyEscaped = false;
536
+ this.#escape = false;
537
+ }
538
+ stepKey(c, at) {
539
+ if (c < " ") {
540
+ this.fail();
541
+ return;
542
+ }
543
+ if (this.#escape) {
544
+ this.#escape = false;
545
+ return;
546
+ }
547
+ if (c === "\\") {
548
+ this.#escape = true;
549
+ this.#keyEscaped = true;
550
+ return;
551
+ }
552
+ if (c !== "\"") return;
553
+ const raw = this.slice(this.#keyStart, at);
554
+ if (this.#keyEscaped) try {
555
+ this.#key = JSON.parse(`"${raw}"`);
556
+ } catch (_error) {
557
+ this.fail();
558
+ return;
559
+ }
560
+ else this.#key = raw;
561
+ this.#mode = "colon";
562
+ }
563
+ open(entry) {
564
+ if (!this.#entries.has(this.#key)) this.#order.push(this.#key);
565
+ this.#entries.set(this.#key, entry);
566
+ this.#current = entry;
567
+ }
568
+ beginValue(c, at) {
569
+ if (isWhitespace(c)) return;
570
+ if (c === "\"") {
571
+ this.open({
572
+ kind: "string",
573
+ start: at + 1,
574
+ end: -1,
575
+ needsDecoding: false,
576
+ invalidAt: void 0,
577
+ length: void 0,
578
+ text: void 0,
579
+ prefixes: void 0
580
+ });
581
+ this.#escape = false;
582
+ this.#mode = "string";
583
+ return;
584
+ }
585
+ if (c === "}" || c === "," || c === ":" || c === "]") {
586
+ this.fail();
587
+ return;
588
+ }
589
+ this.open({
590
+ kind: "value",
591
+ start: at,
592
+ end: -1,
593
+ parsed: void 0,
594
+ invalid: false
595
+ });
596
+ if (c === "{" || c === "[") {
597
+ this.#mode = "nested";
598
+ this.#nestedEnds = [c === "{" ? "}" : "]"];
599
+ this.#nestedInString = false;
600
+ this.#escape = false;
601
+ return;
602
+ }
603
+ this.#mode = "scalar";
604
+ }
605
+ stepScalar(c, at) {
606
+ if (c !== "," && c !== "}" && !isWhitespace(c)) return;
607
+ this.closeValue(at);
608
+ this.#mode = c === "," ? "key-only" : c === "}" ? "closed" : "comma-or-end";
609
+ }
610
+ stepNested(c, at) {
611
+ if (this.#nestedInString) {
612
+ this.#nestedInString = false;
613
+ return;
614
+ }
615
+ if (c === "\"") {
616
+ this.#nestedInString = true;
617
+ return;
618
+ }
619
+ if (c === "{" || c === "[") {
620
+ this.#nestedEnds.push(c === "{" ? "}" : "]");
621
+ return;
622
+ }
623
+ if (c === "}" || c === "]") {
624
+ if (this.#nestedEnds.pop() !== c) {
625
+ this.fail();
626
+ return;
627
+ }
628
+ if (this.#nestedEnds.length === 0) {
629
+ this.closeValue(at + 1);
630
+ this.#mode = "comma-or-end";
631
+ }
632
+ }
633
+ }
634
+ closeValue(end) {
635
+ const entry = this.#current;
636
+ entry.end = end;
637
+ this.#current = null;
638
+ }
639
+ });
640
+ //#endregion
641
+ //#region ../../util/values/src/index.ts
642
+ /**
643
+ * Mark an unreachable closed-union branch.
644
+ * @param value - impossible value; an unhandled typed variant fails at the call site.
645
+ * @param context - optional switch-site label included in the failure message.
646
+ * @returns never; a runtime value that escaped its type always throws.
647
+ */
648
+ function assertNever(value, context) {
649
+ const rendered = JSON.stringify(value) ?? String(value);
650
+ throw new Error(`unreachable variant${context ? ` in ${context}` : ""}: ${rendered}`);
651
+ }
652
+ //#endregion
653
+ //#region ../../core/session/src/types.ts
654
+ /**
655
+ * Admit a numeric value as an existing Session event position.
656
+ * @param value - non-negative safe integer admitted by the owning log operation.
657
+ * @returns the same number with the Session-sequence brand.
658
+ */
659
+ function SessionSeq(value) {
660
+ if (!Number.isSafeInteger(value) || value < 0 || Object.is(value, -0)) throw new TypeError(`SessionSeq must be a non-negative safe integer, got ${String(value)}`);
661
+ return brandNumber(value);
662
+ }
663
+ //#endregion
664
+ //#region lib/types/index.js
665
+ /**
666
+ * Durable session skill catalog and model-facing `skill` loader tool.
667
+ *
668
+ * @module @qilin-agent/tool-skill
669
+ */
670
+ const name = "tool-skill";
671
+ const inject = [
672
+ "agents",
673
+ "tools",
674
+ "skills"
675
+ ];
676
+ const DEFAULT_CATALOG_DESCRIPTION_MAX_LENGTH = 500;
677
+ /** Durable entry list mirroring the rendered catalog lines, for non-model consumers. */
678
+ function catalogSourceEntries(skills, descriptionMaxLength) {
679
+ return skills.map((skill) => ({
680
+ name: skill.name,
681
+ description: catalogDescription(skill.description, descriptionMaxLength)
682
+ }));
683
+ }
684
+ /** Validate and default the model-facing skill catalog configuration. */
685
+ const Config = z.object({ catalogDescriptionMaxLength: z.number().default(DEFAULT_CATALOG_DESCRIPTION_MAX_LENGTH) });
686
+ /**
687
+ * Register the model-facing skill loader and its visibility-matched
688
+ * durable session catalog. The catalog is emitted only when the calling agent
689
+ * resolves this plugin's exact tool registration; a restriction or scoped
690
+ * same-name shadow therefore removes both the schema and its call guidance.
691
+ */
692
+ function apply(ctx, config = {}) {
693
+ const catalogDescriptionMaxLength = config.catalogDescriptionMaxLength ?? DEFAULT_CATALOG_DESCRIPTION_MAX_LENGTH;
694
+ assertPositiveInteger("catalogDescriptionMaxLength", catalogDescriptionMaxLength, 3);
695
+ const skillTool = defineTool({
696
+ name: "skill",
697
+ description: "Load the full instructions for an available skill. Call this with the exact skill name from the session skill catalog before acting on a task that names or clearly matches that skill.",
698
+ parameters: { name: {
699
+ type: "string",
700
+ required: true,
701
+ description: "The exact skill name from the available skills list."
702
+ } },
703
+ output: {
704
+ schema: {
705
+ type: "object",
706
+ additionalProperties: false,
707
+ properties: {
708
+ name: {
709
+ type: "string",
710
+ required: true
711
+ },
712
+ provider: {
713
+ type: "string",
714
+ required: true
715
+ },
716
+ resourceBase: { oneOf: [
717
+ {
718
+ type: "object",
719
+ additionalProperties: false,
720
+ properties: {
721
+ kind: {
722
+ type: "string",
723
+ required: true,
724
+ const: "directory"
725
+ },
726
+ path: {
727
+ type: "string",
728
+ required: true
729
+ }
730
+ }
731
+ },
732
+ {
733
+ type: "object",
734
+ additionalProperties: false,
735
+ properties: {
736
+ kind: {
737
+ type: "string",
738
+ required: true,
739
+ const: "url"
740
+ },
741
+ url: {
742
+ type: "string",
743
+ required: true
744
+ }
745
+ }
746
+ },
747
+ {
748
+ type: "object",
749
+ additionalProperties: false,
750
+ properties: {
751
+ kind: {
752
+ type: "string",
753
+ required: true,
754
+ const: "opaque"
755
+ },
756
+ description: {
757
+ type: "string",
758
+ required: true
759
+ }
760
+ }
761
+ }
762
+ ] },
763
+ content: {
764
+ type: "string",
765
+ required: true
766
+ }
767
+ }
768
+ },
769
+ render: (_args, value) => [{
770
+ type: "text",
771
+ text: renderSkillContent(value)
772
+ }]
773
+ },
774
+ async execute(args, exec) {
775
+ if (!isSkillName(args.name)) throw new Error(`invalid skill name "${args.name}"`);
776
+ const lookup = {
777
+ cwd: exec.agent?.session.header.cwd,
778
+ signal: exec.signal,
779
+ scope: exec.agent
780
+ };
781
+ const summary = (await ctx.skills.list(lookup)).find((skill) => skill.name === args.name);
782
+ if (!summary) throw new Error(`skill "${args.name}" is unknown or no longer available`);
783
+ if (!isModelInvocable(summary)) throw new Error(`skill "${args.name}" is not available for model invocation`);
784
+ const skill = await ctx.skills.get(args.name, lookup);
785
+ if (!skill) throw new Error(`skill "${args.name}" is unknown or no longer available`);
786
+ if (!isModelInvocable(skill)) throw new Error(`skill "${args.name}" is not available for model invocation`);
787
+ return {
788
+ name: skill.name,
789
+ provider: skill.provider,
790
+ ...skill.resourceBase !== void 0 ? { resourceBase: { ...skill.resourceBase } } : {},
791
+ content: skill.content
792
+ };
793
+ },
794
+ presentCall(args) {
795
+ return {
796
+ card: "generic",
797
+ title: `Load skill ${args.name}`,
798
+ kind: "read",
799
+ rawInput: args.name
800
+ };
801
+ }
802
+ });
803
+ ctx.tools.register(skillTool);
804
+ ctx.on("agent/pre-step", async ({ agent, messages, signal }, next) => {
805
+ const decision = await next();
806
+ if (decision.kind === "reject") return decision;
807
+ const names = invokedSkillNames(messages);
808
+ if (names.length === 0) return decision;
809
+ signal.throwIfAborted();
810
+ const lookup = {
811
+ cwd: agent.session.header.cwd,
812
+ signal,
813
+ scope: agent
814
+ };
815
+ const injections = [];
816
+ for (const name of names) {
817
+ const skill = await ctx.skills.get(name, lookup);
818
+ signal.throwIfAborted();
819
+ if (skill === void 0 || !isUserInvocable(skill)) continue;
820
+ const source = {
821
+ kind: "skill-invocation",
822
+ name,
823
+ form: "instructions"
824
+ };
825
+ injections.push(createUserMessage({
826
+ content: [{
827
+ type: "text",
828
+ text: renderSkillContent(skill)
829
+ }],
830
+ source
831
+ }));
832
+ }
833
+ if (injections.length === 0) return decision;
834
+ return {
835
+ ...decision,
836
+ messages: [...decision.messages, ...injections]
837
+ };
838
+ });
839
+ ctx.on("agent/pre-step", async ({ agent, signal }, next) => {
840
+ const decision = await next();
841
+ if (decision.kind === "reject") return decision;
842
+ signal.throwIfAborted();
843
+ const snapshot = ctx.tools.get(skillTool.name, agent) === skillTool ? await ctx.skills.snapshot({
844
+ cwd: agent.session.header.cwd,
845
+ signal,
846
+ scope: agent
847
+ }) : {
848
+ skills: [],
849
+ complete: true
850
+ };
851
+ signal.throwIfAborted();
852
+ if (!snapshot.complete) return decision;
853
+ const skills = snapshot.skills.filter(isModelInvocable);
854
+ const entries = catalogSourceEntries(skills, catalogDescriptionMaxLength);
855
+ const digest = digestCatalogEntries(entries);
856
+ const history = catalogHistory(agent);
857
+ const existing = catalogMessage(decision.messages);
858
+ if (history.visibleDigest === digest) return existing === void 0 ? decision : {
859
+ ...decision,
860
+ messages: decision.messages.filter((message) => message.id !== existing.message.id)
861
+ };
862
+ if (existing !== void 0 && digestCatalogEntries(existing.entries) === digest) return decision;
863
+ if (!history.published && skills.length === 0) return existing === void 0 ? decision : {
864
+ ...decision,
865
+ messages: decision.messages.filter((message) => message.id !== existing.message.id)
866
+ };
867
+ const catalog = history.published ? renderCatalogUpdate(entries) : renderCatalogMessage(entries);
868
+ return {
869
+ ...decision,
870
+ messages: existing === void 0 ? [...decision.messages, catalog] : decision.messages.map((message) => message.id === existing.message.id ? catalog : message)
871
+ };
872
+ });
873
+ }
874
+ function renderCatalogMessage(entries) {
875
+ return createUserMessage({
876
+ content: [{
877
+ type: "text",
878
+ text: [
879
+ "<system-reminder>",
880
+ "A skill is a reusable set of task-specific instructions. The following skills are available in this session:",
881
+ "",
882
+ "<available_skills>",
883
+ ...renderCatalogEntries(entries),
884
+ "</available_skills>",
885
+ "",
886
+ "If the user names a skill, or the task clearly matches a skill's description, call the `skill` tool with the exact skill name before taking task actions. Load all applicable skills, then follow their full instructions. This catalog contains summaries only; do not infer or follow a skill's instructions until it has been loaded.",
887
+ "A user may also invoke a skill directly; its <skill_content> block then appears in this conversation. Follow it, and do not call the `skill` tool again for that skill.",
888
+ "</system-reminder>"
889
+ ].join("\n")
890
+ }],
891
+ source: {
892
+ kind: "skill-catalog",
893
+ form: "catalog",
894
+ entries
895
+ }
896
+ });
897
+ }
898
+ function renderCatalogUpdate(entries) {
899
+ const availability = entries.length === 0 ? ["No skills are currently available through the `skill` tool. Do not use names from earlier skill catalogs.", "A user may still invoke a skill directly; its <skill_content> block then appears in this conversation. Follow it, and do not call the `skill` tool for it."] : ["Use only names in this replacement catalog. If the user names a listed skill, or the task clearly matches its description, call the `skill` tool with the exact name before acting.", "A user may also invoke a skill directly; its <skill_content> block then appears in this conversation. Follow it, and do not call the `skill` tool again for that skill."];
900
+ return createUserMessage({
901
+ content: [{
902
+ type: "text",
903
+ text: [
904
+ "<system-reminder>",
905
+ "The available skill catalog changed. This complete catalog replaces every earlier available-skills list in this session:",
906
+ "",
907
+ "<available_skills>",
908
+ ...renderCatalogEntries(entries),
909
+ "</available_skills>",
910
+ "",
911
+ ...availability,
912
+ "</system-reminder>"
913
+ ].join("\n")
914
+ }],
915
+ source: {
916
+ kind: "skill-catalog",
917
+ form: "catalog",
918
+ update: true,
919
+ entries
920
+ }
921
+ });
922
+ }
923
+ /**
924
+ * Model-facing catalog lines, projected from the same entries the source records.
925
+ * The pseudo-XML escaping belongs to this frame, not to the published fact, so it
926
+ * is applied here and never stored. Names are `isSkillName`-validated and carry
927
+ * no escapable character.
928
+ */
929
+ function renderCatalogEntries(entries) {
930
+ return entries.map((entry) => `- \`${entry.name}\`: ${escapeText(entry.description)}`);
931
+ }
932
+ /**
933
+ * Catalog identity over the durable entry list rather than the rendered prose.
934
+ * The entries are what changes; the surrounding `<system-reminder>` framing is
935
+ * written for the model and must not decide whether a republish is needed.
936
+ */
937
+ function digestCatalogEntries(entries) {
938
+ const canonical = entries.map((entry) => JSON.stringify([entry.name, entry.description])).join("\n");
939
+ return createHash("sha256").update(canonical).digest("hex");
940
+ }
941
+ /**
942
+ * Entries of one durable catalog message, or undefined when the record is not a
943
+ * usable catalog.
944
+ *
945
+ * `agent.session.snapshotEvents()` may contain a resumed, forked, or externally written seed,
946
+ * and seed validation only guarantees a source object with a non-empty `kind`;
947
+ * no per-kind field is checked there. An unreadable record is therefore treated
948
+ * as "not this plugin's catalog" — the posture the replaced content digest had —
949
+ * rather than throwing inside the step listener, which would fail every
950
+ * subsequent turn of that session.
951
+ */
952
+ function readCatalogEntries(source) {
953
+ const entries = source.entries;
954
+ if (!Array.isArray(entries)) return void 0;
955
+ const readable = [];
956
+ for (const entry of entries) {
957
+ if (typeof entry !== "object" || entry === null) return void 0;
958
+ const { name, description } = entry;
959
+ if (typeof name !== "string" || name === "" || typeof description !== "string") return void 0;
960
+ readable.push({
961
+ name,
962
+ description
963
+ });
964
+ }
965
+ return readable;
966
+ }
967
+ function catalogHistory(agent) {
968
+ const visible = new Set(agent.session.surface.nodes);
969
+ let published = false;
970
+ for (let index = agent.session.seq - 1; index >= 0; index -= 1) {
971
+ const event = agent.session.eventAt(SessionSeq(index));
972
+ if (event === void 0) throw new Error(`skill catalog cannot read seq ${String(index)} below the current Session length`);
973
+ if (event.type !== "user/message" || event.data.source.kind !== "skill-catalog") continue;
974
+ const entries = readCatalogEntries(event.data.source);
975
+ if (entries === void 0) continue;
976
+ const digest = digestCatalogEntries(entries);
977
+ published = true;
978
+ if (visible.has(event.seq)) return {
979
+ visibleDigest: digest,
980
+ published
981
+ };
982
+ }
983
+ return { published };
984
+ }
985
+ function catalogMessage(messages) {
986
+ for (const message of messages) {
987
+ if (message.source.kind !== "skill-catalog") continue;
988
+ const entries = readCatalogEntries(message.source);
989
+ if (entries !== void 0) return {
990
+ message,
991
+ entries
992
+ };
993
+ }
994
+ }
995
+ function catalogDescription(value, maxLength) {
996
+ const normalized = value.replaceAll(/\s+/g, " ").trim();
997
+ return normalized.length <= maxLength ? normalized : `${normalized.slice(0, maxLength - 3)}...`;
998
+ }
999
+ function assertPositiveInteger(name, value, minimum = 1) {
1000
+ if (!Number.isInteger(value) || value < minimum) throw new Error(`tool-skill: ${name} must be an integer greater than or equal to ${minimum}`);
1001
+ }
1002
+ /**
1003
+ * A whitespace-bounded `/name` token (the public skill-name grammar) anywhere
1004
+ * in the text — the same word-boundary shape the transcript chip decoration
1005
+ * uses, so a gesture reads as one wherever it sits in the sentence. A second
1006
+ * `/` or any non-boundary character breaks the match, which keeps file paths
1007
+ * (`/usr/bin`) and fractions (`5/8`) out.
1008
+ */
1009
+ const SKILL_GESTURE = /(^|\s)\/([a-z0-9]+(?:-[a-z0-9]+)*)(?=\s|$)/g;
1010
+ /**
1011
+ * `/name` gesture tokens from the claimed user messages, deduplicated in
1012
+ * first-seen order. Every text block of direct user input is scanned; no
1013
+ * other source can forge a gesture.
1014
+ * @param messages - the step's claimed batch.
1015
+ * @returns candidate skill names, unvalidated against the registry.
1016
+ */
1017
+ function invokedSkillNames(messages) {
1018
+ const names = [];
1019
+ for (const message of messages) {
1020
+ if (message.source.kind !== "user") continue;
1021
+ for (const block of message.content) {
1022
+ if (block.type !== "text") continue;
1023
+ for (const match of block.text.matchAll(SKILL_GESTURE)) {
1024
+ const name = match[2];
1025
+ if (name !== void 0 && !names.includes(name)) names.push(name);
1026
+ }
1027
+ }
1028
+ }
1029
+ return names;
1030
+ }
1031
+ //#endregion
1032
+ export { Config, apply, inject, name };