@inupedia/spotlight-client 0.7.7 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # @inupedia/spotlight-client
2
2
 
3
- Spotlight 的浏览器 Tool SDK。业务项目只注册 Tools / Skills,然后调用 `thread.run()`;Tool 名称、说明、JSON Schema、manifest digest、Capability Session、SSE 重连和 Tool 结果回传都由 SDK 处理。
3
+ Spotlight 的浏览器 Tool SDK。业务项目只注册 Tools / Resource Providers / Skills,然后调用 `thread.run()`;Tool 名称、说明、JSON Schema、manifest digest、Capability Session、SSE 重连和 Tool Result 回传都由 SDK 处理。
4
4
 
5
5
  ```ts
6
6
  import { defineClientTool } from "@inupedia/spotlight-client";
@@ -25,7 +25,7 @@ const result = await thread.run("看看泸定取水口");
25
25
  console.log(result.finalResponse);
26
26
  ```
27
27
 
28
- Vite 项目必须启用构建插件:
28
+ Vite 项目可启用构建插件自动推导 Tool 元数据:
29
29
 
30
30
  ```ts
31
31
  import { spotlightClientTools } from "@inupedia/spotlight-client/vite";
@@ -36,8 +36,10 @@ spotlightClientTools({
36
36
  });
37
37
  ```
38
38
 
39
+ 非 Vite 项目直接使用显式 `defineTool({ name, description, schema, handler })`,不需要迁移构建系统。摄像头、资产等大型动态目录使用 `defineResourceProvider` 注册一次 search/get/action;SDK 会生成延迟加载的资源 Tool,并在浏览器侧把用户名称或别名解析成稳定 ID。
40
+
39
41
  生产构建会输出 `spotlight-client-manifest.json`。首次初始化后 Server 保存不可变 Capability Snapshot,后续 Turn 不再重复上传整份 Tools / Skills。
40
42
 
41
- 完整接入、显式 Schema 和生产部署见 [Client Tool 接入指南](../../docs/client-tools.md)。
43
+ 完整接入、显式 Schema 和生产部署见 [Client Tool 接入指南](../../docs/client-tools.md);大型动态目录见 [Resource Provider 接入指南](../../docs/resource-providers.md)。
42
44
 
43
45
  Node-only 的 Skill 脚本执行器仍从 `@inupedia/spotlight-client/node` 导入。主入口不包含 Node API。
@@ -1,10 +1,13 @@
1
1
  import { type FrontendToolManifestV1, type HostToolResultRequest, type SpotlightInitializeResponse, type SpotlightItem, type SpotlightSkill, type SpotlightSkillRegistration, type SpotlightThread, type SpotlightTurn, type SpotlightTurnEvent, type SpotlightTurnStartRequest } from "@inupedia/spotlight-protocol";
2
2
  import { type SpotlightClientConfig } from "./http.js";
3
3
  import { type ClientTool } from "./clientTool.js";
