@bastani/atomic 0.9.35-alpha.3 → 0.9.35-alpha.4
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/CHANGELOG.md +26 -0
- package/dist/builtin/intercom/package.json +2 -2
- package/dist/builtin/mcp/package.json +1 -1
- package/dist/builtin/subagents/package.json +3 -3
- package/dist/builtin/web-access/package.json +2 -2
- package/dist/builtin/workflows/package.json +2 -2
- package/dist/codemode-worker.js +222 -78
- package/dist/config.d.ts +1 -0
- package/dist/config.d.ts.map +1 -1
- package/dist/config.js +1 -0
- package/dist/config.js.map +1 -1
- package/dist/core/extensions/loader-virtual-modules.d.ts.map +1 -1
- package/dist/core/extensions/loader-virtual-modules.js +2 -0
- package/dist/core/extensions/loader-virtual-modules.js.map +1 -1
- package/dist/core/model-runtime.d.ts.map +1 -1
- package/dist/core/model-runtime.js +11 -6
- package/dist/core/model-runtime.js.map +1 -1
- package/dist/core/remote-catalog-provider.d.ts +12 -1
- package/dist/core/remote-catalog-provider.d.ts.map +1 -1
- package/dist/core/remote-catalog-provider.js +85 -24
- package/dist/core/remote-catalog-provider.js.map +1 -1
- package/dist/core/tools/bash.d.ts +2 -6
- package/dist/core/tools/bash.d.ts.map +1 -1
- package/dist/core/tools/bash.js +9 -39
- package/dist/core/tools/bash.js.map +1 -1
- package/dist/core/tools/powershell.d.ts +2 -10
- package/dist/core/tools/powershell.d.ts.map +1 -1
- package/dist/core/tools/render-utils.d.ts +15 -0
- package/dist/core/tools/render-utils.d.ts.map +1 -1
- package/dist/core/tools/render-utils.js +46 -0
- package/dist/core/tools/render-utils.js.map +1 -1
- package/dist/extensions/codemode/execute.d.ts.map +1 -1
- package/dist/extensions/codemode/execute.js +2 -0
- package/dist/extensions/codemode/execute.js.map +1 -1
- package/dist/extensions/codemode/renderer.d.ts +7 -1
- package/dist/extensions/codemode/renderer.d.ts.map +1 -1
- package/dist/extensions/codemode/renderer.js +12 -1
- package/dist/extensions/codemode/renderer.js.map +1 -1
- package/dist/extensions/codemode/tool.d.ts.map +1 -1
- package/dist/extensions/codemode/tool.js +25 -12
- package/dist/extensions/codemode/tool.js.map +1 -1
- package/dist/extensions/mcp/tools.d.ts +2 -3
- package/dist/extensions/mcp/tools.d.ts.map +1 -1
- package/dist/extensions/mcp/tools.js +62 -6
- package/dist/extensions/mcp/tools.js.map +1 -1
- package/dist/modes/interactive/components/custom-editor.d.ts.map +1 -1
- package/dist/modes/interactive/components/custom-editor.js +2 -2
- package/dist/modes/interactive/components/custom-editor.js.map +1 -1
- package/dist/modes/interactive/components/settings-selector-items.js +1 -1
- package/dist/modes/interactive/components/settings-selector-items.js.map +1 -1
- package/dist/modes/interactive/components/tool-execution.d.ts.map +1 -1
- package/dist/modes/interactive/components/tool-execution.js +1 -0
- package/dist/modes/interactive/components/tool-execution.js.map +1 -1
- package/dist/utils/clipboard.d.ts.map +1 -1
- package/dist/utils/clipboard.js +10 -1
- package/dist/utils/clipboard.js.map +1 -1
- package/docs/codemode.md +2 -2
- package/docs/environment-variables.md +1 -0
- package/docs/getting-started/installation.md +1 -1
- package/docs/keybindings.md +1 -1
- package/docs/providers.md +20 -0
- package/docs/sdk.md +2 -6
- package/docs/settings.md +1 -1
- package/docs/tui/reference.md +5 -3
- package/examples/extensions/overlay-test.ts +2 -2
- package/npm-shrinkwrap.json +53 -550
- package/package.json +6 -12
- package/dist/client/index.d.ts +0 -2
- package/dist/client/index.d.ts.map +0 -1
- package/dist/client/index.js +0 -2
- package/dist/client/index.js.map +0 -1
|
@@ -64,13 +64,33 @@ function parseCatalog(providerId, value) {
|
|
|
64
64
|
.filter(hasOperationShape)
|
|
65
65
|
.map((model) => ({ ...model, provider: providerId }));
|
|
66
66
|
}
|
|
67
|
+
/** Read a successful pi.dev catalog response. A missing or invalid Last-Modified header is 0. */
|
|
68
|
+
async function readCatalog(providerId, response) {
|
|
69
|
+
const lastModified = Date.parse(response.headers.get("last-modified") ?? "");
|
|
70
|
+
return {
|
|
71
|
+
models: parseCatalog(providerId, await response.json()),
|
|
72
|
+
lastModified: Number.isNaN(lastModified) ? 0 : lastModified,
|
|
73
|
+
etag: response.headers.get("etag") ?? undefined,
|
|
74
|
+
};
|
|
75
|
+
}
|
|
76
|
+
/** Whether a pi.dev catalog is newer than the model data shipped with Atomic. */
|
|
77
|
+
function isNewer(lastModified, localGeneratedAt) {
|
|
78
|
+
return localGeneratedAt === undefined || (lastModified !== undefined && lastModified > localGeneratedAt);
|
|
79
|
+
}
|
|
67
80
|
function remoteModels(entry, localGeneratedAt) {
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
return
|
|
81
|
+
return entry && isNewer(entry.lastModified, localGeneratedAt) ? entry.models : [];
|
|
82
|
+
}
|
|
83
|
+
function requestCatalog(providerId, catalogBaseUrl, signal, validator) {
|
|
84
|
+
const url = new URL(`/api/models/providers/${encodeURIComponent(providerId)}`, catalogBaseUrl);
|
|
85
|
+
url.searchParams.set("types", REMOTE_CATALOG_MODEL_TYPES.join(","));
|
|
86
|
+
return fetchWithRetry(url, {
|
|
87
|
+
headers: {
|
|
88
|
+
accept: "application/json",
|
|
89
|
+
"User-Agent": getPiUserAgent(VERSION),
|
|
90
|
+
...(validator ? { "if-none-match": validator } : {}),
|
|
91
|
+
},
|
|
92
|
+
signal,
|
|
93
|
+
}, { attemptTimeoutMs: REMOTE_CATALOG_ATTEMPT_TIMEOUT_MS });
|
|
74
94
|
}
|
|
75
95
|
/** Add a persisted pi.dev catalog overlay to a static built-in provider. */
|
|
76
96
|
export function withRemoteCatalog(provider, catalogBaseUrl = DEFAULT_CATALOG_BASE_URL, localGeneratedAt) {
|
|
@@ -98,6 +118,9 @@ export function withRemoteCatalog(provider, catalogBaseUrl = DEFAULT_CATALOG_BAS
|
|
|
98
118
|
}
|
|
99
119
|
if (!context.allowNetwork || context.signal.aborted)
|
|
100
120
|
return;
|
|
121
|
+
// Skip the request if pi.dev was checked less than REMOTE_CATALOG_REFRESH_INTERVAL_MS ago.
|
|
122
|
+
// An entry without lastModified (saved by an older version, or after a failed first request) is
|
|
123
|
+
// always refetched: remoteModels() ignores it, so waiting would leave the overlay empty.
|
|
101
124
|
if (!context.force &&
|
|
102
125
|
stored?.checkedAt !== undefined &&
|
|
103
126
|
stored.lastModified !== undefined &&
|
|
@@ -107,16 +130,7 @@ export function withRemoteCatalog(provider, catalogBaseUrl = DEFAULT_CATALOG_BAS
|
|
|
107
130
|
// Only revalidate when a cached body backs the validator, so a 304 can never
|
|
108
131
|
// leave the overlay empty.
|
|
109
132
|
const validator = stored && stored.models.length > 0 ? stored.etag : undefined;
|
|
110
|
-
const
|
|
111
|
-
url.searchParams.set("types", REMOTE_CATALOG_MODEL_TYPES.join(","));
|
|
112
|
-
const response = await fetchWithRetry(url, {
|
|
113
|
-
headers: {
|
|
114
|
-
accept: "application/json",
|
|
115
|
-
"User-Agent": getPiUserAgent(VERSION),
|
|
116
|
-
...(validator ? { "if-none-match": validator } : {}),
|
|
117
|
-
},
|
|
118
|
-
signal: context.signal,
|
|
119
|
-
}, { attemptTimeoutMs: REMOTE_CATALOG_ATTEMPT_TIMEOUT_MS });
|
|
133
|
+
const response = await requestCatalog(provider.id, catalogBaseUrl, context.signal, validator);
|
|
120
134
|
if (context.signal.aborted)
|
|
121
135
|
return;
|
|
122
136
|
const checkedAt = Date.now();
|
|
@@ -143,16 +157,10 @@ export function withRemoteCatalog(provider, catalogBaseUrl = DEFAULT_CATALOG_BAS
|
|
|
143
157
|
await context.publish({ persist: { ...(stored ?? { models: [] }), checkedAt } });
|
|
144
158
|
throw new Error(`Model catalog request failed for ${provider.id}: ${response.status}`);
|
|
145
159
|
}
|
|
146
|
-
const
|
|
147
|
-
const lastModified = Date.parse(response.headers.get("last-modified") ?? "");
|
|
160
|
+
const catalog = await readCatalog(provider.id, response);
|
|
148
161
|
if (context.signal.aborted)
|
|
149
162
|
return;
|
|
150
|
-
const entry = {
|
|
151
|
-
models: refreshed,
|
|
152
|
-
checkedAt,
|
|
153
|
-
lastModified: Number.isNaN(lastModified) ? 0 : lastModified,
|
|
154
|
-
etag: response.headers.get("etag") ?? undefined,
|
|
155
|
-
};
|
|
163
|
+
const entry = { ...catalog, checkedAt };
|
|
156
164
|
const published = remoteModels(entry, localGeneratedAt);
|
|
157
165
|
await context.publish({
|
|
158
166
|
persist: entry,
|
|
@@ -163,4 +171,57 @@ export function withRemoteCatalog(provider, catalogBaseUrl = DEFAULT_CATALOG_BAS
|
|
|
163
171
|
},
|
|
164
172
|
};
|
|
165
173
|
}
|
|
174
|
+
/**
|
|
175
|
+
* Like `withRemoteCatalog`, but on each network refresh the catalog (built-in models plus a newer
|
|
176
|
+
* pi.dev catalog) is passed through `personalize` and the result is saved. The saved entry holds
|
|
177
|
+
* the personalized list, not the pi.dev catalog, and replaces the catalog, including offline.
|
|
178
|
+
* The refresh interval and etag revalidation are skipped. An empty list (nothing saved yet, or an
|
|
179
|
+
* empty catalog saved by an older version after a failed or missing pi.dev catalog) falls back to
|
|
180
|
+
* the built-in models.
|
|
181
|
+
*/
|
|
182
|
+
export function withPersonalizedCatalog(provider, personalize, catalogBaseUrl = DEFAULT_CATALOG_BASE_URL, localGeneratedAt) {
|
|
183
|
+
let personalModels = [];
|
|
184
|
+
const builtinModels = () => provider.getAllModels?.() ?? provider.getModels();
|
|
185
|
+
const getAllModels = () => (personalModels.length > 0 ? personalModels : builtinModels());
|
|
186
|
+
return {
|
|
187
|
+
...provider,
|
|
188
|
+
getModels: () => getAllModels().filter((model) => isModelType(model, "chat")),
|
|
189
|
+
getAllModels,
|
|
190
|
+
refreshModels: async (context) => {
|
|
191
|
+
const restored = (context.stored?.models ?? []).filter((model) => model.provider === provider.id && hasOperationShape(model));
|
|
192
|
+
if (!(await context.publish({
|
|
193
|
+
update: () => {
|
|
194
|
+
personalModels = restored;
|
|
195
|
+
},
|
|
196
|
+
}))) {
|
|
197
|
+
return;
|
|
198
|
+
}
|
|
199
|
+
if (!context.allowNetwork || context.signal.aborted)
|
|
200
|
+
return;
|
|
201
|
+
let remote = [];
|
|
202
|
+
try {
|
|
203
|
+
const response = await requestCatalog(provider.id, catalogBaseUrl, context.signal);
|
|
204
|
+
if (response.ok) {
|
|
205
|
+
const catalog = await readCatalog(provider.id, response);
|
|
206
|
+
if (isNewer(catalog.lastModified, localGeneratedAt))
|
|
207
|
+
remote = catalog.models;
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
catch {
|
|
211
|
+
remote = [];
|
|
212
|
+
}
|
|
213
|
+
if (context.signal.aborted)
|
|
214
|
+
return;
|
|
215
|
+
const personalized = await personalize(mergeModels(builtinModels(), remote), context);
|
|
216
|
+
if (context.signal.aborted)
|
|
217
|
+
return;
|
|
218
|
+
await context.publish({
|
|
219
|
+
persist: { models: personalized, checkedAt: Date.now() },
|
|
220
|
+
update: () => {
|
|
221
|
+
personalModels = personalized;
|
|
222
|
+
},
|
|
223
|
+
});
|
|
224
|
+
},
|
|
225
|
+
};
|
|
226
|
+
}
|
|
166
227
|
//# sourceMappingURL=remote-catalog-provider.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"remote-catalog-provider.js","sourceRoot":"","sources":["../../src/core/remote-catalog-provider.ts"],"names":[],"mappings":"AAAA,OAAO,EAEN,YAAY,EACZ,WAAW,GAIX,MAAM,gBAAgB,CAAC;AACxB,OAAO,EAAE,OAAO,EAAE,MAAM,cAAc,CAAC;AACvC,OAAO,EAAE,cAAc,EAAE,MAAM,6BAA6B,CAAC;AAC7D,OAAO,EAAE,cAAc,EAAE,MAAM,2BAA2B,CAAC;AAE3D,MAAM,wBAAwB,GAAG,gBAAgB,CAAC;AAClD,MAAM,iCAAiC,GAAG,KAAK,CAAC;AAChD,MAAM,CAAC,MAAM,kCAAkC,GAAG,CAAC,GAAG,EAAE,GAAG,EAAE,GAAG,IAAI,CAAC;AACrE;;;;;GAKG;AACH,MAAM,CAAC,MAAM,0BAA0B,GAAyB,CAAC,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i-ai\";\nimport { VERSION } from \"../config.js\";\nimport { fetchWithRetry } from \"../utils/management-http.ts\";\nimport { getPiUserAgent } from \"../utils/pi-user-agent.ts\";\n\nconst DEFAULT_CATALOG_BASE_URL = \"https://pi.dev\";\nconst REMOTE_CATALOG_ATTEMPT_TIMEOUT_MS = 4_000;\nexport const REMOTE_CATALOG_REFRESH_INTERVAL_MS = 4 * 60 * 60 * 1000;\n/**\n * Model types this client can consume. Sent as `?types=` so the catalog server\n * returns the full-type shard instead of the chat-only one served to clients\n * that predate model types. A server that ignores the parameter still returns\n * the chat-only shard, which this client handles unchanged.\n */\nexport const REMOTE_CATALOG_MODEL_TYPES: readonly ModelType[] = [\"chat\", \"image\", \"classifier\"];\n\nfunction isSupportedModelType(model: { type?: unknown }): boolean {\n\treturn (\n\t\tmodel.type === undefined ||\n\t\t(typeof model.type === \"string\" && REMOTE_CATALOG_MODEL_TYPES.includes(model.type as ModelType))\n\t);\n}\n\nfunction hasOperationShape(model: unknown): boolean {\n\tif (typeof model !== \"object\" || model === null) return false;\n\tif (!(\"type\" in model) || (model.type !== \"image\" && model.type !== \"classifier\")) return true;\n\tif (!(\"cost\" in model)) return false;\n\tconst cost = model.cost;\n\treturn (\n\t\t\"id\" in model &&\n\t\ttypeof model.id === \"string\" &&\n\t\tmodel.id.length > 0 &&\n\t\t\"name\" in model &&\n\t\ttypeof model.name === \"string\" &&\n\t\t\"api\" in model &&\n\t\ttypeof model.api === \"string\" &&\n\t\t\"baseUrl\" in model &&\n\t\ttypeof model.baseUrl === \"string\" &&\n\t\t\"input\" in model &&\n\t\tArray.isArray(model.input) &&\n\t\tcost !== null &&\n\t\ttypeof cost === \"object\" &&\n\t\t[\"input\", \"output\", \"cacheRead\", \"cacheWrite\"].every(\n\t\t\t(key) => key in cost && typeof (cost as Record<string, unknown>)[key] === \"number\",\n\t\t) &&\n\t\t(model.type === \"image\"\n\t\t\t? \"output\" in model && Array.isArray(model.output) && model.output.includes(\"image\")\n\t\t\t: \"contextWindow\" in model && typeof model.contextWindow === \"number\" && model.contextWindow > 0)\n\t);\n}\n\nfunction mergeModels<TModel extends AnyModel>(baseline: readonly TModel[], dynamic: readonly TModel[]): TModel[] {\n\tconst merged = new Map<string, TModel>();\n\tfor (const model of [...baseline, ...dynamic]) merged.set(`${getModelType(model)}\\0${model.id}`, model);\n\treturn [...merged.values()];\n}\n\nfunction parseCatalog(providerId: string, value: unknown): AnyModel[] {\n\tconst entries = Array.isArray(value)\n\t\t? value\n\t\t: typeof value === \"object\" && value !== null && \"models\" in value && Array.isArray(value.models)\n\t\t\t? value.models\n\t\t\t: typeof value === \"object\" && value !== null\n\t\t\t\t? Object.values(value)\n\t\t\t\t: undefined;\n\tif (!entries) throw new Error(`Invalid model catalog for provider \"${providerId}\"`);\n\treturn entries\n\t\t.filter((entry): entry is Record<string, unknown> => typeof entry === \"object\" && entry !== null && \"id\" in entry)\n\t\t.filter(isSupportedModelType)\n\t\t.filter(hasOperationShape)\n\t\t.map((model) => ({ ...model, provider: providerId }) as AnyModel);\n}\n\nfunction remoteModels(entry: ModelsStoreEntry | undefined, localGeneratedAt: number | undefined): readonly AnyModel[] {\n\tif (!entry) return [];\n\tif (localGeneratedAt !== undefined && (entry.lastModified === undefined || entry.lastModified <= localGeneratedAt)) {\n\t\treturn [];\n\t}\n\treturn entry.models;\n}\n\n/** Add a persisted pi.dev catalog overlay to a static built-in provider. */\nexport function withRemoteCatalog(\n\tprovider: Provider,\n\tcatalogBaseUrl: string = DEFAULT_CATALOG_BASE_URL,\n\tlocalGeneratedAt?: number,\n): Provider {\n\tconst models = provider.getAllModels?.() ?? provider.getModels();\n\tif (models.length > 0 && !models.some(isSupportedModelType)) return provider;\n\n\tlet dynamicModels: readonly AnyModel[] = [];\n\n\treturn {\n\t\t...provider,\n\t\tgetModels: () =>\n\t\t\tmergeModels(\n\t\t\t\tprovider.getModels(),\n\t\t\t\tdynamicModels.filter((model) => isModelType(model, \"chat\")),\n\t\t\t),\n\t\tgetAllModels: () => mergeModels(provider.getAllModels?.() ?? provider.getModels(), dynamicModels),\n\t\trefreshModels: async (context) => {\n\t\t\t// 0.84.1 hands the snapshot in directly and coalesces concurrent refreshes\n\t\t\t// itself, so the old inflight-promise dedup is gone. Every mutation of\n\t\t\t// dynamicModels now runs inside a generation-checked publish; a false return\n\t\t\t// means a newer refresh already superseded this pass, so it must not continue.\n\t\t\tconst stored = context.stored;\n\t\t\tconst restored = remoteModels(stored, localGeneratedAt).filter(\n\t\t\t\t(model) => model.provider === provider.id && hasOperationShape(model),\n\t\t\t);\n\t\t\tif (\n\t\t\t\t!(await context.publish({\n\t\t\t\t\tupdate: () => {\n\t\t\t\t\t\tdynamicModels = restored;\n\t\t\t\t\t},\n\t\t\t\t}))\n\t\t\t) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (!context.allowNetwork || context.signal.aborted) return;\n\t\t\tif (\n\t\t\t\t!context.force &&\n\t\t\t\tstored?.checkedAt !== undefined &&\n\t\t\t\tstored.lastModified !== undefined &&\n\t\t\t\tDate.now() - stored.checkedAt < REMOTE_CATALOG_REFRESH_INTERVAL_MS\n\t\t\t) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t// Only revalidate when a cached body backs the validator, so a 304 can never\n\t\t\t// leave the overlay empty.\n\t\t\tconst validator = stored && stored.models.length > 0 ? stored.etag : undefined;\n\t\t\tconst url = new URL(`/api/models/providers/${encodeURIComponent(provider.id)}`, catalogBaseUrl);\n\t\t\turl.searchParams.set(\"types\", REMOTE_CATALOG_MODEL_TYPES.join(\",\"));\n\t\t\tconst response = await fetchWithRetry(\n\t\t\t\turl,\n\t\t\t\t{\n\t\t\t\t\theaders: {\n\t\t\t\t\t\taccept: \"application/json\",\n\t\t\t\t\t\t\"User-Agent\": getPiUserAgent(VERSION),\n\t\t\t\t\t\t...(validator ? { \"if-none-match\": validator } : {}),\n\t\t\t\t\t},\n\t\t\t\t\tsignal: context.signal,\n\t\t\t\t},\n\t\t\t\t{ attemptTimeoutMs: REMOTE_CATALOG_ATTEMPT_TIMEOUT_MS },\n\t\t\t);\n\t\t\tif (context.signal.aborted) return;\n\t\t\tconst checkedAt = Date.now();\n\t\t\t// Unchanged: dynamicModels already holds the stored overlay, so only the\n\t\t\t// freshness window moves.\n\t\t\tif (response.status === 304 && stored) {\n\t\t\t\tawait context.publish({ persist: { ...stored, checkedAt } });\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (response.status === 404 || response.status === 501) {\n\t\t\t\tawait context.publish({\n\t\t\t\t\tpersist: {\n\t\t\t\t\t\t...(stored ?? { models: [] }),\n\t\t\t\t\t\tcheckedAt,\n\t\t\t\t\t\tlastModified: 0,\n\t\t\t\t\t\tetag: undefined,\n\t\t\t\t\t},\n\t\t\t\t});\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (!response.ok) {\n\t\t\t\t// Transient failure: the cached body and its validator stay valid, so keep the\n\t\t\t\t// etag and let the next refresh revalidate instead of downloading the catalog.\n\t\t\t\tawait context.publish({ persist: { ...(stored ?? { models: [] }), checkedAt } });\n\t\t\t\tthrow new Error(`Model catalog request failed for ${provider.id}: ${response.status}`);\n\t\t\t}\n\t\t\tconst refreshed = parseCatalog(provider.id, await response.json());\n\t\t\tconst lastModified = Date.parse(response.headers.get(\"last-modified\") ?? \"\");\n\t\t\tif (context.signal.aborted) return;\n\t\t\tconst entry: ModelsStoreEntry = {\n\t\t\t\tmodels: refreshed,\n\t\t\t\tcheckedAt,\n\t\t\t\tlastModified: Number.isNaN(lastModified) ? 0 : lastModified,\n\t\t\t\tetag: response.headers.get(\"etag\") ?? undefined,\n\t\t\t};\n\t\t\tconst published = remoteModels(entry, localGeneratedAt);\n\t\t\tawait context.publish({\n\t\t\t\tpersist: entry,\n\t\t\t\tupdate: () => {\n\t\t\t\t\tdynamicModels = published;\n\t\t\t\t},\n\t\t\t});\n\t\t},\n\t};\n}\n"]}
|
|
1
|
+
{"version":3,"file":"remote-catalog-provider.js","sourceRoot":"","sources":["../../src/core/remote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,CAAC,WAAW,CAAC,aAAa,EAAE,EAAE,MAAM,CAAC,EAAE,OAAO,CAAC,CAAC;YACtF,IAAI,OAAO,CAAC,MAAM,CAAC,OAAO;gBAAE,OAAO;YACnC,MAAM,OAAO,CAAC,OAAO,CAAC;gBACrB,OAAO,EAAE,EAAE,MAAM,EAAE,YAAY,EAAE,SAAS,EAAE,IAAI,CAAC,GAAG,EAAE,EAAE;gBACxD,MAAM,EAAE,GAAG,EAAE;oBACZ,cAAc,GAAG,YAAY,CAAC;gBAC/B,CAAC;aACD,CAAC,CAAC;QACJ,CAAC;KACD,CAAC;AACH,CAAC","sourcesContent":["import {\n\ttype AnyModel,\n\tgetModelType,\n\tisModelType,\n\ttype ModelsStoreEntry,\n\ttype ModelType,\n\ttype Provider,\n\ttype RefreshModelsContext,\n} from \"@bastani/pi-ai\";\nimport { VERSION } from \"../config.js\";\nimport { fetchWithRetry } from \"../utils/management-http.ts\";\nimport { getPiUserAgent } from \"../utils/pi-user-agent.ts\";\n\nconst DEFAULT_CATALOG_BASE_URL = \"https://pi.dev\";\nconst REMOTE_CATALOG_ATTEMPT_TIMEOUT_MS = 4_000;\nexport const REMOTE_CATALOG_REFRESH_INTERVAL_MS = 4 * 60 * 60 * 1000;\n/**\n * Model types this client can consume. Sent as `?types=` so the catalog server\n * returns the full-type shard instead of the chat-only one served to clients\n * that predate model types. A server that ignores the parameter still returns\n * the chat-only shard, which this client handles unchanged.\n */\nexport const REMOTE_CATALOG_MODEL_TYPES: readonly ModelType[] = [\"chat\", \"image\", \"classifier\"];\n\nfunction isSupportedModelType(model: { type?: unknown }): boolean {\n\treturn (\n\t\tmodel.type === undefined ||\n\t\t(typeof model.type === \"string\" && REMOTE_CATALOG_MODEL_TYPES.includes(model.type as ModelType))\n\t);\n}\n\nfunction hasOperationShape(model: unknown): boolean {\n\tif (typeof model !== \"object\" || model === null) return false;\n\tif (!(\"type\" in model) || (model.type !== \"image\" && model.type !== \"classifier\")) return true;\n\tif (!(\"cost\" in model)) return false;\n\tconst cost = model.cost;\n\treturn (\n\t\t\"id\" in model &&\n\t\ttypeof model.id === \"string\" &&\n\t\tmodel.id.length > 0 &&\n\t\t\"name\" in model &&\n\t\ttypeof model.name === \"string\" &&\n\t\t\"api\" in model &&\n\t\ttypeof model.api === \"string\" &&\n\t\t\"baseUrl\" in model &&\n\t\ttypeof model.baseUrl === \"string\" &&\n\t\t\"input\" in model &&\n\t\tArray.isArray(model.input) &&\n\t\tcost !== null &&\n\t\ttypeof cost === \"object\" &&\n\t\t[\"input\", \"output\", \"cacheRead\", \"cacheWrite\"].every(\n\t\t\t(key) => key in cost && typeof (cost as Record<string, unknown>)[key] === \"number\",\n\t\t) &&\n\t\t(model.type === \"image\"\n\t\t\t? \"output\" in model && Array.isArray(model.output) && model.output.includes(\"image\")\n\t\t\t: \"contextWindow\" in model && typeof model.contextWindow === \"number\" && model.contextWindow > 0)\n\t);\n}\n\nfunction mergeModels<TModel extends AnyModel>(baseline: readonly TModel[], dynamic: readonly TModel[]): TModel[] {\n\tconst merged = new Map<string, TModel>();\n\tfor (const model of [...baseline, ...dynamic]) merged.set(`${getModelType(model)}\\0${model.id}`, model);\n\treturn [...merged.values()];\n}\n\nfunction parseCatalog(providerId: string, value: unknown): AnyModel[] {\n\tconst entries = Array.isArray(value)\n\t\t? value\n\t\t: typeof value === \"object\" && value !== null && \"models\" in value && Array.isArray(value.models)\n\t\t\t? value.models\n\t\t\t: typeof value === \"object\" && value !== null\n\t\t\t\t? Object.values(value)\n\t\t\t\t: undefined;\n\tif (!entries) throw new Error(`Invalid model catalog for provider \"${providerId}\"`);\n\treturn entries\n\t\t.filter((entry): entry is Record<string, unknown> => typeof entry === \"object\" && entry !== null && \"id\" in entry)\n\t\t.filter(isSupportedModelType)\n\t\t.filter(hasOperationShape)\n\t\t.map((model) => ({ ...model, provider: providerId }) as AnyModel);\n}\n\n/** Read a successful pi.dev catalog response. A missing or invalid Last-Modified header is 0. */\nasync function readCatalog(\n\tproviderId: string,\n\tresponse: Response,\n): Promise<{ models: AnyModel[]; lastModified: number; etag: string | undefined }> {\n\tconst lastModified = Date.parse(response.headers.get(\"last-modified\") ?? \"\");\n\treturn {\n\t\tmodels: parseCatalog(providerId, await response.json()),\n\t\tlastModified: Number.isNaN(lastModified) ? 0 : lastModified,\n\t\tetag: response.headers.get(\"etag\") ?? undefined,\n\t};\n}\n\n/** Whether a pi.dev catalog is newer than the model data shipped with Atomic. */\nfunction isNewer(lastModified: number | undefined, localGeneratedAt: number | undefined): boolean {\n\treturn localGeneratedAt === undefined || (lastModified !== undefined && lastModified > localGeneratedAt);\n}\n\nfunction remoteModels(entry: ModelsStoreEntry | undefined, localGeneratedAt: number | undefined): readonly AnyModel[] {\n\treturn entry && isNewer(entry.lastModified, localGeneratedAt) ? entry.models : [];\n}\n\nfunction requestCatalog(\n\tproviderId: string,\n\tcatalogBaseUrl: string,\n\tsignal: AbortSignal,\n\tvalidator?: string,\n): Promise<Response> {\n\tconst url = new URL(`/api/models/providers/${encodeURIComponent(providerId)}`, catalogBaseUrl);\n\turl.searchParams.set(\"types\", REMOTE_CATALOG_MODEL_TYPES.join(\",\"));\n\treturn fetchWithRetry(\n\t\turl,\n\t\t{\n\t\t\theaders: {\n\t\t\t\taccept: \"application/json\",\n\t\t\t\t\"User-Agent\": getPiUserAgent(VERSION),\n\t\t\t\t...(validator ? { \"if-none-match\": validator } : {}),\n\t\t\t},\n\t\t\tsignal,\n\t\t},\n\t\t{ attemptTimeoutMs: REMOTE_CATALOG_ATTEMPT_TIMEOUT_MS },\n\t);\n}\n\n/** Replaces the catalog with a credential-specific model list. */\nexport type PersonalizeCatalog = (\n\tcatalog: readonly AnyModel[],\n\tcontext: RefreshModelsContext,\n) => Promise<readonly AnyModel[]>;\n\n/** Add a persisted pi.dev catalog overlay to a static built-in provider. */\nexport function withRemoteCatalog(\n\tprovider: Provider,\n\tcatalogBaseUrl: string = DEFAULT_CATALOG_BASE_URL,\n\tlocalGeneratedAt?: number,\n): Provider {\n\tconst models = provider.getAllModels?.() ?? provider.getModels();\n\tif (models.length > 0 && !models.some(isSupportedModelType)) return provider;\n\n\tlet dynamicModels: readonly AnyModel[] = [];\n\n\treturn {\n\t\t...provider,\n\t\tgetModels: () =>\n\t\t\tmergeModels(\n\t\t\t\tprovider.getModels(),\n\t\t\t\tdynamicModels.filter((model) => isModelType(model, \"chat\")),\n\t\t\t),\n\t\tgetAllModels: () => mergeModels(provider.getAllModels?.() ?? provider.getModels(), dynamicModels),\n\t\trefreshModels: async (context) => {\n\t\t\t// 0.84.1 hands the snapshot in directly and coalesces concurrent refreshes\n\t\t\t// itself, so the old inflight-promise dedup is gone. Every mutation of\n\t\t\t// dynamicModels now runs inside a generation-checked publish; a false return\n\t\t\t// means a newer refresh already superseded this pass, so it must not continue.\n\t\t\tconst stored = context.stored;\n\t\t\tconst restored = remoteModels(stored, localGeneratedAt).filter(\n\t\t\t\t(model) => model.provider === provider.id && hasOperationShape(model),\n\t\t\t);\n\t\t\tif (\n\t\t\t\t!(await context.publish({\n\t\t\t\t\tupdate: () => {\n\t\t\t\t\t\tdynamicModels = restored;\n\t\t\t\t\t},\n\t\t\t\t}))\n\t\t\t) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (!context.allowNetwork || context.signal.aborted) return;\n\t\t\t// Skip the request if pi.dev was checked less than REMOTE_CATALOG_REFRESH_INTERVAL_MS ago.\n\t\t\t// An entry without lastModified (saved by an older version, or after a failed first request) is\n\t\t\t// always refetched: remoteModels() ignores it, so waiting would leave the overlay empty.\n\t\t\tif (\n\t\t\t\t!context.force &&\n\t\t\t\tstored?.checkedAt !== undefined &&\n\t\t\t\tstored.lastModified !== undefined &&\n\t\t\t\tDate.now() - stored.checkedAt < REMOTE_CATALOG_REFRESH_INTERVAL_MS\n\t\t\t) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t// Only revalidate when a cached body backs the validator, so a 304 can never\n\t\t\t// leave the overlay empty.\n\t\t\tconst validator = stored && stored.models.length > 0 ? stored.etag : undefined;\n\t\t\tconst response = await requestCatalog(provider.id, catalogBaseUrl, context.signal, validator);\n\t\t\tif (context.signal.aborted) return;\n\t\t\tconst checkedAt = Date.now();\n\t\t\t// Unchanged: dynamicModels already holds the stored overlay, so only the\n\t\t\t// freshness window moves.\n\t\t\tif (response.status === 304 && stored) {\n\t\t\t\tawait context.publish({ persist: { ...stored, checkedAt } });\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (response.status === 404 || response.status === 501) {\n\t\t\t\tawait context.publish({\n\t\t\t\t\tpersist: {\n\t\t\t\t\t\t...(stored ?? { models: [] }),\n\t\t\t\t\t\tcheckedAt,\n\t\t\t\t\t\tlastModified: 0,\n\t\t\t\t\t\tetag: undefined,\n\t\t\t\t\t},\n\t\t\t\t});\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (!response.ok) {\n\t\t\t\t// Transient failure: the cached body and its validator stay valid, so keep the\n\t\t\t\t// etag and let the next refresh revalidate instead of downloading the catalog.\n\t\t\t\tawait context.publish({ persist: { ...(stored ?? { models: [] }), checkedAt } });\n\t\t\t\tthrow new Error(`Model catalog request failed for ${provider.id}: ${response.status}`);\n\t\t\t}\n\t\t\tconst catalog = await readCatalog(provider.id, response);\n\t\t\tif (context.signal.aborted) return;\n\t\t\tconst entry: ModelsStoreEntry = { ...catalog, checkedAt };\n\t\t\tconst published = remoteModels(entry, localGeneratedAt);\n\t\t\tawait context.publish({\n\t\t\t\tpersist: entry,\n\t\t\t\tupdate: () => {\n\t\t\t\t\tdynamicModels = published;\n\t\t\t\t},\n\t\t\t});\n\t\t},\n\t};\n}\n\n/**\n * Like `withRemoteCatalog`, but on each network refresh the catalog (built-in models plus a newer\n * pi.dev catalog) is passed through `personalize` and the result is saved. The saved entry holds\n * the personalized list, not the pi.dev catalog, and replaces the catalog, including offline.\n * The refresh interval and etag revalidation are skipped. An empty list (nothing saved yet, or an\n * empty catalog saved by an older version after a failed or missing pi.dev catalog) falls back to\n * the built-in models.\n */\nexport function withPersonalizedCatalog(\n\tprovider: Provider,\n\tpersonalize: PersonalizeCatalog,\n\tcatalogBaseUrl: string = DEFAULT_CATALOG_BASE_URL,\n\tlocalGeneratedAt?: number,\n): Provider {\n\tlet personalModels: readonly AnyModel[] = [];\n\tconst builtinModels = (): readonly AnyModel[] => provider.getAllModels?.() ?? provider.getModels();\n\tconst getAllModels = (): readonly AnyModel[] => (personalModels.length > 0 ? personalModels : builtinModels());\n\n\treturn {\n\t\t...provider,\n\t\tgetModels: () => getAllModels().filter((model) => isModelType(model, \"chat\")),\n\t\tgetAllModels,\n\t\trefreshModels: async (context) => {\n\t\t\tconst restored = (context.stored?.models ?? []).filter(\n\t\t\t\t(model) => model.provider === provider.id && hasOperationShape(model),\n\t\t\t);\n\t\t\tif (\n\t\t\t\t!(await context.publish({\n\t\t\t\t\tupdate: () => {\n\t\t\t\t\t\tpersonalModels = restored;\n\t\t\t\t\t},\n\t\t\t\t}))\n\t\t\t) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (!context.allowNetwork || context.signal.aborted) return;\n\n\t\t\tlet remote: readonly AnyModel[] = [];\n\t\t\ttry {\n\t\t\t\tconst response = await requestCatalog(provider.id, catalogBaseUrl, context.signal);\n\t\t\t\tif (response.ok) {\n\t\t\t\t\tconst catalog = await readCatalog(provider.id, response);\n\t\t\t\t\tif (isNewer(catalog.lastModified, localGeneratedAt)) remote = catalog.models;\n\t\t\t\t}\n\t\t\t} catch {\n\t\t\t\tremote = [];\n\t\t\t}\n\t\t\tif (context.signal.aborted) return;\n\t\t\tconst personalized = await personalize(mergeModels(builtinModels(), remote), context);\n\t\t\tif (context.signal.aborted) return;\n\t\t\tawait context.publish({\n\t\t\t\tpersist: { models: personalized, checkedAt: Date.now() },\n\t\t\t\tupdate: () => {\n\t\t\t\t\tpersonalModels = personalized;\n\t\t\t\t},\n\t\t\t});\n\t\t},\n\t};\n}\n"]}
|
|
@@ -5,6 +5,7 @@ import type { ToolDefinition } from "../extensions/types.ts";
|
|
|
5
5
|
import type { WaitPolicy } from "../tasks/contracts.js";
|
|
6
6
|
import { type BashInterceptorRule } from "./bash-interceptor.ts";
|
|
7
7
|
import { type SupervisedCommandOwner, type SupervisedCommandResult } from "./bash-pty-native.js";
|
|
8
|
+
import { type ToolTimerState } from "./render-utils.ts";
|
|
8
9
|
import { type TruncationResult } from "./truncate.ts";
|
|
9
10
|
declare const bashBaseSchema: Type.TObject<{
|
|
10
11
|
command: Type.TString;
|
|
@@ -103,12 +104,7 @@ export interface ShellToolPresentation {
|
|
|
103
104
|
tempFilePrefix: string;
|
|
104
105
|
}
|
|
105
106
|
export declare const BASH_SHELL_PRESENTATION: ShellToolPresentation;
|
|
106
|
-
|
|
107
|
-
startedAt: number | undefined;
|
|
108
|
-
endedAt: number | undefined;
|
|
109
|
-
interval: NodeJS.Timeout | undefined;
|
|
110
|
-
};
|
|
111
|
-
export declare function createBashToolDefinition(cwd: string, options?: BashToolOptions, presentation?: ShellToolPresentation): ToolDefinition<typeof bashSchema, BashToolDetails | undefined, BashRenderState>;
|
|
107
|
+
export declare function createBashToolDefinition(cwd: string, options?: BashToolOptions, presentation?: ShellToolPresentation): ToolDefinition<typeof bashSchema, BashToolDetails | undefined, ToolTimerState>;
|
|
112
108
|
export declare function createBashTool(cwd: string, options?: BashToolOptions): AgentTool<typeof bashSchema>;
|
|
113
109
|
export {};
|
|
114
110
|
//# sourceMappingURL=bash.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"bash.d.ts","sourceRoot":"","sources":["../../../src/core/tools/bash.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,+BAA+B,CAAC;AAG/D,OAAO,EAAE,KAAK,MAAM,EAAE,IAAI,EAAE,MAAM,SAAS,CAAC;AAa5C,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,qBAAqB,CAAC;AACtD,OAAO,KAAK,EAAoB,cAAc,EAA2B,MAAM,wBAAwB,CAAC;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MAAM,EAAE,MAAM,CAAC;IACf,4DAA4D;IAC5D,cAAc,EAAE,MAAM,CAAC;CACvB;AACD,eAAO,MAAM,uBAAuB,EAAE,qBAGrC,CAAC;AAqGF,wBAAgB,wBAAwB,CACvC,GAAG,EAAE,MAAM,EACX,OAAO,CAAC,EAAE,eAAe,EACzB,YAAY,GAAE,qBAA+C,GAC3D,cAAc,CAAC,OAAO,UAAU,EAAE,eAAe,GAAG,SAAS,EAAE,cAAc,CAAC,CAgThF;AACD,wBAAgB,cAAc,CAAC,GAAG,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,eAAe,GAAG,SAAS,CAAC,OAAO,UAAU,CAAC,CAEnG"}
|
package/dist/core/tools/bash.js
CHANGED
|
@@ -16,7 +16,7 @@ import { stripLeadingCdCommand } from "./bash-leading-cd.js";
|
|
|
16
16
|
import { executeNativePty, executeSupervisedCommand, validateBashWait, waitForSupervisedCommand, } from "./bash-pty-native.js";
|
|
17
17
|
import { applyBashSessionEnvironment, snapshotBashSessionEnvironment } from "./bash-session-environment.js";
|
|
18
18
|
import { OutputAccumulator } from "./output-accumulator.js";
|
|
19
|
-
import { getTextOutput, invalidArgText, str } from "./render-utils.js";
|
|
19
|
+
import { getTextOutput, invalidArgText, startToolTimer, str, toolTimerText, } from "./render-utils.js";
|
|
20
20
|
import { expandShellInternalUrls } from "./resource-selectors.js";
|
|
21
21
|
import { invalidateNativeSearchCache } from "./search-native.js";
|
|
22
22
|
import { wrapToolDefinition } from "./tool-definition-wrapper.js";
|
|
@@ -230,17 +230,6 @@ function bashResultToToolResult(result) {
|
|
|
230
230
|
const text = `${result.output || "(no output)"}${status ? `\n\n${status}` : ""}`;
|
|
231
231
|
return { content: [{ type: "text", text }], details };
|
|
232
232
|
}
|
|
233
|
-
function formatDuration(ms) {
|
|
234
|
-
const seconds = Math.max(0, ms) / 1000;
|
|
235
|
-
if (seconds < 60)
|
|
236
|
-
return `${seconds.toFixed(1)}s`;
|
|
237
|
-
const totalSeconds = Math.floor(seconds);
|
|
238
|
-
const minutes = Math.floor(totalSeconds / 60);
|
|
239
|
-
const remainder = totalSeconds % 60;
|
|
240
|
-
if (minutes < 60)
|
|
241
|
-
return `${minutes}m ${remainder}s`;
|
|
242
|
-
return `${Math.floor(minutes / 60)}h ${minutes % 60}m ${remainder}s`;
|
|
243
|
-
}
|
|
244
233
|
function formatBashCall(args, prompt) {
|
|
245
234
|
if (args?.action === "wait")
|
|
246
235
|
return theme.fg("toolTitle", theme.bold(`${prompt} wait ${str(args.id) ?? "..."}`));
|
|
@@ -250,7 +239,7 @@ function formatBashCall(args, prompt) {
|
|
|
250
239
|
const commandDisplay = command === null ? invalidArgText(theme) : command ? command : theme.fg("toolOutput", "...");
|
|
251
240
|
return theme.fg("toolTitle", theme.bold(`${prompt} ${commandDisplay}`)) + timeoutSuffix;
|
|
252
241
|
}
|
|
253
|
-
function rebuildBashResultRenderComponent(component, result, options, showImages,
|
|
242
|
+
function rebuildBashResultRenderComponent(component, result, options, showImages, timerText) {
|
|
254
243
|
component.clear();
|
|
255
244
|
let output = getTextOutput(result, showImages).trim();
|
|
256
245
|
const observation = result.details?.observation;
|
|
@@ -303,15 +292,8 @@ function rebuildBashResultRenderComponent(component, result, options, showImages
|
|
|
303
292
|
}
|
|
304
293
|
component.addChild(new Text(`\n${theme.fg("warning", `[${warnings.join(". ")}]`)}`, 0, 0));
|
|
305
294
|
}
|
|
306
|
-
if (
|
|
307
|
-
|
|
308
|
-
component.addChild(new Text(`\n${theme.fg("muted", `${label} ${formatDuration(durationMs)}`)}`, 0, 0));
|
|
309
|
-
}
|
|
310
|
-
else if (startedAt !== undefined) {
|
|
311
|
-
const label = options.isPartial ? "Elapsed" : observation?.kind === "yielded" ? "Observed for" : "Took";
|
|
312
|
-
const endTime = endedAt ?? Date.now();
|
|
313
|
-
component.addChild(new Text(`\n${theme.fg("muted", `${label} ${formatDuration(endTime - startedAt)}`)}`, 0, 0));
|
|
314
|
-
}
|
|
295
|
+
if (timerText)
|
|
296
|
+
component.addChild(new Text(`\n${theme.fg("muted", timerText)}`, 0, 0));
|
|
315
297
|
}
|
|
316
298
|
export function createBashToolDefinition(cwd, options, presentation = BASH_SHELL_PRESENTATION) {
|
|
317
299
|
const defaultOps = options?.operations ??
|
|
@@ -586,29 +568,17 @@ export function createBashToolDefinition(cwd, options, presentation = BASH_SHELL
|
|
|
586
568
|
}
|
|
587
569
|
},
|
|
588
570
|
renderCall(args, _theme, context) {
|
|
589
|
-
|
|
590
|
-
if (context.executionStarted && state.startedAt === undefined) {
|
|
591
|
-
state.startedAt = Date.now();
|
|
592
|
-
state.endedAt = undefined;
|
|
593
|
-
}
|
|
571
|
+
startToolTimer(context);
|
|
594
572
|
const text = context.lastComponent ?? new Text("", 0, 0);
|
|
595
573
|
text.setText(formatBashCall(args, presentation.prompt));
|
|
596
574
|
return text;
|
|
597
575
|
},
|
|
598
576
|
renderResult(result, options, _theme, context) {
|
|
599
|
-
|
|
600
|
-
|
|
601
|
-
|
|
602
|
-
}
|
|
603
|
-
if (!options.isPartial || context.isError) {
|
|
604
|
-
state.endedAt ??= Date.now();
|
|
605
|
-
if (state.interval) {
|
|
606
|
-
clearInterval(state.interval);
|
|
607
|
-
state.interval = undefined;
|
|
608
|
-
}
|
|
609
|
-
}
|
|
577
|
+
// A command yielded to the background is still running, so its row reports how long it was observed.
|
|
578
|
+
const finalLabel = result.details?.observation?.kind === "yielded" ? "Observed for" : "Took";
|
|
579
|
+
const timerText = toolTimerText(context, options.isPartial, finalLabel);
|
|
610
580
|
const component = context.lastComponent ?? new Container();
|
|
611
|
-
rebuildBashResultRenderComponent(component, result, options, context.showImages,
|
|
581
|
+
rebuildBashResultRenderComponent(component, result, options, context.showImages, timerText);
|
|
612
582
|
component.invalidate();
|
|
613
583
|
return component;
|
|
614
584
|
},
|