tenjin-cli 0.1.0-alpha.4 → 0.1.0-alpha.7
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/README.md +269 -38
- package/dist/{buy-OOOLUDND.js → buy-XVOMNWKN.js} +21 -18
- package/dist/{candidate-TWCWTFGA.js → candidate-DJB2NNTG.js} +7 -8
- package/dist/{chunk-KXIX7YDV.js → chunk-2KIDDWQO.js} +5 -5
- package/dist/{chunk-NXCJN2FJ.js → chunk-2L73UI6T.js} +51 -42
- package/dist/chunk-2L73UI6T.js.map +1 -0
- package/dist/{chunk-OJD54DIU.js → chunk-2YX6LTCD.js} +5 -5
- package/dist/{chunk-H5ETJRQD.js → chunk-5X4EBGGU.js} +22 -14
- package/dist/chunk-5X4EBGGU.js.map +1 -0
- package/dist/chunk-6S44OLND.js +699 -0
- package/dist/chunk-6S44OLND.js.map +1 -0
- package/dist/{chunk-FU6MCSLG.js → chunk-7WDY4AXV.js} +2 -64
- package/dist/chunk-7WDY4AXV.js.map +1 -0
- package/dist/{chunk-VV4P5RVK.js → chunk-BBUYCDSG.js} +16 -4
- package/dist/chunk-BBUYCDSG.js.map +1 -0
- package/dist/chunk-CYRYVZPN.js +213 -0
- package/dist/chunk-CYRYVZPN.js.map +1 -0
- package/dist/{chunk-FHB3VKZW.js → chunk-DAJ56EUU.js} +5 -3
- package/dist/chunk-DAJ56EUU.js.map +1 -0
- package/dist/chunk-DH6D6QIO.js +239 -0
- package/dist/chunk-DH6D6QIO.js.map +1 -0
- package/dist/chunk-E6BNARCS.js +614 -0
- package/dist/chunk-E6BNARCS.js.map +1 -0
- package/dist/chunk-GABYDXWL.js +190 -0
- package/dist/chunk-GABYDXWL.js.map +1 -0
- package/dist/{chunk-EUQN3L5X.js → chunk-GM4RZUVU.js} +21 -9
- package/dist/chunk-GM4RZUVU.js.map +1 -0
- package/dist/{chunk-C4TIWOAM.js → chunk-GXYNLMUQ.js} +28 -11
- package/dist/chunk-GXYNLMUQ.js.map +1 -0
- package/dist/{chunk-6WWVYYSB.js → chunk-J6CVKC4M.js} +86 -4
- package/dist/chunk-J6CVKC4M.js.map +1 -0
- package/dist/{chunk-5JH7ZB6Z.js → chunk-KT2DGKFT.js} +76 -10
- package/dist/chunk-KT2DGKFT.js.map +1 -0
- package/dist/chunk-L6AV2Q73.js +105 -0
- package/dist/chunk-L6AV2Q73.js.map +1 -0
- package/dist/{chunk-333FOTUJ.js → chunk-MJZZTKCC.js} +108 -2
- package/dist/chunk-MJZZTKCC.js.map +1 -0
- package/dist/{chunk-XNNOR7F7.js → chunk-OTDI5FXG.js} +3 -5
- package/dist/{chunk-XNNOR7F7.js.map → chunk-OTDI5FXG.js.map} +1 -1
- package/dist/chunk-PIIWLEEG.js +337 -0
- package/dist/chunk-PIIWLEEG.js.map +1 -0
- package/dist/{chunk-ULLWHHIT.js → chunk-PLU3E63S.js} +468 -559
- package/dist/chunk-PLU3E63S.js.map +1 -0
- package/dist/chunk-QW2Q2KAH.js +27 -0
- package/dist/chunk-QW2Q2KAH.js.map +1 -0
- package/dist/{chunk-S3KZ3PPK.js → chunk-RGFBBNGP.js} +291 -59
- package/dist/chunk-RGFBBNGP.js.map +1 -0
- package/dist/chunk-SGK2B724.js +67 -0
- package/dist/chunk-SGK2B724.js.map +1 -0
- package/dist/chunk-UYP7G3GZ.js +412 -0
- package/dist/chunk-UYP7G3GZ.js.map +1 -0
- package/dist/{chunk-DPUMEMGM.js → chunk-VZ3AJCO5.js} +3 -5
- package/dist/{chunk-DPUMEMGM.js.map → chunk-VZ3AJCO5.js.map} +1 -1
- package/dist/{chunk-QH6677FJ.js → chunk-WDJTGVKN.js} +2 -2
- package/dist/{chunk-QH6677FJ.js.map → chunk-WDJTGVKN.js.map} +1 -1
- package/dist/{chunk-4GR7DGD6.js → chunk-WI5EOAQQ.js} +33 -256
- package/dist/{chunk-4GR7DGD6.js.map → chunk-WI5EOAQQ.js.map} +1 -1
- package/dist/{chunk-DPET3TW5.js → chunk-WRWCDLVK.js} +13 -12
- package/dist/chunk-WRWCDLVK.js.map +1 -0
- package/dist/chunk-XBJ3VLWX.js +35 -0
- package/dist/chunk-XBJ3VLWX.js.map +1 -0
- package/dist/chunk-ZEWY3RJ3.js +149 -0
- package/dist/chunk-ZEWY3RJ3.js.map +1 -0
- package/dist/chunk-ZFE7STX7.js +143 -0
- package/dist/chunk-ZFE7STX7.js.map +1 -0
- package/dist/{cli-AFSLAKR6.js → cli-7B2QNJG3.js} +247 -26
- package/dist/cli-7B2QNJG3.js.map +1 -0
- package/dist/{config-DBEEM3UA.js → config-SAQEQRFB.js} +7 -6
- package/dist/{doctor-XDA3YU6H.js → doctor-ENJ22XWN.js} +10 -8
- package/dist/{publish-IH7RJXGB.js → edit-2QO5GQDU.js} +19 -17
- package/dist/index.js +1 -1
- package/dist/{inspect-YBGDAG47.js → inspect-IPKKQB2S.js} +16 -15
- package/dist/{install-7J6KKEEP.js → install-7ZIYISQ7.js} +180 -133
- package/dist/install-7ZIYISQ7.js.map +1 -0
- package/dist/outcome-NSDE2KAJ.js +20 -0
- package/dist/publish-7WIFFNFG.js +40 -0
- package/dist/read-5TQR7LCF.js +158 -0
- package/dist/read-5TQR7LCF.js.map +1 -0
- package/dist/{run-DCZFEW2C.js → run-NPKIP26Y.js} +109 -34
- package/dist/{run-DCZFEW2C.js.map → run-NPKIP26Y.js.map} +1 -1
- package/dist/search-63ELMRZH.js +24 -0
- package/dist/send-ENE47KQE.js +222 -0
- package/dist/send-ENE47KQE.js.map +1 -0
- package/dist/session-FZU4VFFE.js +87 -0
- package/dist/session-FZU4VFFE.js.map +1 -0
- package/dist/{usdc-AU6ZIKA6.js → usdc-4VCDHFWX.js} +20 -4
- package/dist/{wallet-UWHSHWC6.js → wallet-OCCGEH6H.js} +8 -8
- package/dist/{wallet-HKG3GSTX.js → wallet-RBDVNZVR.js} +17 -7
- package/dist/wallet-RBDVNZVR.js.map +1 -0
- package/package.json +1 -1
- package/skills/tenjin/SKILL.md +32 -7
- package/skills/tenjin-publish/SKILL.md +109 -16
- package/skills/tenjin-search/SKILL.md +174 -15
- package/dist/chunk-333FOTUJ.js.map +0 -1
- package/dist/chunk-5JH7ZB6Z.js.map +0 -1
- package/dist/chunk-6WWVYYSB.js.map +0 -1
- package/dist/chunk-BXUS5UCT.js +0 -212
- package/dist/chunk-BXUS5UCT.js.map +0 -1
- package/dist/chunk-C4TIWOAM.js.map +0 -1
- package/dist/chunk-CJU555P5.js +0 -333
- package/dist/chunk-CJU555P5.js.map +0 -1
- package/dist/chunk-DPET3TW5.js.map +0 -1
- package/dist/chunk-EUQN3L5X.js.map +0 -1
- package/dist/chunk-FHB3VKZW.js.map +0 -1
- package/dist/chunk-FU6MCSLG.js.map +0 -1
- package/dist/chunk-H5ETJRQD.js.map +0 -1
- package/dist/chunk-MM4TGTST.js +0 -59
- package/dist/chunk-MM4TGTST.js.map +0 -1
- package/dist/chunk-MUBUQVC3.js +0 -67
- package/dist/chunk-MUBUQVC3.js.map +0 -1
- package/dist/chunk-NXCJN2FJ.js.map +0 -1
- package/dist/chunk-R7BMDJZM.js +0 -167
- package/dist/chunk-R7BMDJZM.js.map +0 -1
- package/dist/chunk-S3KZ3PPK.js.map +0 -1
- package/dist/chunk-ULLWHHIT.js.map +0 -1
- package/dist/chunk-VV4P5RVK.js.map +0 -1
- package/dist/chunk-YFREUEUI.js +0 -78
- package/dist/chunk-YFREUEUI.js.map +0 -1
- package/dist/cli-AFSLAKR6.js.map +0 -1
- package/dist/install-7J6KKEEP.js.map +0 -1
- package/dist/outcome-ZFGHX2XW.js +0 -20
- package/dist/search-R6NIQFXI.js +0 -24
- /package/dist/{buy-OOOLUDND.js.map → buy-XVOMNWKN.js.map} +0 -0
- /package/dist/{candidate-TWCWTFGA.js.map → candidate-DJB2NNTG.js.map} +0 -0
- /package/dist/{chunk-KXIX7YDV.js.map → chunk-2KIDDWQO.js.map} +0 -0
- /package/dist/{chunk-OJD54DIU.js.map → chunk-2YX6LTCD.js.map} +0 -0
- /package/dist/{config-DBEEM3UA.js.map → config-SAQEQRFB.js.map} +0 -0
- /package/dist/{doctor-XDA3YU6H.js.map → doctor-ENJ22XWN.js.map} +0 -0
- /package/dist/{inspect-YBGDAG47.js.map → edit-2QO5GQDU.js.map} +0 -0
- /package/dist/{outcome-ZFGHX2XW.js.map → inspect-IPKKQB2S.js.map} +0 -0
- /package/dist/{publish-IH7RJXGB.js.map → outcome-NSDE2KAJ.js.map} +0 -0
- /package/dist/{search-R6NIQFXI.js.map → publish-7WIFFNFG.js.map} +0 -0
- /package/dist/{usdc-AU6ZIKA6.js.map → search-63ELMRZH.js.map} +0 -0
- /package/dist/{wallet-HKG3GSTX.js.map → usdc-4VCDHFWX.js.map} +0 -0
- /package/dist/{wallet-UWHSHWC6.js.map → wallet-OCCGEH6H.js.map} +0 -0
|
@@ -5,17 +5,20 @@ import {
|
|
|
5
5
|
} from "./chunk-WWX32ML4.js";
|
|
6
6
|
import {
|
|
7
7
|
CLIENT_HEADER,
|
|
8
|
-
httpRequest
|
|
8
|
+
httpRequest
|
|
9
|
+
} from "./chunk-GXYNLMUQ.js";
|
|
10
|
+
import {
|
|
9
11
|
trimSlash
|
|
10
|
-
} from "./chunk-
|
|
12
|
+
} from "./chunk-XBJ3VLWX.js";
|
|
11
13
|
import {
|
|
12
14
|
CliError,
|
|
13
15
|
external_exports
|
|
14
|
-
} from "./chunk-
|
|
16
|
+
} from "./chunk-J6CVKC4M.js";
|
|
15
17
|
|
|
16
18
|
// src/lib/agent-api.ts
|
|
17
19
|
var FRESH_WITHIN_RE = /^P(\d+)[DWMY]$/;
|
|
18
20
|
var CANONICAL_KEY_RE = /^[a-z][a-z0-9_]{0,31}$/;
|
|
21
|
+
var MAX_LIMIT = 10;
|
|
19
22
|
function buildSearchRequest(input) {
|
|
20
23
|
const question = input.question.trim();
|
|
21
24
|
if (question.length === 0 || question.length > 512) {
|
|
@@ -37,9 +40,9 @@ function buildSearchRequest(input) {
|
|
|
37
40
|
});
|
|
38
41
|
}
|
|
39
42
|
const limit = input.limit ?? 5;
|
|
40
|
-
if (!Number.isInteger(limit) || limit < 1 || limit >
|
|
43
|
+
if (!Number.isInteger(limit) || limit < 1 || limit > MAX_LIMIT) {
|
|
41
44
|
throw new CliError("USAGE", `Invalid --limit: ${JSON.stringify(input.limit)}`, {
|
|
42
|
-
fix:
|
|
45
|
+
fix: `Pass an integer between 1 and ${MAX_LIMIT}.`
|
|
43
46
|
});
|
|
44
47
|
}
|
|
45
48
|
if (input.appliesTo !== void 0) {
|
|
@@ -72,7 +75,7 @@ function buildSearchRequest(input) {
|
|
|
72
75
|
}
|
|
73
76
|
}
|
|
74
77
|
return {
|
|
75
|
-
schemaVersion:
|
|
78
|
+
schemaVersion: 2,
|
|
76
79
|
question,
|
|
77
80
|
...input.freshWithin !== void 0 ? { freshWithin: input.freshWithin } : {},
|
|
78
81
|
...input.maxPrice !== void 0 ? { maxPrice: input.maxPrice } : {},
|
|
@@ -83,17 +86,12 @@ function buildSearchRequest(input) {
|
|
|
83
86
|
var searchCandidateSchema = external_exports.object({
|
|
84
87
|
resourceId: external_exports.string().regex(UUID_RE, "resourceId must be a uuid"),
|
|
85
88
|
url: external_exports.string(),
|
|
89
|
+
slug: external_exports.string(),
|
|
86
90
|
title: external_exports.string(),
|
|
87
91
|
artifactType: external_exports.string(),
|
|
88
92
|
price: external_exports.string().regex(ATOMIC_RE, "price must be an atomic integer string"),
|
|
89
93
|
asOf: external_exports.string().nullable(),
|
|
90
94
|
validUntil: external_exports.string().nullable(),
|
|
91
|
-
temporalMode: external_exports.string(),
|
|
92
|
-
appliesTo: external_exports.record(external_exports.string(), external_exports.array(external_exports.string())),
|
|
93
|
-
questionsAnswered: external_exports.array(external_exports.string()),
|
|
94
|
-
tasksSupported: external_exports.array(external_exports.string()),
|
|
95
|
-
scope: external_exports.string().nullable(),
|
|
96
|
-
exclusions: external_exports.string().nullable(),
|
|
97
95
|
matchReasons: external_exports.array(external_exports.string()),
|
|
98
96
|
estimatedTokens: external_exports.number(),
|
|
99
97
|
creator: external_exports.object({ handle: external_exports.string() }).passthrough()
|
|
@@ -107,11 +105,18 @@ var searchBrowseSchema = external_exports.object({
|
|
|
107
105
|
creator: external_exports.object({ handle: external_exports.string() }).passthrough()
|
|
108
106
|
}).passthrough();
|
|
109
107
|
var searchResponseSchema = external_exports.object({
|
|
110
|
-
schemaVersion: external_exports.literal(
|
|
108
|
+
schemaVersion: external_exports.literal(2),
|
|
111
109
|
searchId: external_exports.string().regex(UUID_RE, "searchId must be a uuid"),
|
|
112
110
|
decision: external_exports.enum(["CANDIDATES", "MISS"]),
|
|
113
111
|
calibration: external_exports.string(),
|
|
114
112
|
candidates: external_exports.array(searchCandidateSchema).optional(),
|
|
113
|
+
// Set only when the server's size backstop dropped trailing candidates the
|
|
114
|
+
// requested limit had room for; omitted entirely otherwise. There is no cursor,
|
|
115
|
+
// so a retry at a SMALLER limit returns strictly fewer rows; the ceiling scales
|
|
116
|
+
// with the candidates returned, so a LARGER limit (up to MAX_LIMIT) is what
|
|
117
|
+
// recovers the tail, and at MAX_LIMIT the tail is unrecoverable and narrowing the
|
|
118
|
+
// question is the remedy. `runSearch` picks the half that applies.
|
|
119
|
+
truncated: external_exports.literal(true).optional(),
|
|
115
120
|
// Omitted entirely by the server when empty, and only ever present on a MISS.
|
|
116
121
|
// Not enforced here (a stricter schema would reject an otherwise-usable
|
|
117
122
|
// response); truncateResponse drops it on a CANDIDATES decision instead.
|
|
@@ -120,7 +125,7 @@ var searchResponseSchema = external_exports.object({
|
|
|
120
125
|
function apiFailure(url, result) {
|
|
121
126
|
const code = result.kind === "network" || result.kind === "timeout" ? "NETWORK_ERROR" : "API_UNREACHABLE";
|
|
122
127
|
return new CliError(code, `${url}: ${result.message}`, {
|
|
123
|
-
fix: "Check
|
|
128
|
+
fix: "Check your network and the configured base URL (`tenjin config get baseUrl`), then retry."
|
|
124
129
|
});
|
|
125
130
|
}
|
|
126
131
|
function rateLimitError(url, header) {
|
|
@@ -161,6 +166,11 @@ async function postSearch(body, opts) {
|
|
|
161
166
|
if (!res.ok) throw apiFailure(url, res);
|
|
162
167
|
if (res.status === 429) throw rateLimitError(url, (n) => res.header(n));
|
|
163
168
|
if (res.status !== 200) {
|
|
169
|
+
if (res.status === 400 && rejectedSchemaVersion(res.json)) {
|
|
170
|
+
throw outdatedServerError("The server rejected schemaVersion 2: it predates search v2.", {
|
|
171
|
+
details: res.json
|
|
172
|
+
});
|
|
173
|
+
}
|
|
164
174
|
throw new CliError(
|
|
165
175
|
"API_UNREACHABLE",
|
|
166
176
|
serverErrorMessage(res.json) ?? `Search failed (${res.status})`,
|
|
@@ -172,6 +182,13 @@ async function postSearch(body, opts) {
|
|
|
172
182
|
}
|
|
173
183
|
const parsed = searchResponseSchema.safeParse(res.json);
|
|
174
184
|
if (!parsed.success) {
|
|
185
|
+
const served = serverSchemaVersion(res.json);
|
|
186
|
+
if (served !== void 0 && served !== 2) {
|
|
187
|
+
throw outdatedServerError(
|
|
188
|
+
`Search response is schemaVersion ${served}; this CLI requires 2 (search v2).`,
|
|
189
|
+
{ details: parsed.error.issues }
|
|
190
|
+
);
|
|
191
|
+
}
|
|
175
192
|
throw new CliError("CONTRACT_MISMATCH", "Search response did not match the expected contract", {
|
|
176
193
|
fix: "Update tenjin-cli; the server contract may have changed.",
|
|
177
194
|
details: parsed.error.issues
|
|
@@ -179,17 +196,26 @@ async function postSearch(body, opts) {
|
|
|
179
196
|
}
|
|
180
197
|
return truncateResponse(parsed.data);
|
|
181
198
|
}
|
|
199
|
+
function outdatedServerError(message, opts) {
|
|
200
|
+
return new CliError("CONTRACT_MISMATCH", message, {
|
|
201
|
+
fix: "The server predates search v2. Point the configured base URL (`tenjin config set baseUrl`) at an updated deployment, or install an older tenjin-cli.",
|
|
202
|
+
details: opts.details
|
|
203
|
+
});
|
|
204
|
+
}
|
|
205
|
+
function rejectedSchemaVersion(json) {
|
|
206
|
+
const record = (v) => typeof v === "object" && v !== null ? v : void 0;
|
|
207
|
+
const fieldErrors = record(record(record(json)?.error)?.details)?.fieldErrors;
|
|
208
|
+
return Array.isArray(record(fieldErrors)?.schemaVersion);
|
|
209
|
+
}
|
|
210
|
+
function serverSchemaVersion(json) {
|
|
211
|
+
if (typeof json !== "object" || json === null) return void 0;
|
|
212
|
+
const v = json.schemaVersion;
|
|
213
|
+
return typeof v === "number" ? v : void 0;
|
|
214
|
+
}
|
|
182
215
|
var CAND_BOUNDS = {
|
|
183
216
|
title: 200,
|
|
184
|
-
scope: 240,
|
|
185
|
-
exclusions: 240,
|
|
186
|
-
listItems: 4,
|
|
187
|
-
listItemChars: 160,
|
|
188
217
|
matchReasons: 3,
|
|
189
|
-
matchReasonChars: 80
|
|
190
|
-
appliesToKeys: 6,
|
|
191
|
-
appliesToValues: 5,
|
|
192
|
-
appliesToValueChars: 80
|
|
218
|
+
matchReasonChars: 80
|
|
193
219
|
};
|
|
194
220
|
var cap = (s, n) => s.length > n ? s.slice(0, n) : s;
|
|
195
221
|
function truncateResponse(res) {
|
|
@@ -212,28 +238,10 @@ function truncateResponse(res) {
|
|
|
212
238
|
}
|
|
213
239
|
var BROWSE_MAX = 3;
|
|
214
240
|
function truncateCandidate(c) {
|
|
215
|
-
const capList = (list, items, chars) => list.slice(0, items).map((s) => cap(s, chars));
|
|
216
|
-
const appliesTo = {};
|
|
217
|
-
for (const key of Object.keys(c.appliesTo).slice(0, CAND_BOUNDS.appliesToKeys)) {
|
|
218
|
-
appliesTo[cap(key, CAND_BOUNDS.appliesToValueChars)] = capList(
|
|
219
|
-
c.appliesTo[key] ?? [],
|
|
220
|
-
CAND_BOUNDS.appliesToValues,
|
|
221
|
-
CAND_BOUNDS.appliesToValueChars
|
|
222
|
-
);
|
|
223
|
-
}
|
|
224
241
|
return {
|
|
225
242
|
...c,
|
|
226
243
|
title: cap(c.title, CAND_BOUNDS.title),
|
|
227
|
-
|
|
228
|
-
exclusions: c.exclusions === null ? null : cap(c.exclusions, CAND_BOUNDS.exclusions),
|
|
229
|
-
questionsAnswered: capList(
|
|
230
|
-
c.questionsAnswered,
|
|
231
|
-
CAND_BOUNDS.listItems,
|
|
232
|
-
CAND_BOUNDS.listItemChars
|
|
233
|
-
),
|
|
234
|
-
tasksSupported: capList(c.tasksSupported, CAND_BOUNDS.listItems, CAND_BOUNDS.listItemChars),
|
|
235
|
-
matchReasons: capList(c.matchReasons, CAND_BOUNDS.matchReasons, CAND_BOUNDS.matchReasonChars),
|
|
236
|
-
appliesTo
|
|
244
|
+
matchReasons: c.matchReasons.slice(0, CAND_BOUNDS.matchReasons).map((r) => cap(r, CAND_BOUNDS.matchReasonChars))
|
|
237
245
|
};
|
|
238
246
|
}
|
|
239
247
|
var OUTCOME_STATUSES = [
|
|
@@ -304,10 +312,11 @@ async function postOutcomes(searchId, items, opts) {
|
|
|
304
312
|
}
|
|
305
313
|
|
|
306
314
|
export {
|
|
315
|
+
MAX_LIMIT,
|
|
307
316
|
buildSearchRequest,
|
|
308
317
|
rateLimitError,
|
|
309
318
|
postSearch,
|
|
310
319
|
buildOutcomeItem,
|
|
311
320
|
postOutcomes
|
|
312
321
|
};
|
|
313
|
-
//# sourceMappingURL=chunk-
|
|
322
|
+
//# sourceMappingURL=chunk-2L73UI6T.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/lib/agent-api.ts"],"sourcesContent":["import { z } from 'zod';\nimport { CliError } from './errors';\nimport { httpRequest, type HttpResult } from './http';\nimport { CLIENT_HEADER } from './client-meta';\nimport { ATOMIC_RE, UUID_RE } from './ids';\nimport { trimSlash } from './url';\n\n/**\n * The search + outcome HTTP contract (A2, tenjin#370). Request building and\n * response validation live here; the wire shape is validated defensively, an\n * unknown `schemaVersion` degrades to a parse refusal rather than a guess, and\n * unrecognized candidate fields are ignored (forward-compatible), per spec 10.\n *\n * These endpoints are anonymous: no wallet, no SIWX. The only header of note is\n * `X-Tenjin-Client`, which attributes a later purchase back to the search flow.\n */\n\nconst FRESH_WITHIN_RE = /^P(\\d+)[DWMY]$/;\nconst CANONICAL_KEY_RE = /^[a-z][a-z0-9_]{0,31}$/;\n\n/** The server's `limit` ceiling. Exported because the truncation advice in\n * `search` has to name it: past search v2 the response budget scales with the\n * candidates returned, so a truncated page is recovered by asking for MORE, and\n * this is the value to ask for. One definition, so the cap the CLI enforces and\n * the number it tells the operator to retry with cannot drift apart. */\nexport const MAX_LIMIT = 10;\n\n/** Client-side search request (mirrors the server lookupRequestSchema bounds\n * so a malformed flag fails locally as USAGE, before a round trip). */\nexport interface SearchInput {\n question: string;\n freshWithin?: string;\n maxPrice?: string;\n appliesTo?: Record<string, string[]>;\n limit?: number;\n}\n\nexport interface SearchRequestBody {\n schemaVersion: 2;\n question: string;\n freshWithin?: string;\n maxPrice?: string;\n appliesTo?: Record<string, string[]>;\n limit: number;\n}\n\nexport function buildSearchRequest(input: SearchInput): SearchRequestBody {\n const question = input.question.trim();\n if (question.length === 0 || question.length > 512) {\n throw new CliError('USAGE', 'question must be 1 to 512 characters', {\n fix: 'Pass a non-empty question under 512 characters.',\n });\n }\n if (input.freshWithin !== undefined) {\n // The server rejects ANY zero-valued duration (P0D, P0W, P00M, ...), so a\n // zero window fails here as USAGE instead of a remote 400.\n const digits = FRESH_WITHIN_RE.exec(input.freshWithin)?.[1];\n if (digits === undefined || Number(digits) === 0) {\n throw new CliError('USAGE', `Invalid --fresh-within: ${JSON.stringify(input.freshWithin)}`, {\n fix: 'Use a nonzero ISO-like window P<n>[DWMY], e.g. P30D, P2W, P1Y.',\n });\n }\n }\n if (input.maxPrice !== undefined && !ATOMIC_RE.test(input.maxPrice)) {\n throw new CliError('USAGE', `Invalid --max-price: ${JSON.stringify(input.maxPrice)}`, {\n fix: 'Pass an atomic USDC integer, e.g. 100000 for $0.10.',\n });\n }\n const limit = input.limit ?? 5;\n if (!Number.isInteger(limit) || limit < 1 || limit > MAX_LIMIT) {\n throw new CliError('USAGE', `Invalid --limit: ${JSON.stringify(input.limit)}`, {\n fix: `Pass an integer between 1 and ${MAX_LIMIT}.`,\n });\n }\n if (input.appliesTo !== undefined) {\n // Mirror the server's strictObject bounds (<=8 keys, <=20 values/key,\n // 1..120 chars/value) so a bad filter fails locally, never as a remote 400.\n const keys = Object.keys(input.appliesTo);\n if (keys.length > 8) {\n throw new CliError('USAGE', 'Too many --applies-to keys (max 8).');\n }\n for (const [key, values] of Object.entries(input.appliesTo)) {\n if (!CANONICAL_KEY_RE.test(key)) {\n throw new CliError('USAGE', `Invalid appliesTo key: ${JSON.stringify(key)}`, {\n fix: 'Keys must be canonical lowercase identifiers, e.g. products=Vercel.',\n });\n }\n if (values.length === 0) {\n throw new CliError('USAGE', `appliesTo key ${JSON.stringify(key)} has no values`, {\n fix: 'Give each --applies-to key at least one value.',\n });\n }\n if (values.length > 20) {\n throw new CliError('USAGE', `Too many --applies-to values for ${key} (max 20).`);\n }\n for (const value of values) {\n if (value.length === 0 || value.length > 120) {\n throw new CliError(\n 'USAGE',\n `Invalid --applies-to value for ${key}: must be 1 to 120 characters.`,\n );\n }\n }\n }\n }\n return {\n schemaVersion: 2,\n question,\n ...(input.freshWithin !== undefined ? { freshWithin: input.freshWithin } : {}),\n ...(input.maxPrice !== undefined ? { maxPrice: input.maxPrice } : {}),\n ...(input.appliesTo !== undefined ? { appliesTo: input.appliesTo } : {}),\n limit,\n };\n}\n\n// Response schemas. `.passthrough()` on the candidate keeps unknown future fields\n// instead of stripping them (forward-compatible), while still requiring the\n// contract fields this CLI reads. `decision` is uppercase on the wire.\n//\n// A candidate is a LEAN hit (search v2): identity, price, freshness and why it\n// matched, and nothing more. The full answer card is one free unpaid GET of `url`\n// away, which is what `tenjin inspect` does, so breadth here costs no depth there.\nexport const searchCandidateSchema = z\n .object({\n resourceId: z.string().regex(UUID_RE, 'resourceId must be a uuid'),\n url: z.string(),\n slug: z.string(),\n title: z.string(),\n artifactType: z.string(),\n price: z.string().regex(ATOMIC_RE, 'price must be an atomic integer string'),\n asOf: z.string().nullable(),\n validUntil: z.string().nullable(),\n matchReasons: z.array(z.string()),\n estimatedTokens: z.number(),\n creator: z.object({ handle: z.string() }).passthrough(),\n })\n .passthrough();\n\nexport type SearchCandidate = z.infer<typeof searchCandidateSchema>;\n\n/** Per-field caps for a browse pointer's free-form strings. `url` gets its own,\n * looser bound so a legitimate read URL is never mangled while an invented one\n * still cannot run away. Declared above the schema because the schema enforces\n * the `url` bound at parse time (see below). */\nconst BROWSE_BOUNDS = { title: 200, url: 512, handle: 64 } as const;\n\n// A browse pointer, carried ONLY on a MISS (tenjin#460): a piece from the broad\n// discoverable corpus with deliberately NO matchReasons, NO estimatedTokens and\n// no confidence field. It is a \"you might browse this\" hint, never a scored\n// answer candidate, so it is kept strictly out of `candidates` and never\n// recorded in the local search store.\n//\n// That store exclusion makes `inspect`/`buy`/`outcome` unreachable BY\n// `resourceId` (resolveResourceRef's uuid arm needs a store hit and fails with\n// RESOURCE_NOT_FOUND), but NOT by url: resolveResourceRef's URL arm is gated on\n// origin alone and never consults the store, so `tenjin buy <browse url>` does\n// pay. That is by design here, since the url is the payable read endpoint and\n// the contract re-emits it verbatim, but it is a real spend path, so the human\n// hint line carries the price and every spend gate still applies. Do not\n// restate the old \"never reachable by inspect/buy/outcome\" claim: it was false.\n//\n// A malformed pointer fails the WHOLE response into CONTRACT_MISMATCH rather\n// than being dropped. Deliberate: this client is fail-closed on every other\n// contract deviation, and silently swallowing a bad tail would hide server\n// drift that contract.test.ts exists to catch. Pinned in agent-api.test.ts.\n//\n// The `url` bound is enforced HERE rather than by truncation in the projection\n// below, and that asymmetry with `title`/`handle` is deliberate. Those two are\n// display strings: clipping one degrades gracefully and the human still reads\n// something true. `url` is an actionable payable pointer, and a clipped url is\n// not a shorter url, it is a DIFFERENT and broken one that still looks payable\n// in `--json`. Refusing is also the only ordering-independent answer: capping\n// first would hand the origin assertion in `runSearch` a string the server never\n// sent. 512 is far above any real read endpoint, so exceeding it is server drift.\nexport const searchBrowseSchema = z\n .object({\n resourceId: z.string().regex(UUID_RE, 'resourceId must be a uuid'),\n url: z.string().max(BROWSE_BOUNDS.url, `url must be at most ${BROWSE_BOUNDS.url} characters`),\n title: z.string(),\n price: z.string().regex(ATOMIC_RE, 'price must be an atomic integer string'),\n creator: z.object({ handle: z.string() }).passthrough(),\n })\n .passthrough();\n\nexport type SearchBrowse = z.infer<typeof searchBrowseSchema>;\n\nexport const searchResponseSchema = z.object({\n schemaVersion: z.literal(2),\n searchId: z.string().regex(UUID_RE, 'searchId must be a uuid'),\n decision: z.enum(['CANDIDATES', 'MISS']),\n calibration: z.string(),\n candidates: z.array(searchCandidateSchema).optional(),\n // Set only when the server's size backstop dropped trailing candidates the\n // requested limit had room for; omitted entirely otherwise. There is no cursor,\n // so a retry at a SMALLER limit returns strictly fewer rows; the ceiling scales\n // with the candidates returned, so a LARGER limit (up to MAX_LIMIT) is what\n // recovers the tail, and at MAX_LIMIT the tail is unrecoverable and narrowing the\n // question is the remedy. `runSearch` picks the half that applies.\n truncated: z.literal(true).optional(),\n // Omitted entirely by the server when empty, and only ever present on a MISS.\n // Not enforced here (a stricter schema would reject an otherwise-usable\n // response); truncateResponse drops it on a CANDIDATES decision instead.\n browse: z.array(searchBrowseSchema).optional(),\n});\n\nexport type SearchResponse = z.infer<typeof searchResponseSchema>;\n\nexport interface AgentApiOptions {\n baseUrl: string;\n timeoutMs: number;\n fetchImpl?: typeof fetch;\n /** Spec 09 §3 evaluation-cohort opt-in: sends X-Tenjin-Eval-Cohort: 1. */\n evalCohort?: boolean;\n}\n\n/** Turn a non-2xx / transport HttpResult into the CLI error contract. */\nfunction apiFailure(url: string, result: Exclude<HttpResult, { ok: true }>): CliError {\n const code =\n result.kind === 'network' || result.kind === 'timeout' ? 'NETWORK_ERROR' : 'API_UNREACHABLE';\n return new CliError(code, `${url}: ${result.message}`, {\n fix: 'Check your network and the configured base URL (`tenjin config get baseUrl`), then retry.',\n });\n}\n\n/** 429 with Retry-After: a recoverable pause, not an outage; agents branch on it. */\nexport function rateLimitError(\n url: string,\n header: (name: string) => string | undefined,\n): CliError {\n const retryAfter = header('retry-after');\n const seconds = retryAfter !== undefined ? Number(retryAfter) : undefined;\n return new CliError('RATE_LIMITED', `${url}: rate limited by the server.`, {\n fix:\n seconds !== undefined && Number.isFinite(seconds)\n ? `Retry after ${seconds}s.`\n : 'Back off and retry shortly.',\n details: {\n ...(seconds !== undefined && Number.isFinite(seconds) ? { retryAfterSeconds: seconds } : {}),\n },\n });\n}\n\nfunction serverErrorMessage(json: unknown): string | undefined {\n if (typeof json === 'object' && json !== null) {\n const rec = json as Record<string, unknown>;\n const err = rec.error;\n if (typeof err === 'string') return err;\n if (typeof err === 'object' && err !== null) {\n const m = (err as Record<string, unknown>).message;\n if (typeof m === 'string') return m;\n }\n if (typeof rec.message === 'string') return rec.message;\n }\n return undefined;\n}\n\nexport async function postSearch(\n body: SearchRequestBody,\n opts: AgentApiOptions,\n): Promise<SearchResponse> {\n const url = `${trimSlash(opts.baseUrl)}/api/agent/search`;\n const res = await httpRequest(url, {\n method: 'POST',\n timeoutMs: opts.timeoutMs,\n headers: {\n 'x-tenjin-client': CLIENT_HEADER,\n ...(opts.evalCohort === true ? { 'x-tenjin-eval-cohort': '1' } : {}),\n },\n jsonBody: body,\n fetchImpl: opts.fetchImpl,\n });\n if (!res.ok) throw apiFailure(url, res);\n if (res.status === 429) throw rateLimitError(url, (n) => res.header(n));\n if (res.status !== 200) {\n // The REQUEST gate is where a pre-v2 server actually refuses us, and it is\n // the arm that fires in practice. Old tenjin declares `schemaVersion:\n // z.literal(1)` inside a strictObject, so a v2 request never reaches the\n // handler: it comes back 400 \"Invalid request body\" with the zod flatten in\n // `error.details`, and the response check further down can never see it.\n // Without this the operator is told to retry a request that cannot succeed.\n if (res.status === 400 && rejectedSchemaVersion(res.json)) {\n throw outdatedServerError('The server rejected schemaVersion 2: it predates search v2.', {\n details: res.json,\n });\n }\n throw new CliError(\n 'API_UNREACHABLE',\n serverErrorMessage(res.json) ?? `Search failed (${res.status})`,\n {\n fix: 'Retry; if it persists the search endpoint may be unavailable.',\n details: res.json,\n },\n );\n }\n const parsed = searchResponseSchema.safeParse(res.json);\n if (!parsed.success) {\n // The other way a stale server surfaces: it answered 200 with a v1 body.\n // Unreachable against today's old tenjin (the request gate above refuses\n // first), but correct for anything that accepts the request and replies v1.\n const served = serverSchemaVersion(res.json);\n if (served !== undefined && served !== 2) {\n throw outdatedServerError(\n `Search response is schemaVersion ${served}; this CLI requires 2 (search v2).`,\n { details: parsed.error.issues },\n );\n }\n throw new CliError('CONTRACT_MISMATCH', 'Search response did not match the expected contract', {\n fix: 'Update tenjin-cli; the server contract may have changed.',\n details: parsed.error.issues,\n });\n }\n return truncateResponse(parsed.data);\n}\n\n/** One wording for both ways a pre-v2 server refuses this CLI, so the request-gate\n * arm and the response arm can never drift apart. */\nfunction outdatedServerError(message: string, opts: { details: unknown }): CliError {\n return new CliError('CONTRACT_MISMATCH', message, {\n fix: 'The server predates search v2. Point the configured base URL (`tenjin config set baseUrl`) at an updated deployment, or install an older tenjin-cli.',\n details: opts.details,\n });\n}\n\n/** True when a 400 body is the old server's request-gate refusal of our\n * `schemaVersion`: an ApiError envelope whose zod `flatten()` details carry a\n * `schemaVersion` fieldError. Keyed on the field, never the message text. */\nfunction rejectedSchemaVersion(json: unknown): boolean {\n const record = (v: unknown): Record<string, unknown> | undefined =>\n typeof v === 'object' && v !== null ? (v as Record<string, unknown>) : undefined;\n const fieldErrors = record(record(record(json)?.error)?.details)?.fieldErrors;\n return Array.isArray(record(fieldErrors)?.schemaVersion);\n}\n\n/** The `schemaVersion` an unparsed body claims, when it claims a number at all. */\nfunction serverSchemaVersion(json: unknown): number | undefined {\n if (typeof json !== 'object' || json === null) return undefined;\n const v = (json as { schemaVersion?: unknown }).schemaVersion;\n return typeof v === 'number' ? v : undefined;\n}\n\n/**\n * The server bounds every free-form candidate string (spec 09); re-apply the same\n * caps defensively so a misbehaving server cannot blow up an agent transcript\n * through the CLI (spec 10 response-size discipline).\n *\n * `slug` is deliberately absent: it is an identifier, not display text, so\n * clipping it would not shorten it but change it into a slug that resolves to\n * nothing while still looking usable in `--json`. The server tolerates an\n * uncapped slug for the same reason (that is the one case its `truncated` flag\n * exists for), so capping here would fail on a response the server calls valid.\n */\nconst CAND_BOUNDS = {\n title: 200,\n matchReasons: 3,\n matchReasonChars: 80,\n} as const;\n\nconst cap = (s: string, n: number): string => (s.length > n ? s.slice(0, n) : s);\n\nfunction truncateResponse(res: SearchResponse): SearchResponse {\n const out: SearchResponse = { ...res };\n if (res.candidates !== undefined) out.candidates = res.candidates.map(truncateCandidate);\n // Browse pointers ride the same defensive discipline, and then some. The\n // schema is `.passthrough()` so a server-invented key would otherwise survive\n // at unbounded length into `--json` and MCP structuredContent; we rebuild each\n // pointer explicitly from the five contract fields instead of spreading, which\n // drops unknown keys and is what makes the contract.test.ts \"no score-like\n // field\" pin hold at runtime and not just against the fixture. Count is capped\n // at the server's BROWSE_MAX, and every free-form string (title, url, handle)\n // at its own bound.\n //\n // `browse` is MISS-only by contract; drop it outright on a CANDIDATES decision\n // rather than trust the server, since humanLines renders no hint line there and\n // it would otherwise be an unrendered channel of server text and payable urls.\n if (res.browse !== undefined && res.decision === 'MISS') {\n out.browse = res.browse.slice(0, BROWSE_MAX).map((b) => ({\n resourceId: b.resourceId,\n // Not capped: the schema already refused anything over BROWSE_BOUNDS.url,\n // so this is the url the server sent, verbatim and payable.\n url: b.url,\n title: cap(b.title, BROWSE_BOUNDS.title),\n price: b.price,\n creator: { handle: cap(b.creator.handle, BROWSE_BOUNDS.handle) },\n }));\n } else {\n delete out.browse;\n }\n return out;\n}\n\n/** Mirrors the server's BROWSE_MAX (lib/search-browse.ts): a MISS carries at\n * most three browse pointers. */\nconst BROWSE_MAX = 3;\n\nfunction truncateCandidate(c: SearchCandidate): SearchCandidate {\n return {\n ...c,\n title: cap(c.title, CAND_BOUNDS.title),\n matchReasons: c.matchReasons\n .slice(0, CAND_BOUNDS.matchReasons)\n .map((r) => cap(r, CAND_BOUNDS.matchReasonChars)),\n };\n}\n\nconst OUTCOME_STATUSES = [\n 'used',\n 'partially_used',\n 'rejected',\n 'regenerated',\n 'purchase_declined',\n] as const;\nexport type OutcomeStatus = (typeof OUTCOME_STATUSES)[number];\nexport const OUTCOME_STATUS_VALUES: readonly string[] = OUTCOME_STATUSES;\n\nconst CONTENT_HASH_RE = /^sha256:[0-9a-f]{64}$/;\n\nexport interface OutcomeInput {\n status: string;\n resourceId?: string;\n contentHash?: string;\n}\n\nexport interface OutcomeBodyItem {\n status: OutcomeStatus;\n resourceId?: string;\n contentHash?: string;\n}\n\nexport function buildOutcomeItem(input: OutcomeInput): OutcomeBodyItem {\n if (!OUTCOME_STATUS_VALUES.includes(input.status)) {\n throw new CliError('USAGE', `Invalid outcome status: ${JSON.stringify(input.status)}`, {\n fix: `Use one of: ${OUTCOME_STATUSES.join(', ')}.`,\n });\n }\n if (input.resourceId !== undefined && !UUID_RE.test(input.resourceId)) {\n throw new CliError('USAGE', `Invalid --resource id: ${JSON.stringify(input.resourceId)}`, {\n fix: 'Pass the resourceId (a uuid) from a search candidate.',\n });\n }\n if (input.contentHash !== undefined && !CONTENT_HASH_RE.test(input.contentHash)) {\n throw new CliError('USAGE', `Invalid content hash: ${JSON.stringify(input.contentHash)}`, {\n fix: 'A content hash is \"sha256:<64 hex>\".',\n });\n }\n return {\n status: input.status as OutcomeStatus,\n ...(input.resourceId !== undefined ? { resourceId: input.resourceId } : {}),\n ...(input.contentHash !== undefined ? { contentHash: input.contentHash } : {}),\n };\n}\n\nconst SEARCH_ID_RE = UUID_RE;\n\nexport async function postOutcomes(\n searchId: string,\n items: OutcomeBodyItem[],\n opts: AgentApiOptions,\n): Promise<{ accepted: number }> {\n if (!SEARCH_ID_RE.test(searchId)) {\n throw new CliError('USAGE', `Invalid search id: ${JSON.stringify(searchId)}`, {\n fix: 'Pass the searchId from a prior search (or use --last).',\n });\n }\n if (items.length === 0 || items.length > 10) {\n throw new CliError('USAGE', 'An outcome report carries 1 to 10 items', {\n fix: 'Report between 1 and 10 outcomes per call.',\n });\n }\n const url = `${trimSlash(opts.baseUrl)}/api/agent/searches/${searchId}/outcomes`;\n const res = await httpRequest(url, {\n method: 'POST',\n timeoutMs: opts.timeoutMs,\n headers: { 'x-tenjin-client': CLIENT_HEADER },\n jsonBody: items.length === 1 ? items[0] : items,\n fetchImpl: opts.fetchImpl,\n });\n if (!res.ok) throw apiFailure(url, res);\n if (res.status === 429) throw rateLimitError(url, (n) => res.header(n));\n // 202 is the only success; the body is a uniform { accepted } regardless of\n // whether the searchId existed (no existence oracle, by design).\n if (res.status !== 202) {\n throw new CliError(\n 'API_UNREACHABLE',\n serverErrorMessage(res.json) ?? `Outcome report failed (${res.status})`,\n {\n fix: 'Check the status vocabulary and search id, then retry.',\n details: res.json,\n },\n );\n }\n const accepted =\n typeof res.json === 'object' && res.json !== null && 'accepted' in res.json\n ? Number((res.json as { accepted: unknown }).accepted)\n : items.length;\n return { accepted: Number.isFinite(accepted) ? accepted : items.length };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAiBA,IAAM,kBAAkB;AACxB,IAAM,mBAAmB;AAOlB,IAAM,YAAY;AAqBlB,SAAS,mBAAmB,OAAuC;AACxE,QAAM,WAAW,MAAM,SAAS,KAAK;AACrC,MAAI,SAAS,WAAW,KAAK,SAAS,SAAS,KAAK;AAClD,UAAM,IAAI,SAAS,SAAS,wCAAwC;AAAA,MAClE,KAAK;AAAA,IACP,CAAC;AAAA,EACH;AACA,MAAI,MAAM,gBAAgB,QAAW;AAGnC,UAAM,SAAS,gBAAgB,KAAK,MAAM,WAAW,IAAI,CAAC;AAC1D,QAAI,WAAW,UAAa,OAAO,MAAM,MAAM,GAAG;AAChD,YAAM,IAAI,SAAS,SAAS,2BAA2B,KAAK,UAAU,MAAM,WAAW,CAAC,IAAI;AAAA,QAC1F,KAAK;AAAA,MACP,CAAC;AAAA,IACH;AAAA,EACF;AACA,MAAI,MAAM,aAAa,UAAa,CAAC,UAAU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
|
3
3
|
createCandidate,
|
|
4
4
|
dropCandidate,
|
|
5
5
|
listCandidates
|
|
6
|
-
} from "./chunk-
|
|
6
|
+
} from "./chunk-VZ3AJCO5.js";
|
|
7
7
|
import {
|
|
8
8
|
UUID_RE
|
|
9
9
|
} from "./chunk-WWX32ML4.js";
|
|
10
10
|
import {
|
|
11
11
|
sanitizeForTerminal
|
|
12
|
-
} from "./chunk-
|
|
12
|
+
} from "./chunk-BBUYCDSG.js";
|
|
13
13
|
import {
|
|
14
14
|
pathExists
|
|
15
|
-
} from "./chunk-
|
|
15
|
+
} from "./chunk-DAJ56EUU.js";
|
|
16
16
|
import {
|
|
17
17
|
CliError
|
|
18
|
-
} from "./chunk-
|
|
18
|
+
} from "./chunk-J6CVKC4M.js";
|
|
19
19
|
|
|
20
20
|
// src/commands/candidate.ts
|
|
21
21
|
import { readFile } from "fs/promises";
|
|
@@ -120,4 +120,4 @@ export {
|
|
|
120
120
|
runCandidateList,
|
|
121
121
|
runCandidateDrop
|
|
122
122
|
};
|
|
123
|
-
//# sourceMappingURL=chunk-
|
|
123
|
+
//# sourceMappingURL=chunk-2YX6LTCD.js.map
|
|
@@ -1,30 +1,31 @@
|
|
|
1
1
|
import { createRequire as __tenjinCreateRequire } from 'node:module'; const require = __tenjinCreateRequire(import.meta.url);
|
|
2
2
|
import {
|
|
3
3
|
assertOnBaseOrigin
|
|
4
|
-
} from "./chunk-
|
|
4
|
+
} from "./chunk-CYRYVZPN.js";
|
|
5
|
+
import {
|
|
6
|
+
listCandidates
|
|
7
|
+
} from "./chunk-VZ3AJCO5.js";
|
|
5
8
|
import {
|
|
6
9
|
recordSearch
|
|
7
|
-
} from "./chunk-
|
|
10
|
+
} from "./chunk-OTDI5FXG.js";
|
|
8
11
|
import {
|
|
12
|
+
MAX_LIMIT,
|
|
9
13
|
buildSearchRequest,
|
|
10
14
|
postSearch
|
|
11
|
-
} from "./chunk-
|
|
12
|
-
import {
|
|
13
|
-
listCandidates
|
|
14
|
-
} from "./chunk-DPUMEMGM.js";
|
|
15
|
+
} from "./chunk-2L73UI6T.js";
|
|
15
16
|
import {
|
|
16
17
|
sanitizeForTerminal
|
|
17
|
-
} from "./chunk-
|
|
18
|
+
} from "./chunk-BBUYCDSG.js";
|
|
18
19
|
import {
|
|
19
20
|
resolveContextSettings
|
|
20
|
-
} from "./chunk-
|
|
21
|
+
} from "./chunk-DAJ56EUU.js";
|
|
21
22
|
import {
|
|
22
23
|
formatUsdDisplay,
|
|
23
24
|
parseUsdToAtomic
|
|
24
|
-
} from "./chunk-
|
|
25
|
+
} from "./chunk-UYP7G3GZ.js";
|
|
25
26
|
import {
|
|
26
27
|
CliError
|
|
27
|
-
} from "./chunk-
|
|
28
|
+
} from "./chunk-J6CVKC4M.js";
|
|
28
29
|
|
|
29
30
|
// src/commands/search.ts
|
|
30
31
|
async function runSearch(args, ctx, deps = {}) {
|
|
@@ -83,11 +84,18 @@ async function runSearch(args, ctx, deps = {}) {
|
|
|
83
84
|
const browseHint = browse.length > 0 ? [
|
|
84
85
|
`no match, ${browse.length} piece(s) you could browse: ${browse.map((b) => `${sanitizeForTerminal(b.title)} (${formatUsdDisplay(b.price)} USD)`).join("; ")}`
|
|
85
86
|
] : [];
|
|
86
|
-
const
|
|
87
|
+
const truncatedHint = response.truncated === true ? [
|
|
88
|
+
request.limit < MAX_LIMIT ? `some candidates were dropped for size; retry with --limit ${MAX_LIMIT} (the size ceiling grows with the number of candidates returned)` : `some candidates were dropped for size; at --limit ${MAX_LIMIT} the dropped tail cannot be recovered, so narrow the question`
|
|
89
|
+
] : [];
|
|
90
|
+
const humanLines = response.decision === "MISS" ? [`MISS, no candidates (searchId ${response.searchId})`, ...browseHint, ...truncatedHint] : [
|
|
87
91
|
`${candidates.length} candidate(s) (searchId ${response.searchId}):`,
|
|
92
|
+
// Dollars for the same reason the browse hint uses them: this is the
|
|
93
|
+
// human's cue to size the spend against gates they entered in decimal
|
|
94
|
+
// USD. The machine `candidates` array in --json keeps atomic.
|
|
88
95
|
...candidates.map(
|
|
89
|
-
(c, i) => ` ${i + 1}. ${sanitizeForTerminal(c.title)}, ${c.price}
|
|
90
|
-
)
|
|
96
|
+
(c, i) => ` ${i + 1}. ${sanitizeForTerminal(c.title)}, ${formatUsdDisplay(c.price)} USD, ${sanitizeForTerminal(c.url)}`
|
|
97
|
+
),
|
|
98
|
+
...truncatedHint
|
|
91
99
|
];
|
|
92
100
|
return { data: response, humanLines };
|
|
93
101
|
}
|
|
@@ -135,4 +143,4 @@ function parseAppliesTo(pairs) {
|
|
|
135
143
|
export {
|
|
136
144
|
runSearch
|
|
137
145
|
};
|
|
138
|
-
//# sourceMappingURL=chunk-
|
|
146
|
+
//# sourceMappingURL=chunk-5X4EBGGU.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/commands/search.ts"],"sourcesContent":["import { CliError } from '../lib/errors';\nimport { formatUsdDisplay, parseUsdToAtomic } from '../lib/money';\nimport { resolveContextSettings } from '../lib/settings';\nimport { buildSearchRequest, postSearch, MAX_LIMIT, type SearchInput } from '../lib/agent-api';\nimport { recordSearch } from '../lib/search-store';\nimport { listCandidates } from '../lib/candidate-store';\nimport { assertOnBaseOrigin } from '../lib/resource-ref';\nimport { sanitizeForTerminal } from '../lib/output';\nimport type { CommandContext, CommandResult } from '../context';\n\n/**\n * `tenjin search \"<question>\"`, one POST to /api/agent/search. Prints the compact\n * CANDIDATES/MISS response verbatim (spec 10), and records the searchId +\n * candidates locally so `outcome --last` and `buy <resourceId>` can use them. No\n * wallet, no signing: search is anonymous.\n *\n * Search is the breadth step: a candidate is a lean hit (identity, price,\n * freshness, why it matched), and the full answer card comes from `tenjin inspect`,\n * which is free. So a candidate line stays short on purpose.\n *\n * The response's `searchId` is the outcome-reporting capability for\n * POST /api/agent/searches/<searchId>/outcomes. tenjin#463 renamed both the field\n * (from `lookupId`) and that path, and this client follows the rename end to end,\n * so nothing on the wire or in the local store still speaks `lookupId`.\n */\n\nexport interface SearchArgs {\n question: string;\n /** Decimal USD at the edge (O1); converted to atomic for the wire. */\n maxPrice?: string;\n freshWithin?: string;\n limit?: string;\n /** Raw `k=v` / `k=v1,v2` pairs from repeated --applies-to. */\n appliesTo?: string[];\n}\n\nexport interface SearchDeps {\n fetchImpl?: typeof fetch;\n}\n\nexport async function runSearch(\n args: SearchArgs,\n ctx: CommandContext,\n deps: SearchDeps = {},\n): Promise<CommandResult> {\n const settings = await resolveContextSettings(ctx);\n const input: SearchInput = { question: args.question };\n if (args.maxPrice !== undefined) input.maxPrice = parseUsdToAtomic(args.maxPrice);\n if (args.freshWithin !== undefined) input.freshWithin = args.freshWithin;\n if (args.limit !== undefined) input.limit = parseLimit(args.limit);\n if (args.appliesTo !== undefined && args.appliesTo.length > 0) {\n input.appliesTo = parseAppliesTo(args.appliesTo);\n }\n\n const request = buildSearchRequest(input);\n const response = await postSearch(request, {\n baseUrl: settings.baseUrl,\n timeoutMs: ctx.flags.timeout,\n evalCohort: settings.evalCohort,\n ...(deps.fetchImpl !== undefined ? { fetchImpl: deps.fetchImpl } : {}),\n });\n\n const candidates = response.candidates ?? [];\n // Ingest trust boundary: a candidate url that points off the configured origin\n // would later route a wallet-signed SIWX header and payment to that host via\n // `buy <resourceId>`. Refuse the whole response as a contract violation.\n for (const c of candidates) {\n try {\n assertOnBaseOrigin(c.url, settings.baseUrl, 'search candidate URL');\n } catch (err) {\n throw new CliError(\n 'CONTRACT_MISMATCH',\n `Search candidate ${c.resourceId} points off the configured base URL.`,\n { cause: err },\n );\n }\n }\n // Browse pointers are never buyable through `buy <resourceId>` (they are not\n // recorded), but their urls are still emitted into the agent's transcript, so\n // they get the same origin check rather than a weaker one.\n for (const b of response.browse ?? []) {\n try {\n assertOnBaseOrigin(b.url, settings.baseUrl, 'browse pointer URL');\n } catch (err) {\n throw new CliError(\n 'CONTRACT_MISMATCH',\n `Browse pointer ${b.resourceId} points off the configured base URL.`,\n { cause: err },\n );\n }\n }\n await recordSearch(ctx.dataDir, {\n searchId: response.searchId,\n at: new Date().toISOString(),\n question: request.question,\n decision: response.decision,\n candidates: candidates.map((c) => ({\n resourceId: c.resourceId,\n url: c.url,\n title: c.title,\n price: c.price,\n })),\n });\n\n // A parked-candidate nudge on stderr (not in the machine JSON), MISS only: a\n // MISS is the moment to publish the answer you are about to derive, and stale\n // drafts should not rot unseen. A HIT is not a publish moment, and hot search\n // paths should not get advisory noise every call. One line, only when parked.\n if (response.decision === 'MISS') await emitCandidateNudge(ctx);\n\n // A MISS may carry up to 3 browse pointers from the broad corpus. They are\n // pointers, NOT candidates: rendered as ONE hint line with no scores and no\n // per-item detail, so a MISS still reads as a MISS and an agent is never\n // nudged to treat a browse pointer as an answer. The machine JSON keeps the\n // full `browse` array; this line is only the human tail.\n //\n // The price rides this line because a browse url IS payable: it is the read\n // endpoint that answers a 402, and `buy <url>` resolves the URL arm by origin\n // without consulting the search store, so a browse pointer can be bought even\n // though `buy <resourceId>` can never reach one. All spend gates (price cap,\n // session budget, allowlist, confirm) still run; showing the price keeps the\n // only human-visible surface from being a blind spend.\n //\n // It renders in DOLLARS, not atomic units, because the whole point of the line\n // is that a human can size the spend against the gates they set, and every gate\n // is entered in decimal USD (`--max-price 0.10`, the `maxAutoSpend` config).\n // `formatUsdDisplay` is the canonical human-copy form (always two decimals, so\n // a dime reads \"0.10\" and not \"0.1\"); the machine `browse` array in --json still\n // carries the exact atomic string, per the money-units contract in the README.\n const browse = response.browse ?? [];\n const browseHint =\n browse.length > 0\n ? [\n `no match, ${browse.length} piece(s) you could browse: ${browse\n .map((b) => `${sanitizeForTerminal(b.title)} (${formatUsdDisplay(b.price)} USD)`)\n .join('; ')}`,\n ]\n : [];\n\n // `truncated` means the server's size backstop dropped candidates, either a\n // trailing few the limit had room for or a single oversized one. The response\n // ceiling GROWS with the number of candidates returned (tenjin#501), so the\n // remedy is counter-intuitive and worth stating outright: a larger --limit\n // recovers the tail, a smaller one returns strictly fewer. Only at the maximum\n // is the tail unrecoverable and narrowing the question the answer.\n //\n // The CLI knows the limit it sent, so it names the next step instead of\n // restating the rule and leaving the reader to work out which half applies.\n // The flag stays in the machine envelope (--json) untouched, where it is\n // omitted rather than false when it did not fire.\n //\n // Rendering it on a MISS too is DEFENSIVE, not wire behavior: the server only\n // ever sets the flag alongside candidates it dropped. Handling both keeps the\n // flag from going unrendered if that ever changes.\n const truncatedHint =\n response.truncated === true\n ? [\n request.limit < MAX_LIMIT\n ? `some candidates were dropped for size; retry with --limit ${MAX_LIMIT} (the size ceiling grows with the number of candidates returned)`\n : `some candidates were dropped for size; at --limit ${MAX_LIMIT} the dropped tail cannot be recovered, so narrow the question`,\n ]\n : [];\n\n const humanLines =\n response.decision === 'MISS'\n ? [`MISS, no candidates (searchId ${response.searchId})`, ...browseHint, ...truncatedHint]\n : [\n `${candidates.length} candidate(s) (searchId ${response.searchId}):`,\n // Dollars for the same reason the browse hint uses them: this is the\n // human's cue to size the spend against gates they entered in decimal\n // USD. The machine `candidates` array in --json keeps atomic.\n ...candidates.map(\n (c, i) =>\n ` ${i + 1}. ${sanitizeForTerminal(c.title)}, ${formatUsdDisplay(c.price)} USD, ${sanitizeForTerminal(c.url)}`,\n ),\n ...truncatedHint,\n ];\n\n return { data: response, humanLines };\n}\n\nconst STALE_MS = 7 * 24 * 60 * 60 * 1000;\n\n/** One stderr line naming parked candidates (and how many are stale >7d), so a\n * search is a reminder to publish/tidy the local pen. Silent when none parked. */\nasync function emitCandidateNudge(ctx: CommandContext): Promise<void> {\n const records = await listCandidates(ctx.dataDir);\n if (records.length === 0) return;\n const now = Date.now();\n const stale = records.filter((r) => now - Date.parse(r.meta.created) > STALE_MS).length;\n ctx.io.stderr.write(\n `${records.length} candidate(s) parked (${stale} stale >7d) - tenjin candidate list\\n`,\n );\n}\n\nfunction parseLimit(raw: string): number {\n const n = Number(raw);\n if (!Number.isInteger(n)) {\n throw new CliError('USAGE', `Invalid --limit: ${JSON.stringify(raw)}`, {\n fix: 'Pass an integer between 1 and 10.',\n });\n }\n return n;\n}\n\n/** `products=Vercel` or `products=Vercel,Next` → { products: [\"Vercel\",\"Next\"] }. Repeated\n * keys merge their values. */\nfunction parseAppliesTo(pairs: string[]): Record<string, string[]> {\n const out: Record<string, string[]> = {};\n for (const pair of pairs) {\n const eq = pair.indexOf('=');\n if (eq <= 0) {\n throw new CliError('USAGE', `Invalid --applies-to: ${JSON.stringify(pair)}`, {\n fix: 'Use key=value, e.g. --applies-to products=Vercel.',\n });\n }\n const key = pair.slice(0, eq).trim();\n const values = pair\n .slice(eq + 1)\n .split(',')\n .map((v) => v.trim())\n .filter((v) => v.length > 0);\n if (values.length === 0) {\n throw new CliError('USAGE', `--applies-to ${JSON.stringify(key)} has no values`, {\n fix: 'Give each key at least one value, e.g. products=Vercel.',\n });\n }\n out[key] = [...(out[key] ?? []), ...values];\n }\n return out;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAwCA,eAAsB,UACpB,MACA,KACA,OAAmB,CAAC,GACI;AACxB,QAAM,WAAW,MAAM,uBAAuB,GAAG;AACjD,QAAM,QAAqB,EAAE,UAAU,KAAK,SAAS;AACrD,MAAI,KAAK,aAAa,OAAW,OAAM,WAAW,iBAAiB,KAAK,QAAQ;AAChF,MAAI,KAAK,gBAAgB,OAAW,OAAM,cAAc,KAAK;AAC7D,MAAI,KAAK,UAAU,OAAW,OAAM,QAAQ,WAAW,KAAK,KAAK;AACjE,MAAI,KAAK,cAAc,UAAa,KAAK,UAAU,SAAS,GAAG;AAC7D,UAAM,YAAY,eAAe,KAAK,SAAS;AAAA,EACjD;AAEA,QAAM,UAAU,mBAAmB,KAAK;AACxC,QAAM,WAAW,MAAM,WAAW,SAAS;AAAA,IACzC,SAAS,SAAS;AAAA,IAClB,WAAW,IAAI,MAAM;AAAA,IACrB,YAAY,SAAS;AAAA,IACrB,GAAI,KAAK,cAAc,SAAY,EAAE,WAAW,KAAK,UAAU,IAAI,CAAC;AAAA,EACtE,CAAC;AAED,QAAM,aAAa,SAAS,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