@thinkingai/ae-cli 6.1.42 → 6.1.43

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (114) hide show
  1. package/README.md +14 -4
  2. package/README.zh.md +14 -4
  3. package/bin/ae-cli.js +3 -0
  4. package/bin/heari/commander-LICENSE +22 -0
  5. package/bin/heari/engine.mjs +6136 -0
  6. package/bin/heari/package.json +6 -0
  7. package/bin/heari.mjs +29 -0
  8. package/cli-installation-guide.md +3 -5
  9. package/dist/{ai-monitor-E62FT3TT.js → ai-monitor-4VPHXQTL.js} +7 -6
  10. package/dist/ai-monitor.js +10 -9
  11. package/dist/{auth-SDK5OAGP.js → auth-RDSS2LUT.js} +18 -16
  12. package/dist/{automation-IMDCJUML.js → automation-VLIWG2XY.js} +5 -4
  13. package/dist/{capability-F6YWGPZZ.js → capability-CUOEIB5F.js} +5 -4
  14. package/dist/{chunk-KE5WGBXS.js → chunk-3DTMWDJX.js} +1 -1
  15. package/dist/{chunk-KAZ5FWPB.js → chunk-3FSYICDW.js} +6 -5
  16. package/dist/{chunk-ZK6KEGUR.js → chunk-3TV24AVQ.js} +10 -10
  17. package/dist/{chunk-DTODOQ6T.js → chunk-3U75VLCP.js} +1 -1
  18. package/dist/{chunk-N2QILIGH.js → chunk-4MOCV6HU.js} +1 -1
  19. package/dist/{chunk-M2OCZRVX.js → chunk-6VLHJKDD.js} +2 -2
  20. package/dist/{chunk-WG27BD67.js → chunk-7KBENPQF.js} +8 -16
  21. package/dist/{chunk-CDBW5RE6.js → chunk-BFSWGXM2.js} +3 -3
  22. package/dist/{chunk-UK7HQ4IL.js → chunk-CBNE2S44.js} +2 -2
  23. package/dist/{chunk-UWQXGF44.js → chunk-FEYZBUFQ.js} +4 -353
  24. package/dist/chunk-FKTVD63C.js +369 -0
  25. package/dist/{chunk-2H3SFJE3.js → chunk-FKVG7LOP.js} +5 -3
  26. package/dist/{chunk-GTENC5CO.js → chunk-IAZ4AMVY.js} +6 -4
  27. package/dist/{chunk-ZSKLELL7.js → chunk-LSELMDKQ.js} +2 -2
  28. package/dist/{chunk-2RORKIF6.js → chunk-NJGB4YOH.js} +2 -2
  29. package/dist/{chunk-L7MT53VM.js → chunk-PWG5IGCP.js} +1 -1
  30. package/dist/{chunk-DIYDOOBL.js → chunk-TFEGYB4X.js} +2 -2
  31. package/dist/{chunk-DZRQGI2Z.js → chunk-ZPAOEDK7.js} +5 -3
  32. package/dist/{compat-check-J5K3NO5G.js → compat-check-L3C7HCVG.js} +4 -3
  33. package/dist/{config-O3W6XLHO.js → config-LAF5MMYK.js} +6 -5
  34. package/dist/context-E4YKECC4.js +350 -0
  35. package/dist/{evaluation-OZM54MES.js → evaluation-I4IJ25CY.js} +4 -3
  36. package/dist/heari-cli-login.js +83 -0
  37. package/dist/index.js +42 -34
  38. package/dist/{memory-VPOPSU52.js → memory-Y7LPCRP4.js} +5 -4
  39. package/dist/{metadata-3GA2N27I.js → metadata-T6HYAU7E.js} +7 -6
  40. package/dist/{model-2F2354QP.js → model-2BNN72MN.js} +7 -6
  41. package/dist/{personal-semantic-preference-T2HFF2V4.js → personal-semantic-preference-WCZBOA7V.js} +42 -16
  42. package/dist/{project-semantic-WJOP2HGJ.js → project-semantic-WW5AZST3.js} +266 -17
  43. package/dist/{sync-K65X7ODO.js → sync-6PL25V42.js} +13 -12
  44. package/dist/{te-agent-QWZC36YS.js → te-agent-KXLDW4NE.js} +6 -5
  45. package/dist/{te-analysis-7E2GVKOR.js → te-analysis-KKRECQ7F.js} +311 -52
  46. package/dist/{te-community-NQNSLNON.js → te-community-6RGX7IWH.js} +8 -6
  47. package/dist/{te-dataops-PMI7UX36.js → te-dataops-RSPBC6WJ.js} +726 -220
  48. package/dist/{te-engage-EZBV5IPQ.js → te-engage-FIPP5L2Z.js} +6 -5
  49. package/dist/{te-experiment-RDB3TYBG.js → te-experiment-KQ5CBYKI.js} +86 -10
  50. package/dist/{te-kb-OWPJB243.js → te-kb-XYSDXZUG.js} +32 -11
  51. package/dist/{te-system-Z4VEB6PL.js → te-system-QSOHAP7M.js} +7 -6
  52. package/dist/{te-team-NCMN34IL.js → te-team-R6MZ4RK2.js} +6 -5
  53. package/dist/{things-UBMLTY3S.js → things-DEONFUGS.js} +6 -5
  54. package/dist/{update-LYVYF3KJ.js → update-C6G4P3C7.js} +5 -4
  55. package/dist/{web-runtime-XJWDFVP3.js → web-runtime-UGKPTBOK.js} +12 -10
  56. package/dist/{workspace-W5ZPVWJS.js → workspace-OBIIE5FN.js} +5 -4
  57. package/package.json +7 -5
  58. package/skills/ae-analysis/SKILL.md +41 -16
  59. package/skills/ae-analysis/references/adhoc_export.md +1 -1
  60. package/skills/ae-analysis/references/adhoc_run.md +8 -2
  61. package/skills/ae-analysis/references/analysis_drilldown_contract.md +1 -1
  62. package/skills/ae-analysis/references/audience_scheduling.md +30 -0
  63. package/skills/ae-analysis/references/business_semantics_workspace.md +57 -0
  64. package/skills/ae-analysis/references/command_index.md +18 -13
  65. package/skills/ae-analysis/references/context_prepare.md +49 -0
  66. package/skills/ae-analysis/references/drilldown_entities_export.md +1 -1
  67. package/skills/ae-analysis/references/drilldown_entities_run.md +1 -1
  68. package/skills/ae-analysis/references/drilldown_user_events_export.md +3 -1
  69. package/skills/ae-analysis/references/drilldown_user_events_run.md +2 -1
  70. package/skills/ae-analysis/references/governance_recommendation_export.md +1 -1
  71. package/skills/ae-analysis/references/personal_semantic_preference_add.md +5 -1
  72. package/skills/ae-analysis/references/personal_semantic_preference_get.md +4 -2
  73. package/skills/ae-analysis/references/personal_semantic_preference_list.md +7 -6
  74. package/skills/ae-analysis/references/personal_semantic_preference_submit.md +1 -1
  75. package/skills/ae-analysis/references/personal_semantic_preference_update.md +5 -1
  76. package/skills/ae-analysis/references/project_info_get.md +4 -0
  77. package/skills/ae-analysis/references/project_semantic_knowledge_wiki.md +1 -1
  78. package/skills/ae-analysis/references/project_semantic_setup.md +60 -0
  79. package/skills/ae-analysis/references/report_get.md +2 -0
  80. package/skills/ae-analysis/references/report_presentation.md +55 -0
  81. package/skills/ae-analysis/references/report_update.md +4 -2
  82. package/skills/ae-analysis/references/system_openapi_token_batch_generate.md +20 -0
  83. package/skills/ae-analysis/references/system_openapi_token_get.md +14 -0
  84. package/skills/ae-analysis/references/user_cluster_create.md +3 -1
  85. package/skills/ae-analysis/references/user_cluster_models.md +2 -0
  86. package/skills/ae-analysis/references/user_cluster_update.md +5 -3
  87. package/skills/ae-analysis/references/user_tag_create.md +4 -22
  88. package/skills/ae-analysis/references/user_tag_models.md +8 -0
  89. package/skills/ae-analysis/references/user_tag_update.md +6 -14
  90. package/skills/ae-analysis/scripts/read-semantic-catalog.mjs +40 -0
  91. package/skills/ae-capability/SKILL.md +5 -1
  92. package/skills/ae-dataops/SKILL.md +9 -6
  93. package/skills/ae-dataops/references/dataops-flow-create.md +64 -47
  94. package/skills/ae-dataops/references/dataops-flow-monitor.md +4 -2
  95. package/skills/ae-dataops/references/dataops-flow-python.md +109 -0
  96. package/skills/ae-experiment/SKILL.md +9 -1
  97. package/skills/ae-experiment/references/manage_feature_fixed_value.md +73 -0
  98. package/skills/ae-experiment/references/save_feature.md +14 -1
  99. package/skills/ae-heari-research/SKILL.md +40 -0
  100. package/skills/ae-heari-research/references/design.md +35 -0
  101. package/skills/ae-heari-research/references/examples.md +46 -0
  102. package/skills/ae-heari-research/references/platform-auth.md +35 -0
  103. package/skills/ae-heari-research/references/platform-research.md +74 -0
  104. package/skills/ae-heari-research/references/platform-results.md +73 -0
  105. package/skills/ae-heari-research/references/platform.md +34 -0
  106. package/skills/ae-heari-research/references/probing-screening.md +31 -0
  107. package/skills/ae-heari-research/references/quality.md +44 -0
  108. package/skills/ae-kb/SKILL.md +10 -5
  109. package/skills/ae-kb/references/analysis-workflow.md +19 -10
  110. package/skills/ae-kb/references/query-workflow.md +34 -17
  111. package/skills/ae-kb-discovery/SKILL.md +4 -3
  112. package/skills/ae-onboarding/SKILL.md +3 -3
  113. package/dist/context-WJQGJD6F.js +0 -139
  114. package/dist/{data-integration-KMJWYAKK.js → data-integration-SCYYZLWI.js} +4 -4
