@insmind/cli 1.4.0 → 1.4.1

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.
@@ -1,3 +1,5 @@
1
+ import { taskScope } from "../features/task/store.js";
2
+ import { TaskNotFoundError } from "../features/task/use-cases.js";
1
3
  import { homedir } from "node:os";
2
4
  import { createAgentBackgroundLauncher } from "../features/task/agent-background.js";
3
5
  import { createTaskStore } from "../features/task/store.js";
@@ -159,6 +161,7 @@ export function createProductionRuntime(options = {}) {
159
161
  const sso = createSsoService({
160
162
  ssoApi: endpoints.ssoApi,
161
163
  clientId: product.deviceClientId,
164
+ traceparent: () => telemetry.traceparent(),
162
165
  fetch,
163
166
  now
164
167
  });
@@ -247,26 +250,44 @@ export function createProductionRuntime(options = {}) {
247
250
  },
248
251
  telemetry
249
252
  });
250
- const resourceAuthorizer = createAgentResourceAuthorizer({
251
- authKeys: options.resourceAuthKeys
252
- ?? createFilemsResourceAuthKeyProvider({ transport: createSignedHttpTransport({
253
- baseUrl: endpoints.filemsApi,
254
- fetch,
255
- now,
256
- channelId: "32",
257
- traceparent: () => telemetry.traceparent(),
258
- ...(businessHeaders ? { businessHeaders } : {})
259
- }) })
260
- });
261
- const authorizeTaskResult = async (result, state, signal) => {
253
+ const resourceAuthKeys = options.resourceAuthKeys
254
+ ?? createFilemsResourceAuthKeyProvider({ transport: createSignedHttpTransport({
255
+ baseUrl: endpoints.filemsApi,
256
+ fetch,
257
+ now,
258
+ channelId: "32",
259
+ traceparent: () => telemetry.traceparent(),
260
+ ...(businessHeaders ? { businessHeaders } : {})
261
+ }) });
262
+ const resourceAuthorizer = createAgentResourceAuthorizer({ authKeys: resourceAuthKeys });
263
+ const accessPolicies = createAccessPolicies({ store, now, refreshCurrentOrganization: org.refreshCurrentOrganization });
264
+ const authorizeTaskAccess = async (state, signal) => {
265
+ await telemetry.stage("access", async () => {
266
+ const current = await accessPolicies.organization.authorize(signal);
267
+ if (!("state" in current) || !current.state.organization
268
+ || taskScope(current.state) !== taskScope(state)
269
+ || current.state.credential.accessKey !== state.credential.accessKey) {
270
+ throw new TaskNotFoundError(text("身份或组织已切换,请重新查询原任务。", "The identity or organization changed. Query the original task again."));
271
+ }
272
+ });
273
+ };
274
+ const authorizeTaskResult = async (result, state, signal, alreadyAuthorized = false) => {
275
+ // Bind only if this result actually needs a fresh resource token.
276
+ const taskAuthorizer = createAgentResourceAuthorizer({ authKeys: {
277
+ async getAuthKey(access, tokenSignal) {
278
+ if (!alreadyAuthorized)
279
+ await authorizeTaskAccess(state, tokenSignal);
280
+ return resourceAuthKeys.getAuthKey(access, tokenSignal);
281
+ }
282
+ } });
262
283
  const access = { credential: state.credential, organizationId: state.organization.id };
263
284
  if ("message" in result)
264
- return resourceAuthorizer.authorize(result, access, signal);
285
+ return taskAuthorizer.authorize(result, access, signal);
265
286
  const links = result.content.filter(part => part.type === "resource_link");
266
287
  if (links.length === 0)
267
288
  return result;
268
289
  const parts = links.map(part => ({ url: part.uri, mediaType: part.mimeType ?? "application/octet-stream" }));
269
- const authorized = await resourceAuthorizer.authorize({
290
+ const authorized = await taskAuthorizer.authorize({
270
291
  message: { contextId: "resource-authorization", parts: [parts[0], ...parts.slice(1)] },
271
292
  usage: { cost: { unit: "gaodou", amount: 0 }, items: [] }
272
293
  }, access, signal);
@@ -309,13 +330,14 @@ export function createProductionRuntime(options = {}) {
309
330
  return {
310
331
  state: "unknown", note: text("本地记录未取得服务端会话标识;无法确认提交结果,不自动重新生成。", "No service context was recorded. The submission outcome is unknown; do not generate again.")
311
332
  };
333
+ await authorizeTaskAccess(state, signal);
312
334
  const snapshot = await readAgentResult(agentTransport, {
313
335
  contextId: progress.contextId, localMessageId: progress.localMessageId,
314
336
  credential: state.credential, organizationId: state.organization.id, signal
315
337
  });
316
338
  return { state: "unknown",
317
339
  note: text(`会话连接为 ${snapshot.connectionState};这不是本次调用的完成凭据。已有内容仅作为消息快照。`, `The context connection is ${snapshot.connectionState}; this does not prove that the run completed. Available content is a message snapshot only.`),
318
- ...(snapshot.partialResult ? { partialResult: await authorizeTaskResult(agentOutputWithBillingUnit(snapshot.partialResult, product.billingUnit), state, signal) } : {})
340
+ ...(snapshot.partialResult ? { partialResult: await authorizeTaskResult(agentOutputWithBillingUnit(snapshot.partialResult, product.billingUnit), state, signal, true) } : {})
319
341
  };
320
342
  },
321
343
  async tool(progress, state, signal) {
@@ -323,6 +345,7 @@ export function createProductionRuntime(options = {}) {
323
345
  return {
324
346
  state: "unknown", note: text("本地记录未取得可查询的 Tool 回执;不自动重新生成。", "No queryable Tool receipt was recorded; do not generate again.")
325
347
  };
348
+ await authorizeTaskAccess(state, signal);
326
349
  const response = await queryToolResult(toolTransport, {
327
350
  taskId: progress.remoteTaskId, credential: state.credential,
328
351
  organizationId: state.organization.id, signal
@@ -335,7 +358,7 @@ export function createProductionRuntime(options = {}) {
335
358
  }
336
359
  return { state: "completed", result: await authorizeTaskResult(toolOutputWithBillingUnit({
337
360
  content: response.content, usage: progress.toolUsage
338
- }, product.billingUnit), state, signal) };
361
+ }, product.billingUnit), state, signal, true) };
339
362
  }
340
363
  }
341
364
  });