4
+ import type { SpotlightResourceProvider } from "./resourceProvider.js";
4
5
  export interface SpotlightAppClientOptions extends SpotlightClientConfig {
5
6
  toolManifest?: FrontendToolManifestV1 | (() => FrontendToolManifestV1 | Promise<FrontendToolManifestV1>);
6
7
  /** Preferred: register Tools and let the SDK derive and snapshot the manifest. */
7
8
  tools?: readonly ClientTool[] | (() => readonly ClientTool[]);
9
+ /** Resource providers generate search/get/action Tools and optional Skills. */
10
+ resources?: readonly SpotlightResourceProvider[] | (() => readonly SpotlightResourceProvider[]);
8
11
  frontendBuildId?: string;
9
12
  skills?: Array<SpotlightSkill | SpotlightSkillRegistration> | (() => Array<SpotlightSkill | SpotlightSkillRegistration>);
10
13
  executeTool?: (request: {
@@ -59,6 +62,9 @@ export declare class SpotlightAppClient {
59
62
  private toolRegistry;
60
63
  constructor(options: SpotlightAppClientOptions);
61
64
  private manifest;
65
+ private resolveResources;
66
+ private resolveTools;
67
+ private resolveSkills;
62
68
  initialize(signal?: AbortSignal): Promise<SpotlightInitializeResponse>;
63
69
  startThread(threadId?: string, signal?: AbortSignal): Promise<SpotlightThread>;
64
70
  thread(threadId?: string): SpotlightThreadHandle;
@@ -1 +1 @@
1
- {"version":3,"file":"appClient.d.ts","sourceRoot":"","sources":["../src/appClient.ts"],"names":[],"mappings":"AAAA,OAAO,EAIL,KAAK,sBAAsB,EAC3B,KAAK,qBAAqB,EAC1B,KAAK,2BAA2B,EAChC,KAAK,aAAa,EAClB,KAAK,cAAc,EACnB,KAAK,0BAA0B,EAC/B,KAAK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 @@ function normalizeSkills(skills) {
21
21
  displayName: skill.interface?.displayName ?? skill.displayName,
22
22
  description: skill.description,
23
23
  version: skill.version,
24
- allowImplicitInvocation: skill.policy?.allowImplicitInvocation ?? skill.disableModelInvocation !== true,
24
+ allowImplicitInvocation: skill.policy?.allowImplicitInvocation ??
25
+ skill.disableModelInvocation !== true,
25
26
  userInvocable: skill.userInvocable,
26
27
  dependencies: { tools: spotlightSkillToolNames(skill) },
27
28
  })),
@@ -75,10 +76,9 @@ export class SpotlightAppClient {
75
76
  async manifest() {
76
77
  if (this.options.toolManifest)
77
78
  return asyncValueOf(this.options.toolManifest);
78
- if (!this.options.tools) {
79
- throw new Error("Spotlight requires tools or toolManifest");
80
- }
81
- const tools = valueOf(this.options.tools);
79
+ const tools = this.resolveTools();
80
+ if (tools.length === 0)
81
+ throw new Error("Spotlight requires tools, resources or toolManifest");
82
82
  this.toolRegistry = createClientToolRegistry(tools);
83
83
  return createClientToolManifest({
84
84
  projectId: this.options.projectId,
@@ -86,29 +86,48 @@ export class SpotlightAppClient {
86
86
  tools,
87
87
  });
88
88
  }
89
+ resolveResources() {
90
+ return this.options.resources ? valueOf(this.options.resources) : [];
91
+ }
92
+ resolveTools() {
93
+ const direct = this.options.tools ? valueOf(this.options.tools) : [];
94
+ return [
95
+ ...direct,
96
+ ...this.resolveResources().flatMap((resource) => resource.tools),
97
+ ];
98
+ }
99
+ resolveSkills() {
100
+ const direct = this.options.skills ? valueOf(this.options.skills) : [];
101
+ const generated = this.resolveResources().flatMap((resource) => resource.skill ? [resource.skill] : []);
102
+ return [...direct, ...generated];
103
+ }
89
104
  async initialize(signal) {
90
105
  const manifest = await this.manifest();
91
- if (this.initialization && this.initializedDigest === manifest.manifestDigest) {
106
+ if (this.initialization &&
107
+ this.initializedDigest === manifest.manifestDigest) {
92
108
  return this.initialization;
93
109
  }
94
110
  this.initializedDigest = manifest.manifestDigest;
95
- const normalizedSkills = normalizeSkills(this.options.skills ? valueOf(this.options.skills) : []);
96
- this.initialization = this.http.postJson("/v1/initialize", {
111
+ const normalizedSkills = normalizeSkills(this.resolveSkills());
112
+ this.initialization = this.http
113
+ .postJson("/v1/initialize", {
97
114
  protocolVersion: SPOTLIGHT_APP_PROTOCOL_V1,
98
115
  projectId: this.options.projectId,
99
116
  clientInfo: {
100
117
  name: this.options.clientInfo?.name ?? "spotlight-typescript",
101
118
  title: this.options.clientInfo?.title,
102
- version: this.options.clientInfo?.version ?? "0.7.1",
119
+ version: this.options.clientInfo?.version ?? "0.8.0",
103
120
  },
104
121
  capabilities: defaultSpotlightClientCapabilities(),
105
122
  toolManifest: manifest,
106
123
  skills: normalizedSkills.registrations,
107
124
  skillDefinitions: normalizedSkills.definitions,
108
- }, signal).then((response) => {
125
+ }, signal)
126
+ .then((response) => {
109
127
  this.capabilitySessionId = response.capabilitySession.id;
110
128
  return response;
111
- }).catch((error) => {
129
+ })
130
+ .catch((error) => {
112
131
  this.initialization = null;
113
132
  this.capabilitySessionId = null;
114
133
  throw error;
@@ -127,7 +146,10 @@ export class SpotlightAppClient {
127
146
  return resolvedId;
128
147
  },
129
148
  run: async (input, options = {}) => {
130
- const result = await this.run(input, { ...options, threadId: resolvedId });
149
+ const result = await this.run(input, {
150
+ ...options,
151
+ threadId: resolvedId,
152
+ });
131
153
  resolvedId = result.thread.id;
132
154
  return result;
133
155
  },
@@ -143,12 +165,16 @@ export class SpotlightAppClient {
143
165
  }
144
166
  async startTurn(threadId, request, signal) {
145
167
  await this.initialize(signal);
146
- const start = () => this.http.postJson(`/v1/threads/${encodeURIComponent(threadId)}/turns`, { ...request, capabilitySessionId: request.capabilitySessionId ?? this.capabilitySessionId }, signal);
168
+ const start = () => this.http.postJson(`/v1/threads/${encodeURIComponent(threadId)}/turns`, {
169
+ ...request,
170
+ capabilitySessionId: request.capabilitySessionId ?? this.capabilitySessionId,
171
+ }, signal);
147
172
  try {
148
173
  return (await start()).turn;
149
174
  }
150
175
  catch (error) {
151
- if (!(error instanceof SpotlightHttpError) || error.code !== "CAPABILITY_SESSION_EXPIRED") {
176
+ if (!(error instanceof SpotlightHttpError) ||
177
+ error.code !== "CAPABILITY_SESSION_EXPIRED") {
152
178
  throw error;
153
179
  }
154
180
  this.initialization = null;
@@ -168,9 +194,13 @@ export class SpotlightAppClient {
168
194
  let summary;
169
195
  for await (const event of this.streamTurn(turn.id, signal)) {
170
196
  events.push(event);
171
- if (event.type === "item.started" || event.type === "item.updated" || event.type === "item.completed") {
197
+ if (event.type === "item.started" ||
198
+ event.type === "item.updated" ||
199
+ event.type === "item.completed") {
172
200
  items.set(event.item.id, event.item);
173
- const clientRequest = event.item.type === "tool_call" ? event.item.clientRequest : undefined;
201
+ const clientRequest = event.item.type === "tool_call"
202
+ ? event.item.clientRequest
203
+ : undefined;
174
204
  if (event.item.type === "tool_call" &&
175
205
  event.item.status === "waiting_for_client" &&
176
206
  clientRequest &&
@@ -187,13 +217,24 @@ export class SpotlightAppClient {
187
217
  const result = !approved
188
218
  ? { success: false, error: "Tool execution was not approved" }
189
219
  : this.options.executeTool
190
- ? await this.options.executeTool({ turnId: turn.id, item: event.item })
220
+ ? await this.options.executeTool({
221
+ turnId: turn.id,
222
+ item: event.item,
223
+ })
191
224
  : this.toolRegistry?.has(event.item.tool)
192
- ? {
193
- success: true,
194
- output: await this.toolRegistry.execute(event.item.tool, event.item.arguments),
195
- }
196
- : { success: false, error: `Client tool is not registered: ${event.item.tool}` };
225
+ ? await this.toolRegistry
226
+ .executeResult(event.item.tool, event.item.arguments)
227
+ .then((result) => result.success
228
+ ? { success: true, output: result }
229
+ : {
230
+ success: false,
231
+ error: result.error.message,
232
+ errorCode: result.error.code,
233
+ })
234
+ : {
235
+ success: false,
236
+ error: `Client tool is not registered: ${event.item.tool}`,
237
+ };
197
238
  await this.submitToolResult(turn.id, {
198
239
  correlationId: clientRequest.correlationId,
199
240
  ...result,
@@ -208,7 +249,14 @@ export class SpotlightAppClient {
208
249
  summary = event.summary;
209
250
  }
210
251
  }
211
- return { thread, turn, events, items: [...items.values()], finalResponse, summary };
252
+ return {
253
+ thread,
254
+ turn,
255
+ events,
256
+ items: [...items.values()],
257
+ finalResponse,
258
+ summary,
259
+ };
212
260
  }
213
261
  async *streamTurn(turnId, signal) {
214
262
  let lastSeq = 0;
@@ -251,7 +299,8 @@ export class SpotlightAppClient {
251
299
  continue;
252
300
  lastSeq = event.seq;
253
301
  yield event;
254
- if (event.type === "turn.completed" || event.type === "turn.failed") {
302
+ if (event.type === "turn.completed" ||
303
+ event.type === "turn.failed") {
255
304
  terminal = true;
256
305
  return;
257
306
  }
@@ -1,4 +1,4 @@
1
- import { type FrontendToolDescriptorV1, type FrontendToolManifestV1, type JsonSchemaV1, type ToolReplayPolicyV1, type ToolRiskLevelV1, type ToolSideEffectV1, type ToolTierV1 } from "@inupedia/spotlight-protocol";
1
+ import { type FrontendToolDescriptorV1, type FrontendToolManifestV1, type JsonSchemaV1, type SpotlightToolResultEnvelope, type ToolReplayPolicyV1, type ToolRiskLevelV1, type ToolSideEffectV1, type ToolTierV1 } from "@inupedia/spotlight-protocol";
2
2
  export declare const CLIENT_TOOL_META: unique symbol;
3
3
  export interface ClientToolSchemaOverride {
4
4
  input: JsonSchemaV1;
@@ -19,6 +19,9 @@ export interface ClientToolOptions {
19
19
  riskLevel?: ToolRiskLevelV1;
20
20
  requiresConfirmation?: boolean;
21
21
  maxOutputBytes?: number;
22
+ namespace?: string;
23
+ deferLoading?: boolean;
24
+ resource?: FrontendToolDescriptorV1["resource"];
22
25
  }
23
26
  export interface GeneratedClientToolMeta extends ClientToolOptions {
24
27
  name: string;
@@ -29,16 +32,36 @@ export type ClientToolHandler<TInput, TOutput> = (input: TInput) => TOutput | Pr
29
32
  export type ClientTool<TInput = never, TOutput = unknown> = ClientToolHandler<TInput, TOutput> & {
30
33
  readonly [CLIENT_TOOL_META]: GeneratedClientToolMeta;
31
34
  };
35
+ export interface DefineToolOptions<TInput, TOutput> extends ClientToolOptions {
36
+ name: string;
37
+ description: string;
38
+ schema: ClientToolSchemaOverride;
39
+ handler: ClientToolHandler<TInput, TOutput>;
40
+ }
41
+ export declare class SpotlightToolValidationError extends Error {
42
+ readonly code: "TOOL_INPUT_INVALID" | "TOOL_OUTPUT_INVALID";
43
+ readonly issues: Array<{
44
+ path: string;
45
+ message: string;
46
+ }>;
47
+ constructor(code: "TOOL_INPUT_INVALID" | "TOOL_OUTPUT_INVALID", message: string, issues: Array<{
48
+ path: string;
49
+ message: string;
50
+ }>);
51
+ }
32
52
  /**
33
53
  * Define a browser-side tool. Name, JSDoc and schemas are injected by the
34
54
  * Spotlight Vite plugin. Pass `schema` only as an explicit inference escape hatch.
35
55
  */
36
56
  export declare function defineClientTool<TInput = void, TOutput = void>(handler: ClientToolHandler<TInput, TOutput>, options?: ClientToolOptions | GeneratedClientToolMeta): ClientTool<TInput, TOutput>;
57
+ /** Framework/build-tool neutral Tool definition for non-Vite and generated capabilities. */
58
+ export declare function defineTool<TInput = void, TOutput = void>(options: DefineToolOptions<TInput, TOutput>): ClientTool<TInput, TOutput>;
37
59
  export declare function getClientToolDescriptor(tool: ClientTool): FrontendToolDescriptorV1;
38
60
  export declare function createClientToolRegistry(tools: readonly ClientTool[]): {
39
61
  descriptors: FrontendToolDescriptorV1[];
40
62
  has(name: string): boolean;
41
63
  execute(name: string, input: unknown): Promise<unknown>;
64
+ executeResult(name: string, input: unknown): Promise<SpotlightToolResultEnvelope>;
42
65
  };
43
66
  export declare function createClientToolManifest(options: {
44
67
  projectId: string;
@@ -1 +1 @@
1
- {"version":3,"file":"clientTool.d.ts","sourceRoot":"","sources":["../src/clientTool.ts"],"names":[],"mappings":"AAAA,OAAO,EAIL,KAAK,wBAAwB,EAC7B,KAAK,sBAAsB,EAC3B,KAAK,YAAY,EACjB,KAAK,kBAAkB,EACvB,KAAK,eAAe,EACpB,KAAK,gBAAgB,EACrB,KAAK,UAAU,EAChB,MAAM,8BAA8B,CAAC;AAEtC,eAAO,MAAM,gBAAgB,eAA+C,CAAC;AAE7E,MAA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AAC,EAAE,iBAAiB,GAAG,uBAAuB,GACpD,UAAU,CAAC,MAAM,EAAE,OAAO,CAAC,CAa7B;AAED,4FAA4F;AAC5F,wBAAgB,UAAU,CAAC,MAAM,GAAG,IAAI,EAAE,OAAO,GAAG,IAAI,EACtD,OAAO,EAAE,iBAAiB,CAAC,MAAM,EAAE,OAAO,CAAC,GAC1C,UAAU,CAAC,MAAM,EAAE,OAAO,CAAC,CAG7B;AAED,wBAAgB,uBAAuB,CACrC,IAAI,EAAE,UAAU,GACf,wBAAwB,CAqB1B;AAED,wBAAgB,wBAAwB,CAAC,KAAK,EAAE,SAAS,UAAU,EAAE;;cAyBvD,MAAM,GAAG,OAAO;kBAGN,MAAM,SAAS,OAAO,GAAG,OAAO,CAAC,OAAO,CAAC;wBAkCrD,MAAM,SACL,OAAO,GACb,OAAO,CAAC,2BAA2B,CAAC;EAkB1C;AA2HD,wBAAsB,wBAAwB,CAAC,OAAO,EAAE;IACtD,SAAS,EAAE,MAAM,CAAC;IAClB,eAAe,EAAE,MAAM,CAAC;IACxB,KAAK,EAAE,SAAS,UAAU,EAAE,CAAC;CAC9B,GAAG,OAAO,CAAC,sBAAsB,CAAC,CAelC"}
@@ -1,5 +1,15 @@
1
- import { deriveToolTier, isToolTierReplaySafe, SPOTLIGHT_CAPABILITY_PROTOCOL_V1, } from "@inupedia/spotlight-protocol";
1
+ import { deriveToolTier, isToolTierReplaySafe, normalizeSpotlightToolOutput, SPOTLIGHT_CAPABILITY_PROTOCOL_V1, validateJsonSchemaValue, } from "@inupedia/spotlight-protocol";
2
2
  export const CLIENT_TOOL_META = Symbol.for("inupedia.spotlight.client-tool");
3
+ export class SpotlightToolValidationError extends Error {
4
+ code;
5
+ issues;
6
+ constructor(code, message, issues) {
7
+ super(message);
8
+ this.code = code;
9
+ this.issues = issues;
10
+ this.name = "SpotlightToolValidationError";
11
+ }
12
+ }
3
13
  function isGeneratedMeta(value) {
4
14
  return Boolean(value &&
5
15
  "name" in value &&
@@ -24,6 +34,11 @@ export function defineClientTool(handler, options) {
24
34
  });
25
35
  return handler;
26
36
  }
37
+ /** Framework/build-tool neutral Tool definition for non-Vite and generated capabilities. */
38
+ export function defineTool(options) {
39
+ const { handler, name, description, schema, ...metadata } = options;
40
+ return defineClientTool(handler, { name, description, schema, ...metadata });
41
+ }
27
42
  export function getClientToolDescriptor(tool) {
28
43
  const meta = tool[CLIENT_TOOL_META];
29
44
  const legacy = {
@@ -34,12 +49,15 @@ export function getClientToolDescriptor(tool) {
34
49
  };
35
50
  return {
36
51
  name: meta.name,
52
+ namespace: meta.namespace,
53
+ deferLoading: meta.deferLoading,
37
54
  version: meta.version ?? "1.0.0",
38
55
  description: meta.description,
39
56
  inputSchema: meta.schema.input,
40
57
  outputSchema: meta.schema.output,
41
58
  maxOutputBytes: meta.maxOutputBytes,
42
59
  tier: deriveToolTier({ tier: meta.tier, ...legacy }),
60
+ resource: meta.resource,
43
61
  ...legacy,
44
62
  };
45
63
  }
@@ -71,7 +89,36 @@ export function createClientToolRegistry(tools) {
71
89
  const tool = byName.get(name);
72
90
  if (!tool)
73
91
  throw new Error(`Client tool is not registered: ${name}`);
74
- return tool(input);
92
+ const descriptor = getClientToolDescriptor(tool);
93
+ const inputValidation = validateJsonSchemaValue(input, descriptor.inputSchema);
94
+ if (!inputValidation.valid) {
95
+ throw new SpotlightToolValidationError("TOOL_INPUT_INVALID", `Client tool input is invalid: ${name}`, inputValidation.issues);
96
+ }
97
+ const output = await tool(input);
98
+ if (descriptor.outputSchema) {
99
+ const outputValidation = validateJsonSchemaValue(output, descriptor.outputSchema);
100
+ if (!outputValidation.valid) {
101
+ throw new SpotlightToolValidationError("TOOL_OUTPUT_INVALID", `Client tool output is invalid: ${name}`, outputValidation.issues);
102
+ }
103
+ }
104
+ return output;
105
+ },
106
+ async executeResult(name, input) {
107
+ try {
108
+ return normalizeSpotlightToolOutput(await this.execute(name, input));
109
+ }
110
+ catch (error) {
111
+ const validation = error instanceof SpotlightToolValidationError ? error : null;
112
+ return {
113
+ success: false,
114
+ error: {
115
+ code: validation?.code ?? "TOOL_RUN_FAILED",
116
+ message: error instanceof Error ? error.message : String(error),
117
+ retryable: false,
118
+ ...(validation ? { details: { issues: validation.issues } } : {}),
119
+ },
120
+ };
121
+ }
75
122
  },
76
123
  };
77
124
  }
@@ -98,22 +145,20 @@ async function sha256(value) {
98
145
  .join("")}`;
99
146
  }
100
147
  const SHA256_INITIAL_STATE = [
101
- 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f,
102
- 0x9b05688c, 0x1f83d9ab, 0x5be0cd19,
148
+ 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c,
149
+ 0x1f83d9ab, 0x5be0cd19,
103
150
  ];
104
151
  const SHA256_ROUND_CONSTANTS = [
105
- 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b,
106
- 0x59f111f1, 0x923f82a4, 0xab1c5ed5, 0xd807aa98, 0x12835b01,
107
- 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7,
108
- 0xc19bf174, 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc,
109
- 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, 0x983e5152,
110
- 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147,
111
- 0x06ca6351, 0x14292967, 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc,
112
- 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
113
- 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819,
114
- 0xd6990624, 0xf40e3585, 0x106aa070, 0x19a4c116, 0x1e376c08,
115
- 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f,
116
- 0x682e6ff3, 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208,
152
+ 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1,
153
+ 0x923f82a4, 0xab1c5ed5, 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3,
154
+ 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, 0xe49b69c1, 0xefbe4786,
155
+ 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
156
+ 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147,
157
+ 0x06ca6351, 0x14292967, 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13,
158
+ 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, 0xa2bfe8a1, 0xa81a664b,
159
+ 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
160
+ 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a,
161
+ 0x5b9cca4f, 0x682e6ff3, 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208,
117
162
  0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2,
118
163
  ];
119
164
  function rotateRight(value, amount) {
@@ -151,7 +196,11 @@ function sha256Fallback(bytes) {
151
196
  for (let index = 0; index < 64; index += 1) {
152
197
  const sum1 = rotateRight(e, 6) ^ rotateRight(e, 11) ^ rotateRight(e, 25);
153
198
  const choose = (e & f) ^ (~e & g);
154
- const temporary1 = (h + sum1 + choose + SHA256_ROUND_CONSTANTS[index] + words[index]) >>>
199
+ const temporary1 = (h +
200
+ sum1 +
201
+ choose +
202
+ SHA256_ROUND_CONSTANTS[index] +
203
+ words[index]) >>>
155
204
  0;
156
205
  const sum0 = rotateRight(a, 2) ^ rotateRight(a, 13) ^ rotateRight(a, 22);
157
206
  const majority = (a & b) ^ (a & c) ^ (b & c);
package/dist/index.d.ts CHANGED
@@ -1,9 +1,11 @@
1
1
  export type { SpotlightClientConfig } from "./http.js";
2
- export { CLIENT_TOOL_META, createClientToolManifest, createClientToolRegistry, defineClientTool, getClientToolDescriptor, type ClientTool, type ClientToolHandler, type ClientToolOptions, type ClientToolSchemaOverride, type GeneratedClientToolMeta, } from "./clientTool.js";
2
+ export { CLIENT_TOOL_META, createClientToolManifest, createClientToolRegistry, defineClientTool, defineTool, getClientToolDescriptor, type ClientTool, type ClientToolHandler, type ClientToolOptions, type ClientToolSchemaOverride, type GeneratedClientToolMeta, type DefineToolOptions, SpotlightToolValidationError, } from "./clientTool.js";
3
+ export { defineResourceProvider, type SpotlightResourceAction, type SpotlightResourceProvider, type SpotlightResourceProviderOptions, } from "./resourceProvider.js";
3
4
  export { appendProjectQuery, buildJsonHeaders, createSpotlightHttp, normalizeServerUrl, resolveSpotlightClientConfig, SpotlightHttpError, type SpotlightHttp, } from "./http.js";
4
5
  export { fetchDefaultCommandCatalog, mergeCommandCatalogs, serializeSkillsForRemote, } from "./host.js";
5
6
  export { validateSkillFrontmatter, describeCapabilitySurface, SPOTLIGHT_LAYOUT, SPOTLIGHT_SKILL_LOAD_LEVELS, spotlightSkillsGlobPattern, type SkillValidationResult, type SpotlightSkillFrontmatter, } from "./skillServiceStandard.js";
6
7
  export { substituteSkillPlaceholders, executeInlineShellInMarkdown, prepareSkillMarkdownContent, } from "./skillPrompt.js";
7
8
  export { joinSkillScriptPath, type SkillScriptRunResult, } from "./skillScriptPath.js";
8
9
  export * from "./appClient.js";
10
+ export type { SpotlightResourceRef, SpotlightResourceSearchInput, SpotlightResourceSearchResult, SpotlightResourceStatus, SpotlightToolResultEnvelope, SpotlightContentItem, } from "@inupedia/spotlight-protocol";
9
11
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAA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uBAAuB,EAC5B,KAAK,yBAAyB,EAC9B,KAAK,gCAAgC,GACtC,MAAM,uBAAuB,CAAC;AAC/B,OAAO,EACL,kBAAkB,EAClB,gBAAgB,EAChB,mBAAmB,EACnB,kBAAkB,EAClB,4BAA4B,EAC5B,kBAAkB,EAClB,KAAK,aAAa,GACnB,MAAM,WAAW,CAAC;AACnB,OAAO,EACL,0BAA0B,EAC1B,oBAAoB,EACpB,wBAAwB,GACzB,MAAM,WAAW,CAAC;AACnB,OAAO,EACL,wBAAwB,EACxB,yBAAyB,EACzB,gBAAgB,EAChB,2BAA2B,EAC3B,0BAA0B,EAC1B,KAAK,qBAAqB,EAC1B,KAAK,yBAAyB,GAC/B,MAAM,2BAA2B,CAAC;AACnC,OAAO,EACL,2BAA2B,EAC3B,4BAA4B,EAC5B,2BAA2B,GAC5B,MAAM,kBAAkB,CAAC;AAC1B,OAAO,EACL,mBAAmB,EACnB,KAAK,oBAAoB,GAC1B,MAAM,sBAAsB,CAAC;AAC9B,cAAc,gBAAgB,CAAC;AAC/B,YAAY,EACV,oBAAoB,EACpB,4BAA4B,EAC5B,6BAA6B,EAC7B,uBAAuB,EACvB,2BAA2B,EAC3B,oBAAoB,GACrB,MAAM,8BAA8B,CAAC"}
package/dist/index.js CHANGED
@@ -1,4 +1,5 @@
1
- export { CLIENT_TOOL_META, createClientToolManifest, createClientToolRegistry, defineClientTool, getClientToolDescriptor, } from "./clientTool.js";
1
+ export { CLIENT_TOOL_META, createClientToolManifest, createClientToolRegistry, defineClientTool, defineTool, getClientToolDescriptor, SpotlightToolValidationError, } from "./clientTool.js";
2
+ export { defineResourceProvider, } from "./resourceProvider.js";
2
3
  export { appendProjectQuery, buildJsonHeaders, createSpotlightHttp, normalizeServerUrl, resolveSpotlightClientConfig, SpotlightHttpError, } from "./http.js";
3
4
  export { fetchDefaultCommandCatalog, mergeCommandCatalogs, serializeSkillsForRemote, } from "./host.js";
4
5
  export { validateSkillFrontmatter, describeCapabilitySurface, SPOTLIGHT_LAYOUT, SPOTLIGHT_SKILL_LOAD_LEVELS, spotlightSkillsGlobPattern, } from "./skillServiceStandard.js";
@@ -0,0 +1,34 @@
1
+ import type { SpotlightResourceRef, SpotlightResourceSearchInput, SpotlightResourceSearchResult, SpotlightSkill } from "@inupedia/spotlight-protocol";
2
+ import { type ClientTool } from "./clientTool.js";
3
+ export interface SpotlightResourceAction<TResource extends SpotlightResourceRef> {
4
+ /** Public Tool name. Defaults to `${namespace}_${action}`. */
5
+ toolName?: string;
6
+ description: string;
7
+ handler: (resource: TResource) => unknown | Promise<unknown>;
8
+ tier?: "observe" | "query" | "navigate";
9
+ }
10
+ export interface SpotlightResourceProviderOptions<TResource extends SpotlightResourceRef> {
11
+ namespace: string;
12
+ description: string;
13
+ search(input: SpotlightResourceSearchInput): Promise<SpotlightResourceSearchResult<TResource>>;
14
+ get?(id: string): Promise<TResource | null>;
15
+ actions?: Record<string, SpotlightResourceAction<TResource>>;
16
+ /** Defaults to a generated resource Skill. Set false when a richer consumer Skill already exists. */
17
+ skill?: false | {
18
+ name?: string;
19
+ displayName?: string;
20
+ description?: string;
21
+ whenToUse?: string;
22
+ capabilityExamples?: string[];
23
+ };
24
+ }
25
+ export interface SpotlightResourceProvider<TResource extends SpotlightResourceRef = SpotlightResourceRef> {
26
+ namespace: string;
27
+ description: string;
28
+ tools: ClientTool[];
29
+ skill?: SpotlightSkill;
30
+ search(input: SpotlightResourceSearchInput): Promise<SpotlightResourceSearchResult<TResource>>;
31
+ resolve(query: string): Promise<TResource>;
32
+ }
33
+ export declare function defineResourceProvider<TResource extends SpotlightResourceRef>(options: SpotlightResourceProviderOptions<TResource>): SpotlightResourceProvider<TResource>;
34
+ //# sourceMappingURL=resourceProvider.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"resourceProvider.d.ts","sourceRoot":"","sources":["../src/resourceProvider.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,oBAAoB,EACpB,4BAA4B,EAC5B,6BAA6B,E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IACvB,MAAM,CACJ,KAAK,EAAE,4BAA4B,GAClC,OAAO,CAAC,6BAA6B,CAAC,SAAS,CAAC,CAAC,CAAC;IACrD,OAAO,CAAC,KAAK,EAAE,MAAM,GAAG,OAAO,CAAC,SAAS,CAAC,CAAC;CAC5C;AA6BD,wBAAgB,sBAAsB,CAAC,SAAS,SAAS,oBAAoB,EAC3E,OAAO,EAAE,gCAAgC,CAAC,SAAS,CAAC,GACnD,yBAAyB,CAAC,SAAS,CAAC,CAwItC"}
@@ -0,0 +1,152 @@
1
+ import { defineTool } from "./clientTool.js";
2
+ function normalized(value) {
3
+ return value
4
+ .normalize("NFKC")
5
+ .toLocaleLowerCase()
6
+ .replace(/[\p{P}\p{S}\s]+/gu, "");
7
+ }
8
+ function scoreResource(query, resource) {
9
+ const q = normalized(query);
10
+ const candidates = [resource.id, resource.name, ...(resource.aliases ?? [])]
11
+ .map(normalized)
12
+ .filter(Boolean);
13
+ if (candidates.some((candidate) => candidate === q))
14
+ return 10_000;
15
+ const contained = candidates
16
+ .filter((candidate) => q.includes(candidate) || candidate.includes(q))
17
+ .map((candidate) => candidate.length);
18
+ return contained.length > 0 ? 1_000 + Math.max(...contained) : 0;
19
+ }
20
+ function toolSafeNamespace(value) {
21
+ const normalizedValue = value.trim().replace(/[^a-zA-Z0-9_-]/gu, "_");
22
+ if (!normalizedValue) {
23
+ throw new Error("Resource namespace must contain a tool-safe identifier");
24
+ }
25
+ return normalizedValue;
26
+ }
27
+ export function defineResourceProvider(options) {
28
+ const namespace = toolSafeNamespace(options.namespace);
29
+ const resolve = async (query) => {
30
+ const direct = options.get ? await options.get(query) : null;
31
+ if (direct)
32
+ return direct;
33
+ const result = await options.search({ query, limit: 20 });
34
+ const ranked = result.items
35
+ .map((resource) => ({ resource, score: scoreResource(query, resource) }))
36
+ .filter((item) => item.score > 0)
37
+ .sort((left, right) => right.score - left.score);
38
+ const best = ranked[0];
39
+ if (!best) {
40
+ throw new Error(`RESOURCE_NOT_FOUND: ${options.namespace}:${query}`);
41
+ }
42
+ const ties = ranked.filter((item) => item.score === best.score);
43
+ if (new Set(ties.map((item) => item.resource.id)).size > 1) {
44
+ throw new Error(`RESOURCE_AMBIGUOUS: ${options.namespace}:${query}; matches ${ties
45
+ .map((item) => item.resource.name)
46
+ .join(", ")}`);
47
+ }
48
+ return best.resource;
49
+ };
50
+ const searchToolName = `${namespace}_search`;
51
+ const searchTool = defineTool({
52
+ name: searchToolName,
53
+ description: `Search ${options.description}. Use this for lists, discovery, status and ambiguous names.`,
54
+ namespace,
55
+ deferLoading: true,
56
+ tier: "query",
57
+ sideEffect: "none",
58
+ replayPolicy: "safe",
59
+ resource: { namespace, operation: "search", inputKey: "query" },
60
+ schema: {
61
+ input: {
62
+ type: "object",
63
+ properties: {
64
+ query: { type: "string" },
65
+ limit: { type: "integer", minimum: 1, maximum: 100 },
66
+ cursor: { type: "string" },
67
+ filters: { type: "object" },
68
+ },
69
+ additionalProperties: false,
70
+ },
71
+ },
72
+ handler: (input) => options.search(input),
73
+ });
74
+ const getToolName = `${namespace}_get`;
75
+ const getTool = options.get
76
+ ? defineTool({
77
+ name: getToolName,
78
+ description: `Get one ${options.description} resource by its stable id.`,
79
+ namespace,
80
+ deferLoading: true,
81
+ tier: "query",
82
+ sideEffect: "none",
83
+ replayPolicy: "safe",
84
+ resource: { namespace, operation: "get", inputKey: "id" },
85
+ schema: {
86
+ input: {
87
+ type: "object",
88
+ properties: { id: { type: "string", minLength: 1 } },
89
+ required: ["id"],
90
+ additionalProperties: false,
91
+ },
92
+ },
93
+ handler: ({ id }) => options.get(id),
94
+ })
95
+ : null;
96
+ const actionEntries = Object.entries(options.actions ?? {});
97
+ const actionTools = actionEntries.map(([action, definition]) => {
98
+ const toolName = definition.toolName ?? `${namespace}_${action}`;
99
+ return defineTool({
100
+ name: toolName,
101
+ description: definition.description,
102
+ namespace,
103
+ tier: definition.tier ?? "navigate",
104
+ sideEffect: "ui",
105
+ replayPolicy: "safe",
106
+ resource: {
107
+ namespace,
108
+ operation: "action",
109
+ action,
110
+ inputKey: "query",
111
+ },
112
+ schema: {
113
+ input: {
114
+ type: "object",
115
+ properties: { query: { type: "string", minLength: 1 } },
116
+ required: ["query"],
117
+ additionalProperties: false,
118
+ },
119
+ },
120
+ handler: async ({ query }) => definition.handler(await resolve(query)),
121
+ });
122
+ });
123
+ const tools = [searchTool, ...(getTool ? [getTool] : []), ...actionTools];
124
+ const toolNames = [
125
+ searchToolName,
126
+ ...(getTool ? [getToolName] : []),
127
+ ...actionEntries.map(([action, definition]) => definition.toolName ?? `${namespace}_${action}`),
128
+ ];
129
+ const skillOptions = options.skill === false ? null : (options.skill ?? {});
130
+ const skill = skillOptions
131
+ ? {
132
+ name: skillOptions.name ?? `skill.resource.${namespace}`,
133
+ displayName: skillOptions.displayName ?? options.description,
134
+ description: skillOptions.description ??
135
+ `Search and operate ${options.description}.`,
136
+ whenToUse: skillOptions.whenToUse ??
137
+ `Use when the user asks about ${options.description}.`,
138
+ responseStrategy: "tool_answer",
139
+ allowedTools: toolNames,
140
+ capabilityExamples: skillOptions.capabilityExamples,
141
+ policy: { allowImplicitInvocation: true },
142
+ }
143
+ : undefined;
144
+ return {
145
+ namespace,
146
+ description: options.description,
147
+ tools,
148
+ skill,
149
+ search: options.search,
150
+ resolve,
151
+ };
152
+ }
@@ -9,6 +9,8 @@ type JsonSchema = Record<string, unknown>;
9
9
  type ToolTier = "observe" | "query" | "navigate" | "mutate";
10
10
  type BuildDescriptor = {
11
11
  name: string;
12
+ namespace?: string;
13
+ deferLoading?: boolean;
12
14
  version: string;
13
15
  description: string;
14
16
  inputSchema: JsonSchema;
@@ -19,6 +21,12 @@ type BuildDescriptor = {
19
21
  riskLevel: "low" | "medium" | "high";
20
22
  requiresConfirmation: boolean;
21
23
  maxOutputBytes?: number;
24
+ resource?: {
25
+ namespace: string;
26
+ operation: "search" | "get" | "action";
27
+ action?: string;
28
+ inputKey?: string;
29
+ };
22
30
  };
23
31
  export declare function transformSpotlightClientTools(code: string, id: string, onDescriptor?: (descriptor: BuildDescriptor) => void): {
24
32
  code: string;
@@ -1 +1 @@
1
- {"version":3,"file":"spotlightClientTools.d.ts","sourceRoot":"","sources":["../../src/vite/spotlightClientTools.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,MAAM,CAAC;AAGnC,MAAM,WAAW,2BAA2B;IAC1C,OAAO,CAAC,EAAE,MAAM,GAAG,MAAM,CAAC;IAC1B,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,eAAe,CAAC,EAAE,MAAM,CAAC;IACzB,gBAAgB,CAAC,EAAE,MAAM,CAAC;CAC3B;AAED,KAAK,UAAU,GAAG,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;AAyL1C,KAAK,QAAQ,GAAG,SAAS,GAAG,OAAO,GAAG,UAAU,GAAG,QAAQ,CAAC;AAE5D,KAAK,eAAe,GAAG;IACrB,IAAI,EAAE,MAAM,CAAC;IACb,OAAO,EAAE,MAAM,CAAC;IAChB,WAAW,EAAE,MAAM,CAAC;IACpB,WAAW,EAAE,UAAU,CAAC;IACxB,YAAY,CAAC,EAAE,UAAU,CAAC;IAC1B,IAAI,CAAC,EAAE,QAAQ,CAAC;IAChB,UAAU,EAAE,MAAM,GAAG,IAAI,GAAG,UAAU,CAAC;IACvC,YAAY,EAAE,MAAM,GAAG,iBAAiB,GAAG,OAAO,CAAC;IACnD,SAAS,EAAE,KAAK,GAAG,QAAQ,GAAG,MAAM,CAAC;IACrC,oBAAoB,EAAE,OAAO,CAAC;IAC9B,cAAc,CAAC,EAAE,MAAM,CAAC;CACzB,CAAC;AAkGF,wBAAgB,6BAA6B,CAC3C,IAAI,EAAE,MAAM,EACZ,EAAE,EAAE,MAAM,EACV,YAAY,CAAC,EAAE,CAAC,UAAU,EAAE,eAAe,KAAK,IAAI;;;SA4IrD;AAED,MAAM,CAAC,OAAO,UAAU,oBAAoB,CAC1C,OAAO,GAAE,2BAAgC,GACxC,M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F,wBAAgB,6BAA6B,CAC3C,IAAI,EAAE,MAAM,EACZ,EAAE,EAAE,MAAM,EACV,YAAY,CAAC,EAAE,CAAC,UAAU,EAAE,eAAe,KAAK,IAAI;;;SAsKrD;AAED,MAAM,CAAC,OAAO,UAAU,oBAAoB,CAC1C,OAAO,GAAE,2BAAgC,GACxC,MAAM,CA6DR"}
@@ -3,8 +3,7 @@ import traverseImport from "@babel/traverse";
3
3
  import * as t from "@babel/types";
4
4
  import MagicString from "magic-string";
5
5
  import { createHash } from "node:crypto";
6
- const traverseAst = (traverseImport.default ??
7
- traverseImport);
6
+ const traverseAst = (traverseImport.default ?? traverseImport);
8
7
  function literalSchema(node) {
9
8
  const value = node.literal;
10
9
  if (t.isStringLiteral(value))
@@ -125,7 +124,9 @@ function jsDoc(path) {
125
124
  ...(declaration?.leadingComments ?? []),
126
125
  ...(exportNode?.leadingComments ?? []),
127
126
  ];
128
- const comment = comments.reverse().find((item) => item.type === "CommentBlock");
127
+ const comment = comments
128
+ .reverse()
129
+ .find((item) => item.type === "CommentBlock");
129
130
  if (!comment)
130
131
  return "";
131
132
  return comment.value
@@ -135,7 +136,9 @@ function jsDoc(path) {
135
136
  .join(" ");
136
137
  }
137
138
  function staticJsonValue(node, path, seen = new Set()) {
138
- if (t.isStringLiteral(node) || t.isNumericLiteral(node) || t.isBooleanLiteral(node)) {
139
+ if (t.isStringLiteral(node) ||
140
+ t.isNumericLiteral(node) ||
141
+ t.isBooleanLiteral(node)) {
139
142
  return node.value;
140
143
  }
141
144
  if (t.isNullLiteral(node))
@@ -185,7 +188,9 @@ function shouldInclude(id, include) {
185
188
  const clean = id.split("?", 1)[0];
186
189
  if (!/\.[cm]?[jt]sx?$/.test(clean) || clean.includes("node_modules"))
187
190
  return false;
188
- return typeof include === "string" ? clean.includes(include) : include.test(clean);
191
+ return typeof include === "string"
192
+ ? clean.includes(include)
193
+ : include.test(clean);
189
194
  }
190
195
  function withTier(descriptor) {
191
196
  return { ...descriptor, tier: buildTier(descriptor) };
@@ -270,9 +275,159 @@ function stableJson(value) {
270
275
  }
271
276
  return JSON.stringify(value);
272
277
  }
278
+ function objectKey(property) {
279
+ if (property.computed)
280
+ return undefined;
281
+ if (t.isIdentifier(property.key))
282
+ return property.key.name;
283
+ if (t.isStringLiteral(property.key))
284
+ return property.key.value;
285
+ return undefined;
286
+ }
287
+ function objectProperty(object, name) {
288
+ return object.properties.find((property) => (t.isObjectProperty(property) || t.isObjectMethod(property)) &&
289
+ objectKey(property) === name);
290
+ }
291
+ function staticStringProperty(object, name, path, required = true) {
292
+ const property = objectProperty(object, name);
293
+ if (!property) {
294
+ if (required)
295
+ throw new Error(`${name} must be a string literal`);
296
+ return undefined;
297
+ }
298
+ if (!t.isObjectProperty(property)) {
299
+ throw new Error(`${name} must be a string literal`);
300
+ }
301
+ const value = staticJsonValue(property.value, path);
302
+ if (typeof value !== "string" || !value.trim()) {
303
+ throw new Error(`${name} must be a non-empty string literal`);
304
+ }
305
+ return value.trim();
306
+ }
307
+ function emitResourceProviderDescriptors(options, path, onDescriptor) {
308
+ let namespace;
309
+ let description;
310
+ try {
311
+ namespace = staticStringProperty(options, "namespace", path);
312
+ description = staticStringProperty(options, "description", path);
313
+ }
314
+ catch (error) {
315
+ throw path.buildCodeFrameError(`Cannot emit Resource Provider manifest: ${error instanceof Error ? error.message : String(error)}`);
316
+ }
317
+ const safeNamespace = namespace.replace(/[^a-zA-Z0-9_-]/gu, "_");
318
+ const base = {
319
+ namespace: safeNamespace,
320
+ version: "1.0.0",
321
+ riskLevel: "low",
322
+ requiresConfirmation: false,
323
+ };
324
+ onDescriptor?.({
325
+ ...base,
326
+ name: `${safeNamespace}_search`,
327
+ description: `Search ${description}. Use this for lists, discovery, status and ambiguous names.`,
328
+ inputSchema: {
329
+ type: "object",
330
+ properties: {
331
+ query: { type: "string" },
332
+ limit: { type: "integer", minimum: 1, maximum: 100 },
333
+ cursor: { type: "string" },
334
+ filters: { type: "object" },
335
+ },
336
+ additionalProperties: false,
337
+ },
338
+ tier: "query",
339
+ sideEffect: "none",
340
+ replayPolicy: "safe",
341
+ deferLoading: true,
342
+ resource: {
343
+ namespace: safeNamespace,
344
+ operation: "search",
345
+ inputKey: "query",
346
+ },
347
+ });
348
+ if (objectProperty(options, "get")) {
349
+ onDescriptor?.({
350
+ ...base,
351
+ name: `${safeNamespace}_get`,
352
+ description: `Get one ${description} resource by its stable id.`,
353
+ inputSchema: {
354
+ type: "object",
355
+ properties: { id: { type: "string", minLength: 1 } },
356
+ required: ["id"],
357
+ additionalProperties: false,
358
+ },
359
+ tier: "query",
360
+ sideEffect: "none",
361
+ replayPolicy: "safe",
362
+ deferLoading: true,
363
+ resource: {
364
+ namespace: safeNamespace,
365
+ operation: "get",
366
+ inputKey: "id",
367
+ },
368
+ });
369
+ }
370
+ const actionsProperty = objectProperty(options, "actions");
371
+ if (!actionsProperty || !t.isObjectProperty(actionsProperty))
372
+ return;
373
+ if (!t.isObjectExpression(actionsProperty.value)) {
374
+ throw path.buildCodeFrameError("Cannot emit Resource Provider manifest: actions must be an object literal");
375
+ }
376
+ for (const actionProperty of actionsProperty.value.properties) {
377
+ if (!t.isObjectProperty(actionProperty) ||
378
+ !t.isObjectExpression(actionProperty.value)) {
379
+ throw path.buildCodeFrameError("Cannot emit Resource Provider manifest: every action must be an object literal");
380
+ }
381
+ const action = objectKey(actionProperty);
382
+ if (!action) {
383
+ throw path.buildCodeFrameError("Cannot emit Resource Provider manifest: action keys must be static");
384
+ }
385
+ const definition = actionProperty.value;
386
+ let toolName;
387
+ let actionDescription;
388
+ let tier;
389
+ try {
390
+ toolName =
391
+ staticStringProperty(definition, "toolName", path, false) ??
392
+ `${safeNamespace}_${action}`;
393
+ actionDescription = staticStringProperty(definition, "description", path);
394
+ const declaredTier = staticStringProperty(definition, "tier", path, false);
395
+ if (declaredTier &&
396
+ !["observe", "query", "navigate"].includes(declaredTier)) {
397
+ throw new Error("resource action tier must be observe, query or navigate");
398
+ }
399
+ tier = declaredTier ?? "navigate";
400
+ }
401
+ catch (error) {
402
+ throw path.buildCodeFrameError(`Cannot emit Resource Provider action ${action}: ${error instanceof Error ? error.message : String(error)}`);
403
+ }
404
+ onDescriptor?.({
405
+ ...base,
406
+ name: toolName,
407
+ description: actionDescription,
408
+ inputSchema: {
409
+ type: "object",
410
+ properties: { query: { type: "string", minLength: 1 } },
411
+ required: ["query"],
412
+ additionalProperties: false,
413
+ },
414
+ tier,
415
+ sideEffect: "ui",
416
+ replayPolicy: "safe",
417
+ resource: {
418
+ namespace: safeNamespace,
419
+ operation: "action",
420
+ action,
421
+ inputKey: "query",
422
+ },
423
+ });
424
+ }
425
+ }
273
426
  export function transformSpotlightClientTools(code, id, onDescriptor) {
274
- if (!code.includes("defineClientTool"))
427
+ if (!code.includes("defineClientTool") &&
428
+ !code.includes("defineResourceProvider")) {
275
429
  return null;
430
+ }
276
431
  const ast = parse(code, {
277
432
  sourceType: "module",
278
433
  plugins: ["typescript", "jsx"],
@@ -284,6 +439,14 @@ export function transformSpotlightClientTools(code, id, onDescriptor) {
284
439
  if (!t.isIdentifier(path.node.id) || !t.isCallExpression(path.node.init))
285
440
  return;
286
441
  const call = path.node.init;
442
+ if (t.isIdentifier(call.callee, { name: "defineResourceProvider" })) {
443
+ const options = call.arguments[0];
444
+ if (!t.isObjectExpression(options)) {
445
+ throw path.buildCodeFrameError("defineResourceProvider options must be an object literal");
446
+ }
447
+ emitResourceProviderDescriptors(options, path, onDescriptor);
448
+ return;
449
+ }
287
450
  if (!t.isIdentifier(call.callee, { name: "defineClientTool" }))
288
451
  return;
289
452
  if (call.arguments.length < 1 || call.arguments.length > 2) {
@@ -405,7 +568,8 @@ export default function spotlightClientTools(options = {}) {
405
568
  name: "spotlight-client-tools",
406
569
  enforce: "pre",
407
570
  configResolved(config) {
408
- productionBuild = config.command === "build" && config.mode === "production";
571
+ productionBuild =
572
+ config.command === "build" && config.mode === "production";
409
573
  if (productionBuild &&
410
574
  (!options.projectId?.trim() || !options.frontendBuildId?.trim())) {
411
575
  throw new Error("spotlightClientTools: projectId and frontendBuildId are required for production builds");
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@inupedia/spotlight-client",
3
- "version": "0.7.7",
3
+ "version": "0.8.0",
4
4
  "description": "Build-described browser Client Tools and HTTP helpers for Inupedia Spotlight",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -33,7 +33,7 @@
33
33
  "@babel/types": "^7.28.5",
34
34
  "magic-string": "^0.30.21",
35
35
  "yaml": "^2.8.4",
36
- "@inupedia/spotlight-protocol": "0.7.7"
36
+ "@inupedia/spotlight-protocol": "0.8.0"
37
37
  },
38
38
  "peerDependencies": {
39
39
  "vite": "^5.0.0 || ^6.0.0 || ^7.0.0"