@@ -0,0 +1,350 @@
1
+ import { createRequire as __createRequire } from 'node:module'; const require = __createRequire(import.meta.url);
2
+ import {
3
+ TeAgentApiError,
4
+ getFromMainApp
5
+ } from "./chunk-3DTMWDJX.js";
6
+ import {
7
+ executeCapabilityWithEnvelope,
8
+ readCliAgentContext
9
+ } from "./chunk-7KBENPQF.js";
10
+ import {
11
+ getCliToken,
12
+ internalCallSourceHeaders
13
+ } from "./chunk-FKTVD63C.js";
14
+ import "./chunk-FEYZBUFQ.js";
15
+ import {
16
+ getConfigDir,
17
+ safeJsonParse
18
+ } from "./chunk-IGU3R2JD.js";
19
+ import {
20
+ normalizeUrl
21
+ } from "./chunk-MTK4ZE7W.js";
22
+ import {
23
+ CliValidationError
24
+ } from "./chunk-3ZQY7SLZ.js";
25
+
26
+ // src/core/current-page-context-client.ts
27
+ async function readCurrentPageContext(path) {
28
+ const url = process.env.TE_AGENT_PAGE_CONTEXT_MCP_URL;
29
+ const grant = process.env.TE_AGENT_PAGE_CONTEXT_TOKEN;
30
+ if (url === void 0 && grant === void 0) return getFromMainApp(path);
31
+ let endpoint;
32
+ try {
33
+ endpoint = new URL(url ?? "");
34
+ if (!grant || !["http:", "https:"].includes(endpoint.protocol) || endpoint.username || endpoint.password || endpoint.search || endpoint.hash || !endpoint.pathname.endsWith("/api/internal/dashboard-context/mcp")) throw new Error();
35
+ } catch {
36
+ throw new TeAgentApiError("Current page context Run binding is invalid.", 0, "CURRENT_PAGE_CONTEXT_BINDING_INVALID");
37
+ }
38
+ let response;
39
+ try {
40
+ response = await fetch(endpoint.toString(), {
41
+ method: "POST",
42
+ redirect: "error",
43
+ signal: AbortSignal.timeout(3e4),
44
+ headers: {
45
+ "Content-Type": "application/json",
46
+ Accept: "application/json, text/event-stream",
47
+ "MCP-Protocol-Version": "2025-03-26",
48
+ "X-TE-Page-Context-Token": grant,
49
+ ...internalCallSourceHeaders()
50
+ },
51
+ body: JSON.stringify({
52
+ jsonrpc: "2.0",
53
+ id: 1,
54
+ method: "tools/call",
55
+ params: { name: "read_current_page_context", arguments: {} }
56
+ })
57
+ });
58
+ } catch {
59
+ throw new TeAgentApiError("Current page context MCP request failed.", 0, "CURRENT_PAGE_CONTEXT_NETWORK_ERROR");
60
+ }
61
+ if (!response.ok) {
62
+ await response.body?.cancel();
63
+ throw new TeAgentApiError(
64
+ `Current page context authorization/request failed (HTTP ${response.status}).`,
65
+ response.status,
66
+ "CURRENT_PAGE_CONTEXT_UNAVAILABLE",
67
+ void 0,
68
+ response.status === 403 ? "permission" : response.status === 401 ? "auth" : "api"
69
+ );
70
+ }
71
+ const reader = response.body?.getReader();
72
+ if (!reader) throw invalidResponse();
73
+ const chunks = [];
74
+ let size = 0;
75
+ try {
76
+ while (true) {
77
+ const { value, done } = await reader.read();
78
+ if (done) break;
79
+ size += value.byteLength;
80
+ if (size > 4 * 1024 * 1024) throw invalidResponse();
81
+ chunks.push(value);
82
+ }
83
+ } catch {
84
+ await reader.cancel().catch(() => void 0);
85
+ throw invalidResponse();
86
+ } finally {
87
+ reader.releaseLock();
88
+ }
89
+ let envelope;
90
+ try {
91
+ envelope = safeJsonParse(Buffer.concat(chunks).toString("utf8"));
92
+ } catch {
93
+ throw invalidResponse();
94
+ }
95
+ if (envelope?.error || envelope?.result?.isError) {
96
+ throw new TeAgentApiError(
97
+ "Current page context is unavailable for this Run; authorization may have expired or been revoked.",
98
+ 403,
99
+ "CURRENT_PAGE_CONTEXT_UNAVAILABLE"
100
+ );
101
+ }
102
+ const content = envelope?.result?.content;
103
+ if (envelope?.jsonrpc !== "2.0" || envelope.id !== 1 || !Array.isArray(content) || content.length !== 1 || content[0]?.type !== "text") throw invalidResponse();
104
+ try {
105
+ return safeJsonParse(content[0].text);
106
+ } catch {
107
+ throw invalidResponse();
108
+ }
109
+ }
110
+ function invalidResponse() {
111
+ return new TeAgentApiError("Invalid current page context MCP response.", 0, "CURRENT_PAGE_CONTEXT_RESPONSE_INVALID");
112
+ }
113
+
114
+ // src/commands/context/current.ts
115
+ var CURRENT_PAGE_CONTEXT_PATH = "/api/sandbox/agent/context/current";
116
+ function createCurrentPageContextCommand(read = readCurrentPageContext, readConversationId = () => process.env.TE_AGENT_CONVERSATION_ID) {
117
+ return {
118
+ service: "context",
119
+ command: "+current",
120
+ description: "Read the current page context bound to the active Agent Run",
121
+ flags: [],
122
+ risk: "read",
123
+ usesAeHost: false,
124
+ execute: async () => {
125
+ const conversationId = readConversationId()?.trim();
126
+ if (!conversationId) {
127
+ throw new CliValidationError(
128
+ "Current page context is available only inside an active Agent Run.",
129
+ {
130
+ code: "CURRENT_PAGE_CONTEXT_RUN_REQUIRED",
131
+ hint: "Open AE Agent from a supported product page and ask about the current page."
132
+ }
133
+ );
134
+ }
135
+ const query = new URLSearchParams({ conversationId });
136
+ return read(`${CURRENT_PAGE_CONTEXT_PATH}?${query.toString()}`);
137
+ }
138
+ };
139
+ }
140
+ var currentPageContext = createCurrentPageContextCommand();
141
+
142
+ // src/commands/context/prepare.ts
143
+ import { createHash, randomUUID } from "crypto";
144
+ import { mkdir, readFile, rename, writeFile, unlink } from "fs/promises";
145
+ import { join } from "path";
146
+ var defaults = {
147
+ call: async (host, capability, input) => (await executeCapabilityWithEnvelope(host, "analysis", capability, input)).data,
148
+ // A credential is bound to its company and account. Persist only its digest; a
149
+ // credential change conservatively starts another scope, including token rotation.
150
+ identity: async (host) => digest(await getCliToken(host)),
151
+ session: () => readCliAgentContext().agent_session_id,
152
+ cacheRoot: () => join(getConfigDir(), "analysis-context")
153
+ };
154
+ var PAGE_CHARACTERS = 16e3;
155
+ var digest = (value) => createHash("sha256").update(value).digest("hex");
156
+ function invalid(message) {
157
+ throw new CliValidationError(message, { code: "ANALYSIS_CONTEXT_INVALID" });
158
+ }
159
+ function catalog(value) {
160
+ const data = value;
161
+ if (!data || data.complete !== true || data.truncated === true || !Array.isArray(data.items) || data.total !== data.items.length) invalid("A complete semantic catalog is required.");
162
+ const seen = /* @__PURE__ */ new Set();
163
+ for (const row of data.items) {
164
+ if (!row || typeof row.id !== "string" || !row.id || seen.has(row.id) || typeof row.title !== "string" || typeof row.summary !== "string" || !Number.isSafeInteger(row.revision) || row.revision < 1 || typeof row.expired !== "boolean" || row.keywords !== void 0 && (!Array.isArray(row.keywords) || row.keywords.some((keyword) => typeof keyword !== "string"))) {
165
+ invalid("A semantic catalog contains invalid or duplicate entries.");
166
+ }
167
+ seen.add(row.id);
168
+ }
169
+ return data;
170
+ }
171
+ function background(value) {
172
+ if (!value || typeof value !== "object" || Array.isArray(value) || typeof value.configured !== "boolean") {
173
+ invalid("Published background response must explicitly report configured.");
174
+ }
175
+ return value;
176
+ }
177
+ function options(ctx, deps) {
178
+ const session = ctx.str("session-id") || deps.session();
179
+ if (!session?.trim() || session.length > 191 || /[\x00-\x1f\x7f]/.test(session)) {
180
+ throw new CliValidationError("A stable Agent session ID is required for context preparation.", {
181
+ code: "ANALYSIS_CONTEXT_SESSION_REQUIRED",
182
+ hint: "Set agent_session_id in the effective CLI Agent context file, or pass --session-id. Use a new ID for each conversation."
183
+ });
184
+ }
185
+ const projectId = ctx.optionalNum("project-id");
186
+ if (projectId !== void 0 && (!Number.isSafeInteger(projectId) || projectId <= 0)) {
187
+ invalid("project-id must be a positive integer when supplied.");
188
+ }
189
+ const page = ctx.optionalNum("page") ?? 1;
190
+ if (!Number.isSafeInteger(page) || page < 1) invalid("page must be a positive integer.");
191
+ return { session, projectId, page };
192
+ }
193
+ async function save(path, value) {
194
+ const temp = `${path}.${randomUUID()}.tmp`;
195
+ try {
196
+ await writeFile(temp, JSON.stringify(value), { mode: 384, flag: "wx" });
197
+ await rename(temp, path);
198
+ } finally {
199
+ await unlink(temp).catch((error) => {
200
+ if (error.code !== "ENOENT") throw error;
201
+ });
202
+ }
203
+ }
204
+ async function load(path, binding, project = false) {
205
+ let value;
206
+ try {
207
+ value = JSON.parse(await readFile(path, "utf8"));
208
+ } catch (error) {
209
+ if (error.code === "ENOENT") return void 0;
210
+ throw new CliValidationError("Context cache is unreadable. Use --refresh to prepare it again.", {
211
+ code: "ANALYSIS_CONTEXT_CACHE_INVALID"
212
+ });
213
+ }
214
+ if (value.version === 1) return void 0;
215
+ if (value.version !== 2 || value.binding !== binding) invalid("Context cache scope does not match this request.");
216
+ background(value.background);
217
+ catalog(value.personal);
218
+ if (project && !value.public) invalid("Project context cache is missing its public catalog.");
219
+ if (value.public) catalog(value.public);
220
+ return value;
221
+ }
222
+ function directoryItems(catalog2, scope) {
223
+ return catalog2.items.map((row) => ({ kind: "semantic", scope, ...row }));
224
+ }
225
+ function pages(items) {
226
+ const result = [[]];
227
+ let size = 0;
228
+ for (const item of items) {
229
+ const length = JSON.stringify(item).length;
230
+ if (length > PAGE_CHARACTERS) invalid("A context item exceeds the bounded output size; it was not truncated.");
231
+ if (size + length > PAGE_CHARACTERS && result.at(-1).length) {
232
+ result.push([]);
233
+ size = 0;
234
+ }
235
+ result.at(-1).push(item);
236
+ size += length;
237
+ }
238
+ return result;
239
+ }
240
+ function createContextPrepareCommand(overrides = {}) {
241
+ const deps = { ...defaults, ...overrides };
242
+ return {
243
+ service: "context",
244
+ command: "prepare",
245
+ description: "Prepare company/global personal context, then optional project background and full personal/public catalogs. Reuse a private session snapshot.",
246
+ helpText: "Before every business workflow, use prepare without a project, consume all pages, select the project, then prepare --project-id. Existing business commands do not initialize context automatically.",
247
+ flags: [
248
+ { name: "project-id", type: "number", desc: "Optional selected project. Omit until project selection; global preparation always precedes a new project scope." },
249
+ { name: "session-id", type: "string", desc: "Stable conversation ID. Defaults to agent_session_id from the effective CLI Agent context." },
250
+ { name: "page", type: "number", desc: "One-based bounded output page. Consume every page from the same cached snapshot. Default: 1." },
251
+ { name: "refresh", type: "boolean", desc: "Explicitly replace this scope and its global snapshot after context changes. Not needed for ordinary follow-up actions." }
252
+ ],
253
+ risk: "read",
254
+ sensitiveOutput: true,
255
+ validate: (ctx) => {
256
+ options(ctx, deps);
257
+ },
258
+ dryRun: async (ctx) => ({ workflow: "analysis_context_prepare", ...options(ctx, deps), remote_writes: false }),
259
+ execute: async (ctx) => {
260
+ const { session, projectId, page } = options(ctx, deps);
261
+ const host = normalizeUrl(ctx.host());
262
+ const identity = await deps.identity(host);
263
+ const binding = digest(JSON.stringify([host, identity, session]));
264
+ const root = join(deps.cacheRoot(), binding);
265
+ const globalPath = join(root, "global.json");
266
+ const projectPath = projectId === void 0 ? void 0 : join(root, `project-${projectId}.json`);
267
+ const refresh = ctx.bool("refresh");
268
+ if (refresh && page !== 1) invalid("Refresh must start at page 1.");
269
+ if (refresh) {
270
+ for (const path of [globalPath, projectPath]) {
271
+ if (path) await unlink(path).catch((error) => {
272
+ if (error.code !== "ENOENT") throw error;
273
+ });
274
+ }
275
+ }
276
+ let global = refresh ? void 0 : await load(globalPath, binding);
277
+ let project = projectPath && !refresh ? await load(projectPath, `${binding}:${projectId}`, true) : void 0;
278
+ const globalCached = !!global;
279
+ const projectCached = !!project;
280
+ if (page > 1 && (!global || projectPath && !project)) {
281
+ invalid("Prepare page 1 before requesting another page.");
282
+ }
283
+ const call = (operation, id, extra = {}) => deps.call(host, `business_semantics.${operation}`, { project_id: id, ...extra });
284
+ if (!global) {
285
+ const company = background(await call("background.get", 0));
286
+ const personal = catalog(await call("global_personal_context.list", -1));
287
+ global = { version: 2, binding, prepared_at: (/* @__PURE__ */ new Date()).toISOString(), background: company, personal };
288
+ await mkdir(root, { recursive: true, mode: 448 });
289
+ await save(globalPath, global);
290
+ }
291
+ if (projectId !== void 0 && !project) {
292
+ const published = background(await call("background.get", projectId));
293
+ const personal = catalog(await call("personal_context.list", projectId, { for_analysis_context: true }));
294
+ if (personal.selection_policy !== "ANALYSIS_CONTEXT") {
295
+ invalid("The server must support analysis-context personal semantic filtering. Deploy the matching Common service.");
296
+ }
297
+ const projectPublic = catalog(await call("project_context.list", projectId));
298
+ project = {
299
+ version: 2,
300
+ binding: `${binding}:${projectId}`,
301
+ prepared_at: (/* @__PURE__ */ new Date()).toISOString(),
302
+ background: published,
303
+ personal,
304
+ public: projectPublic
305
+ };
306
+ await save(projectPath, project);
307
+ }
308
+ const items = [
309
+ { kind: "background", scope: "company", ...global.background },
310
+ ...directoryItems(global.personal, "global_personal"),
311
+ ...project ? [
312
+ { kind: "background", scope: "project", ...project.background },
313
+ ...directoryItems(project.personal, "project_personal"),
314
+ ...directoryItems(project.public, "project_public")
315
+ ] : []
316
+ ];
317
+ const outputPages = pages(items);
318
+ if (page > outputPages.length) invalid("Requested context page does not exist.");
319
+ return {
320
+ workflow: "analysis_context_prepare",
321
+ phase: project ? "project" : "global",
322
+ session_id: session,
323
+ ...projectId === void 0 ? {} : { project_id: projectId },
324
+ cache_hit: globalCached && (!project || projectCached),
325
+ global_cache_hit: globalCached,
326
+ ...project ? { project_cache_hit: projectCached } : {},
327
+ prepared_at: project?.prepared_at ?? global.prepared_at,
328
+ complete: true,
329
+ page,
330
+ total_pages: outputPages.length,
331
+ remaining_pages: outputPages.length - page,
332
+ total_source_entries: global.personal.total + (project?.personal.total ?? 0) + (project?.public?.total ?? 0),
333
+ total_presented_entries: items.filter((item) => item.kind === "semantic").length,
334
+ items: outputPages[page - 1],
335
+ remote_writes: false,
336
+ next_action: page < outputPages.length ? `Read context prepare --page ${page + 1}${projectId === void 0 ? "" : ` --project-id ${projectId}`} with the same host/session.` : "Retain this complete context. Read relevant current details and dependencies by original ID; mark only actually adopted entries. Preparation is not semantic use."
337
+ };
338
+ }
339
+ };
340
+ }
341
+ var contextPrepare = createContextPrepareCommand();
342
+
343
+ // src/commands/context/index.ts
344
+ var commands = [currentPageContext, contextPrepare];
345
+ var context_default = commands;
346
+ export {
347
+ contextPrepare,
348
+ currentPageContext,
349
+ context_default as default
350
+ };
@@ -8,9 +8,10 @@ import {
8
8
  idAndLockFlags,
9
9
  idFlag,
10
10
  lockVersionFlag
11
- } from "./chunk-M2OCZRVX.js";
12
- import "./chunk-L7MT53VM.js";
13
- import "./chunk-UWQXGF44.js";
11
+ } from "./chunk-6VLHJKDD.js";
12
+ import "./chunk-PWG5IGCP.js";
13
+ import "./chunk-FKTVD63C.js";
14
+ import "./chunk-FEYZBUFQ.js";
14
15
  import "./chunk-IGU3R2JD.js";