@@ -425,11 +448,7 @@ export function createProductionRuntime(options = {}) {
425
448
  version: primarySkill.version,
426
449
  telemetry,
427
450
  telemetrySink,
428
- accessPolicies: createAccessPolicies({
429
- store,
430
- now,
431
- refreshCurrentOrganization: org.refreshCurrentOrganization
432
- }),
451
+ accessPolicies,
433
452
  auth,
434
453
  org,
435
454
  agent,
@@ -179,6 +179,8 @@ export function classifyTelemetryError(error, options = {}) {
179
179
  const remoteError = error instanceof RemoteRequestError
180
180
  || error instanceof RemoteProtocolError
181
181
  || error instanceof ToolTaskFailedError
182
+ || error instanceof SsoRequestError
183
+ || error instanceof OrganizationBindFailedError
182
184
  ? error
183
185
  : undefined;
184
186
  return {
@@ -10,7 +10,7 @@ export function registerTaskCommands(program, runtime) {
10
10
  .option("--limit <number>", text("返回 1–100 条,默认 20", "return 1–100 tasks; defaults to 20"), "20")
11
11
  .option("--operation <operation>", text("筛选 agent.send 或 tool.call", "filter by agent.send or tool.call"))
12
12
  .allowExcessArguments(false);
13
- bindPreparedAction(list, "organization", async () => {
13
+ bindPreparedAction(list, "local-organization", async () => {
14
14
  const options = list.opts();
15
15
  const limit = Number(options.limit);
16
16
  if (!/^\d+$/u.test(options.limit) || !Number.isInteger(limit) || limit < 1 || limit > 100
@@ -30,12 +30,13 @@ export function registerTaskCommands(program, runtime) {
30
30
  "",
31
31
  text("completed 表示该次执行已有完整结果;running 表示原 CLI 仍在更新记录,或远端任务仍在执行。", "completed means this task has a complete result; running means the original CLI is updating the record or the service is still processing."),
32
32
  text("unknown 表示无法确认本次执行终态;partialResult 仅是已取得的消息片段,不代表完成。", "unknown means completion cannot be confirmed; partialResult is a message snapshot, not a complete result."),
33
+ text("读取本地状态不请求组织绑定;查询远端进度或获取下载授权仍需联网授权。查询请求失败不代表生成失败,可用原 taskId 重查。", "Local status reads do not bind the organization. Remote progress and download authorization still require network access. A failed query does not mean generation failed; query the same taskId again."),
33
34
  text("查询不重新提交创作;同一执行记录多次读取的 usage 是同一份费用。", "Queries never resubmit a creation. Reading the same task again does not add another usage charge."),
34
35
  text(`记录仅来自本机执行;保留至用户删除 ~/${runtime.product.stateDirectory}/tasks。切换身份或组织后只显示对应记录。`, `Tasks are local to this machine and identity context; they remain until you remove ~/${runtime.product.stateDirectory}/tasks.`),
35
36
  text("Agent 首次回执未取得或原连接中断时可能只能确认未知;不会自动选择最近 Context 或重新生成。", "A missing first Agent receipt or interrupted connection may leave the outcome unknown; the CLI does not select another Context or generate again."),
36
37
  ""
37
38
  ].join("\n"));
38
- bindPreparedAction(get, "organization", async () => {
39
+ bindPreparedAction(get, "local-organization", async () => {
39
40
  const id = get.processedArgs[0];
40
41
  if (typeof id !== "string" || !validTaskId(id))
41
42
  throw new CliUsageError();
@@ -312,9 +312,11 @@ function parseQuestionPart(message) {
312
312
  return fail();
313
313
  return { label };
314
314
  });
315
- const allowMultiple = question.allow_multiple ?? question.allowMultiple;
316
- if (typeof allowMultiple !== "boolean")
315
+ const rawAllowMultiple = question.allow_multiple !== undefined
316
+ ? question.allow_multiple : question.allowMultiple;
317
+ if (rawAllowMultiple !== undefined && typeof rawAllowMultiple !== "boolean")
317
318
  return fail();
319
+ const allowMultiple = rawAllowMultiple ?? false;
318
320
  return { question: text, options, allowMultiple };
319
321
  });
320
322
  const title = nonEmptyString(argumentsRecord.title);
@@ -72,6 +72,14 @@ export function createAccessPolicies(dependencies) {
72
72
  return { policy: "credential", state };
73
73
  }
74
74
  },
75
+ "local-organization": {
76
+ async authorize(signal) {
77
+ const state = await readValidState(signal);
78
+ if (!state.organization)
79
+ throw new OrganizationInvalidError();
80
+ return { policy: "local-organization", state: state };
81
+ }
82
+ },
75
83
  organization: {
76
84
  async authorize(signal) {
77
85
  let state = await readValidState(signal);
@@ -1,11 +1,16 @@
1
+ import { remoteErrorEvidence } from "../../platform/remote-error-evidence.js";
1
2
  import { normalizeScope } from "./state.js";
2
3
  import { signBindOrganization } from "../../platform/signature.js";
3
4
  export class SsoRequestError extends Error {
4
5
  status;
5
- constructor(status, cause) {
6
+ remoteCode;
7
+ remoteBody;
8
+ constructor(status, evidence = {}, cause) {
6
9
  super(status === undefined ? "无法连接稿定登录服务。" : `稿定登录服务请求失败(HTTP ${status})。`, { cause });
7
10
  this.name = "SsoRequestError";
8
11
  this.status = status;
12
+ this.remoteCode = evidence.remoteCode;
13
+ this.remoteBody = evidence.remoteBody;
9
14
  }
10
15
  }
11
16
  export function classifyBindOutcome(input) {
@@ -24,22 +29,62 @@ export function createSsoService(options) {
24
29
  const baseUrl = new URL(options.ssoApi);
25
30
  if (!baseUrl.pathname.endsWith("/"))
26
31
  baseUrl.pathname += "/";
32
+ const requests = new WeakMap();
33
+ async function responseError(response, networkError) {
34
+ let evidence = {};
35
+ if (!response.ok && !response.bodyUsed) {
36
+ try {
37
+ evidence = remoteErrorEvidence(await response.text());
38
+ }
39
+ catch (error) {
40
+ networkError = error;
41
+ }
42
+ }
43
+ return new SsoRequestError(response.status, {
44
+ ...(evidence.remoteCode === undefined ? {} : { remoteCode: evidence.remoteCode }),
45
+ ...remoteErrorEvidence({ request: requests.get(response),
46
+ ...(evidence.remoteBody === undefined ? {} : { response: evidence.remoteBody }),
47
+ ...(networkError === undefined ? {} : { network: networkFailure(networkError) }) })
48
+ }, networkError);
49
+ }
50
+ async function responseRecord(response) {
51
+ if (!response.ok) {
52
+ // OAuth pending/slow_down are normal token polling responses.
53
+ const body = await response.clone().json().catch(() => undefined);
54
+ if (isRecord(body) && ["authorization_pending", "slow_down"].includes(String(body.error).toLowerCase()))
55
+ return body;
56
+ throw await responseError(response);
57
+ }
58
+ try {
59
+ const value = await response.json();
60
+ if (isRecord(value))
61
+ return value;
62
+ }
63
+ catch (error) {
64
+ throw await responseError(response, error);
65
+ }
66
+ throw await responseError(response);
67
+ }
27
68
  async function request(relativeUrl, signal, method = "POST") {
28
69
  signal.throwIfAborted();
70
+ const url = new URL(relativeUrl, baseUrl);
71
+ const requestInfo = { method, path: url.pathname };
29
72
  try {
30
- return await options.fetch(new URL(relativeUrl, baseUrl), {
73
+ const response = await options.fetch(url, {
31
74
  method,
32
- headers: { Accept: "application/json" },
75
+ headers: { Accept: "application/json", ...(options.traceparent ? { traceparent: options.traceparent() } : {}) },
33
76
  signal: AbortSignal.any([
34
77
  signal,
35
78
  AbortSignal.timeout(options.timeoutMs ?? 30_000)
36
79
  ])
37
80
  });
81
+ requests.set(response, requestInfo);
82
+ return response;
38
83
  }
39
- catch (cause) {
84
+ catch (error) {
40
85
  if (signal.aborted)
41
86
  throw signal.reason;
42
- throw new SsoRequestError(undefined, cause);
87
+ throw new SsoRequestError(undefined, remoteErrorEvidence({ request: requestInfo, network: networkFailure(error) }), error);
43
88
  }
44
89
  }
45
90
  return {
@@ -48,14 +93,14 @@ export function createSsoService(options) {
48
93
  clientId: options.clientId ?? "gdhub-cli"
49
94
  })}`, signal);
50
95
  if (!response.ok)
51
- throw new SsoRequestError(response.status);
96
+ throw await responseError(response);
52
97
  const body = await responseRecord(response);
53
98
  const authorizeCode = nonEmptyString(body.authorize_code);
54
99
  const deviceCode = nonEmptyString(body.device_code);
55
100
  const expiresInSeconds = positiveNumber(body.expires_in);
56
101
  const intervalSeconds = positiveNumber(body.interval);
57
102
  if (!authorizeCode || !deviceCode || !expiresInSeconds || !intervalSeconds) {
58
- throw new SsoRequestError(response.status);
103
+ throw await responseError(response);
59
104
  }
60
105
  return { authorizeCode, deviceCode, expiresInSeconds, intervalSeconds };
61
106
  },
@@ -72,18 +117,18 @@ export function createSsoService(options) {
72
117
  if (error === "slow_down")
73
118
  return { status: "slow_down" };
74
119
  if (!response.ok)
75
- throw new SsoRequestError(response.status);
120
+ throw await responseError(response);
76
121
  const accessKey = nonEmptyString(body.ak);
77
122
  const secretKey = nonEmptyString(body.sk);
78
123
  const expiresAt = dateString(body.expires_at);
79
124
  if (!accessKey || !secretKey || !expiresAt)
80
- throw new SsoRequestError(response.status);
125
+ throw await responseError(response);
81
126
  let scope;
82
127
  try {
83
128
  scope = normalizeScope(body.scope);
84
129
  }
85
130
  catch {
86
- throw new SsoRequestError(response.status);
131
+ throw await responseError(response);
87
132
  }
88
133
  const result = {
89
134
  status: "authorized",
@@ -104,7 +149,7 @@ export function createSsoService(options) {
104
149
  const query = new URLSearchParams({ ak: accessKey });
105
150
  const response = await request(`oauth/device/identity?${query}`, signal, "GET");
106
151
  if (!response.ok)
107
- throw new SsoRequestError(response.status);
152
+ throw await responseError(response);
108
153
  const body = await responseRecord(response);
109
154
  const result = {};
110
155
  const userId = identifier(body.userId);
@@ -130,8 +175,12 @@ export function createSsoService(options) {
130
175
  });
131
176
  const response = await request(`oauth/device/bind-org?${query}`, signal);
132
177
  if (!response.ok)
133
- throw new SsoRequestError(response.status);
134
- const text = await response.text();
178
+ throw await responseError(response);
179
+ const text = await response.text().catch(async (error) => {
180
+ if (signal.aborted)
181
+ throw signal.reason;
182
+ throw await responseError(response, error);
183
+ });
135
184
  if (!text.trim())
136
185
  return {};
137
186
  let parsed;
@@ -142,7 +191,7 @@ export function createSsoService(options) {
142
191
  return { message: text.trim() };
143
192
  }
144
193
  if (!isRecord(parsed))
145
- throw new SsoRequestError(response.status);
194
+ throw await responseError(response);
146
195
  const result = {};
147
196
  if (typeof parsed.code === "string" || typeof parsed.code === "number") {
148
197
  result.code = parsed.code;
@@ -153,23 +202,24 @@ export function createSsoService(options) {
153
202
  if (parsed.bind_expires_at !== undefined) {
154
203
  const bindExpiresAt = dateString(parsed.bind_expires_at);
155
204
  if (!bindExpiresAt)
156
- throw new SsoRequestError(response.status);
205
+ throw await responseError(response);
157
206
  result.bindExpiresAt = bindExpiresAt;
158
207
  }
159
208
  return result;
160
209
  }
161
210
  };
162
211
  }
163
- async function responseRecord(response) {
164
- try {
165
- const value = await response.json();
166
- if (isRecord(value))
167
- return value;
168
- }
169
- catch {
170
- // Handled as one safe protocol failure below.
171
- }
172
- throw new SsoRequestError(response.status);
212
+ // Preserve only bounded diagnostic identifiers, never arbitrary cause messages/URLs.
213
+ function networkFailure(error) {
214
+ const safe = (value) => typeof value === "string" && /^[A-Za-z0-9_]{1,80}$/u.test(value) ? value : undefined;
215
+ const one = (value) => {
216
+ const record = value !== null && typeof value === "object" ? value : {};
217
+ const name = safe(record.name);
218
+ const code = safe(record.code);
219
+ return { ...(name ? { name } : {}), ...(code ? { code } : {}) };
220
+ };
221
+ const cause = error !== null && typeof error === "object" && "cause" in error ? one(error.cause) : undefined;
222
+ return { ...one(error), ...(cause ? { cause } : {}) };
173
223
  }
174
224
  function positiveNumber(value) {
175
225
  return typeof value === "number" && Number.isFinite(value) && value > 0
@@ -1,3 +1,4 @@
1
+ import { remoteErrorEvidence } from "../../platform/remote-error-evidence.js";
1
2
  import { classifyBindOutcome, SsoRequestError } from "../auth/sso-service.js";
2
3
  import { RemoteRequestError } from "../../platform/signed-http-transport.js";
3
4
  import { OrganizationResponseError } from "./org-service.js";
@@ -14,9 +15,13 @@ export class OrganizationInvalidError extends Error {
14
15
  }
15
16
  }
16
17
  export class OrganizationBindFailedError extends Error {
17
- constructor() {
18
+ remoteCode;
19
+ remoteBody;
20
+ constructor(evidence = {}) {
18
21
  super("选择组织失败,请稍后重试。");
19
22
  this.name = "OrganizationBindFailedError";
23
+ this.remoteCode = evidence.remoteCode;
24
+ this.remoteBody = evidence.remoteBody;
20
25
  }
21
26
  }
22
27
  export function createOrgUseCases(dependencies) {
@@ -29,7 +34,7 @@ export function createOrgUseCases(dependencies) {
29
34
  if (outcome.status === "invalid")
30
35
  throw new OrganizationInvalidError();
31
36
  if (outcome.status === "failed")
32
- throw new OrganizationBindFailedError();
37
+ throw new OrganizationBindFailedError(remoteErrorEvidence(response));
33
38
  return {
34
39
  id: record.id,
35
40
  name: record.publicName,
@@ -134,7 +139,7 @@ export function createOrgUseCases(dependencies) {
134
139
  if (outcome.status === "invalid")
135
140
  throw new OrganizationInvalidError();
136
141
  if (outcome.status === "failed")
137
- throw new OrganizationBindFailedError();
142
+ throw new OrganizationBindFailedError(remoteErrorEvidence(response));
138
143
  return {
139
144
  id: input.state.organization.id,
140
145
  name: input.state.organization.name,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@insmind/cli",
3
- "version": "1.4.0",
3
+ "version": "1.4.1",
4
4
  "description": "insMind command-line interface for agents and people.",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -46,8 +46,8 @@
46
46
  "@gaoding/cli": "workspace:*"
47
47
  },
48
48
  "gaodingRelease": {
49
- "sourceCommit": "c8b6775824e2c5d4a08be92d3d4f0bc07c5dad61",
50
- "pipelineId": "183000",
51
- "pipelineUrl": "https://git.intra.gaoding.com/gtt/gaoding-cli/-/pipelines/183000"
49
+ "sourceCommit": "3240af623d045c12d5ab21fbf55e45a2cff195c2",
50
+ "pipelineId": "183172",
51
+ "pipelineUrl": "https://git.intra.gaoding.com/gtt/gaoding-cli/-/pipelines/183172"
52
52
  }
53
53
  }
@@ -1,5 +1,17 @@
1
1
  # Creation
2
2
 
3
+ ## Requirements and inputs
4
+
5
+ Faithfully convey the user’s request, supplied materials and explicit constraints. When essential information or materials are missing, ask the user for clarification or pass the original request to the business Agent to assess and ask. Do not add instructions to generate replacement materials, disregard constraints or change the task’s objective without the user’s authorization. When the user explicitly permits free creation, illustrative materials or filling in missing details, work within that permission.
6
+
7
+ Judge whether the missing input affects the feasibility of the task, the identity of its subject or compliance with explicit requirements. Optional style preferences do not always require clarification.
8
+
9
+ For example, the user says “Make a promotional image for this product” without providing material that identifies the product:
10
+
11
+ - Correct: ask for the product image, or pass the original request to the business Agent so it can assess which materials are needed and ask.
12
+ - Incorrect: add “There is no original image, so generate an illustrative product first.” Labeling it a “concept” still changes the subject the user selected; obtain their choice first.
13
+ - Free creation differs: “Design a fictional product and make a promotional image” permits inventing the subject, so proceed. Unspecified colors or layouts can be designed as style details.
14
+
3
15
  ## Choose a route
4
16
 
5
17
  Choose the Creation Route before selecting or validating a Model. Both Agent and Tool accept models and parameters; `model list` and `model get` provide shared, live discovery.