15
16
  import "./chunk-MTK4ZE7W.js";
16
17
  import {
@@ -0,0 +1,83 @@
1
+ import { createRequire as __createRequire } from 'node:module'; const require = __createRequire(import.meta.url);
2
+ import {
3
+ loadCliToken
4
+ } from "./chunk-FEYZBUFQ.js";
5
+ import {
6
+ loadConfig,
7
+ readSandboxCliTokenEntry
8
+ } from "./chunk-IGU3R2JD.js";
9
+ import {
10
+ readExternalCliToken
11
+ } from "./chunk-MTK4ZE7W.js";
12
+ import "./chunk-3ZQY7SLZ.js";
13
+
14
+ // src/core/heari-cli-login.ts
15
+ var ticketPath = "/v1/ta/heari/agent/cli-ticket";
16
+ var publicCodes = /* @__PURE__ */ new Set([
17
+ "AE_SSO_GRANT_REJECTED",
18
+ "AE_WORKSPACE_UNAVAILABLE",
19
+ "AE_SSO_UNAVAILABLE",
20
+ "invalid_user",
21
+ "invalid_credentials",
22
+ "temporarily_unavailable"
23
+ ]);
24
+ async function requestGrant(url, options, stage) {
25
+ const failed = (status, serviceCode) => {
26
+ const detail = { stage, site: url.origin, http_status: status, service_code: serviceCode };
27
+ const message = stage === "cli-ticket" ? "AE could not issue a HearI ticket" : "AE issued a ticket; HearI exchange failed";
28
+ return Object.assign(new Error(message + " at " + url.origin + (status ? " (HTTP " + status + (serviceCode ? ", " + serviceCode : "") + ")" : " (network error)")), { aeDiagnostic: detail });
29
+ };
30
+ let response;
31
+ try {
32
+ response = await fetch(url, options);
33
+ } catch {
34
+ throw failed();
35
+ }
36
+ if (!response.ok) {
37
+ const body = await response.json().catch(() => null);
38
+ const code = body?.detail ?? body?.error;
39
+ throw failed(response.status, publicCodes.has(code) ? code : void 0);
40
+ }
41
+ return response;
42
+ }
43
+ async function exchangeHeariCredentials(signal, checkEndpoint) {
44
+ const session = readExternalCliToken() ?? readSandboxCliTokenEntry();
45
+ if (!session && process.env.TE_AGENT_CLI_CONFIG_DIR !== void 0) {
46
+ throw new Error("Current session credentials are unavailable.");
47
+ }
48
+ const host = session?.url ?? loadConfig().activeHost;
49
+ if (!host) return void 0;
50
+ const cliToken = session?.token ?? loadCliToken(host);
51
+ if (!cliToken) return void 0;
52
+ const origin = new URL(host);
53
+ if (!["http:", "https:"].includes(origin.protocol) || origin.username || origin.password || origin.search || origin.hash || !/^cli_[!-~]{1,8192}$/.test(cliToken)) {
54
+ throw new Error("Invalid AE session.");
55
+ }
56
+ const timeout = AbortSignal.timeout(15e3);
57
+ const requestSignal = signal ? AbortSignal.any([signal, timeout]) : timeout;
58
+ const options = { method: "POST", redirect: "error", cache: "no-store", signal: requestSignal };
59
+ const response = await requestGrant(new URL(ticketPath, origin), {
60
+ ...options,
61
+ headers: { "cli-token": cliToken }
62
+ }, "cli-ticket");
63
+ const { ticket, execution_id, audience } = await response.json();
64
+ const target = new URL(audience);
65
+ if (target.protocol !== "https:" || target.origin !== audience || typeof ticket !== "string" || !/^[A-Za-z0-9_-]{43}$/.test(ticket) || typeof execution_id !== "string" || !/^cli-[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(execution_id)) {
66
+ throw new Error("Invalid HearI registration on the current AE deployment.");
67
+ }
68
+ const endpoint = new URL("/mcp", target).href;
69
+ checkEndpoint?.(endpoint);
70
+ const exchange = await requestGrant(new URL("/api/auth/ae/agent/exchange", target), {
71
+ ...options,
72
+ headers: { "Content-Type": "application/json" },
73
+ body: JSON.stringify({ ticket, execution_id })
74
+ }, "agent/exchange");
75
+ const { access_token, expires_in } = await exchange.json();
76
+ if (typeof access_token !== "string" || !/^[!-~]{1,4096}$/.test(access_token) || !Number.isInteger(expires_in) || expires_in < 1 || expires_in > 300) {
77
+ throw new Error("Invalid HearI credential response.");
78
+ }
79
+ return { endpoint, token: access_token };
80
+ }
81
+ export {
82
+ exchangeHeariCredentials
83
+ };