@huaweidevtools/aishell-dsh-deploy 0.0.35 → 0.0.37

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/lib/index.js CHANGED
@@ -1,6 +1,7 @@
1
1
  import { createCredentialsStore } from "@huaweidevtools/aishell-dsh-credentials-store";
2
2
  import { z } from "zod";
3
3
  import { access, mkdir, readFile, readdir, rm, stat, writeFile } from "node:fs/promises";
4
+ import { AsyncLocalStorage } from "node:async_hooks";
4
5
  import { readFileSync } from "node:fs";
5
6
  import { dirname, isAbsolute, join, resolve } from "node:path";
6
7
  import { fileURLToPath } from "node:url";
@@ -59,11 +60,11 @@ function snapshot(value, ancestors = /* @__PURE__ */ new Set()) {
59
60
  * @returns a reference whose value is updated only by its owning runtime.
60
61
  */
61
62
  function createVolatile(value) {
62
- let current$1 = snapshot(value);
63
+ let current = snapshot(value);
63
64
  return Object.freeze({
64
- get: () => current$1,
65
+ get: () => current,
65
66
  [write]: (value$1) => {
66
- current$1 = value$1;
67
+ current = value$1;
67
68
  }
68
69
  });
69
70
  }
@@ -552,11 +553,11 @@ Schema.resolve = function resolve$1(data, schema, options = {}, strict = false)
552
553
  if (options.ignore?.(data, schema)) return [data];
553
554
  if (isNullable(data) && schema.type !== "lazy") {
554
555
  if (schema.meta.required) throw new ValidationError(`missing required value`, options);
555
- let current$1 = schema;
556
+ let current = schema;
556
557
  let fallback = schema.meta.default;
557
- while (current$1?.type === "intersect" && isNullable(fallback)) {
558
- current$1 = current$1.list[0];
559
- fallback = current$1?.meta.default;
558
+ while (current?.type === "intersect" && isNullable(fallback)) {
559
+ current = current.list[0];
560
+ fallback = current?.meta.default;
560
561
  }
561
562
  if (isNullable(fallback)) return [data];
562
563
  data = clone(fallback);
@@ -1027,13 +1028,17 @@ function argumentValidator(schema) {
1027
1028
  * @returns the handler context.
1028
1029
  */
1029
1030
  async function contextFor(exec, workingDirectory) {
1030
- const call = exec;
1031
- const agent = call?.agent;
1032
- if (workingDirectory === void 0 || agent === void 0) return {};
1031
+ const agent = exec.agent;
1032
+ const sessionId = typeof agent?.id === "string" && agent.id.length > 0 ? agent.id : void 0;
1033
+ const withSession = sessionId === void 0 ? {} : { sessionId };
1034
+ if (workingDirectory === void 0 || agent === void 0) return withSession;
1033
1035
  try {
1034
- return { sessionDirectory: await workingDirectory.ensure(agent, call?.signal) };
1036
+ return {
1037
+ ...withSession,
1038
+ sessionDirectory: await workingDirectory.ensure(agent, exec.signal)
1039
+ };
1035
1040
  } catch {
1036
- return {};
1041
+ return withSession;
1037
1042
  }
1038
1043
  }
1039
1044
  /**
@@ -1246,57 +1251,34 @@ function installPermissionRecorder(record) {
1246
1251
  };
1247
1252
  }
1248
1253
  /**
1249
- * Environment variable holding the startup default.
1254
+ * The posture every Session starts in.
1250
1255
  *
1251
- * Read once at module load and never re-read, so the mode cannot be changed
1252
- * by anything the agent can influence at runtime. It is intentionally absent
1253
- * from every tool description and from the prompt: it is an operator knob,
1254
- * not something the model is meant to reason about.
1256
+ * Read-only unless the deployment asked for otherwise before any conversation
1257
+ * opened. A Session is pinned to this value when it is created, so a later
1258
+ * change reaches only Sessions that have not started yet.
1255
1259
  */
1256
- const DEFAULT_MODE_ENV = "HW_DEFAULT_PERMISSION";
1257
- /** The mode when nothing overrides it. */
1258
- const FALLBACK_MODE = "read_only";
1259
- /**
1260
- * Parse a mode string.
1261
- *
1262
- * Accepts the wire spellings plus a few the operator is likely to type in an
1263
- * environment variable. Anything unrecognised yields `undefined` rather than
1264
- * throwing, so a typo degrades to the default instead of failing startup.
1265
- *
1266
- * @param value - candidate string.
1267
- * @returns the mode, or `undefined` when unrecognised.
1268
- */
1269
- function parseMode(value) {
1270
- if (value === void 0) return void 0;
1271
- switch (value.trim().toLowerCase()) {
1272
- case "read_only":
1273
- case "read-only":
1274
- case "readonly":
1275
- case "ro": return "read_only";
1276
- case "read_write":
1277
- case "read-write":
1278
- case "readwrite":
1279
- case "rw": return "read_write";
1280
- default: return void 0;
1281
- }
1260
+ const STARTUP_POSTURE = "read_only";
1261
+ /** The posture new Sessions are pinned to. Not retroactive — see the module header. */
1262
+ let posture = STARTUP_POSTURE;
1263
+ /** Modes by Session. Every created Session has an entry; `posture` covers the rest. */
1264
+ const modes = new Map();
1265
+ /** The mode one Session may act under. */
1266
+ function getMode(session) {
1267
+ if (session === void 0) return posture;
1268
+ return modes.get(session) ?? posture;
1282
1269
  }
1283
1270
  /**
1284
- * The mode this process started in.
1271
+ * The posture new Sessions start in.
1285
1272
  *
1286
- * Resolved once, at load. The environment variable is an operator's input to a
1287
- * running process, not a live setting: re-reading it would let a runtime change
1288
- * of the variable move the "startup default" that `resetMode` restores and that
1289
- * `/permission/get_mode` reports, which is a fact about the past.
1273
+ * Read through a function rather than exported as a value: the route and the
1274
+ * client both report it, and a snapshot taken at import time would go stale the
1275
+ * first time a deployment sets it.
1290
1276
  */
1291
- const STARTUP_MODE = parseMode(process.env[DEFAULT_MODE_ENV]) ?? FALLBACK_MODE;
1292
- /** Current mode. Module-level state — one server instance per connection. */
1293
- let current = STARTUP_MODE;
1294
- /** The mode in effect. */
1295
- function getMode$1() {
1296
- return current;
1277
+ function defaultPosture() {
1278
+ return posture;
1297
1279
  }
1298
1280
  /**
1299
- * Set the mode.
1281
+ * Set one Session's mode.
1300
1282
  *
1301
1283
  * ## Why the notification lives here
1302
1284
  *
@@ -1309,28 +1291,123 @@ function getMode$1() {
1309
1291
  * notified: the chip re-reads the state after every call, and recording those
1310
1292
  * would fill the trail with actions nobody took.
1311
1293
  *
1294
+ * A mode is stored under its Session for as long as that Session lives, whatever
1295
+ * its value. Only a Session that has never been given one follows the posture;
1296
+ * once a conversation has an answer of its own, that answer is the one it keeps,
1297
+ * so a later posture change cannot revise a decision already made about it.
1298
+ *
1299
+ * @param session - the Session the mode applies to.
1312
1300
  * @param mode - the mode to apply.
1313
1301
  * @param actor - who is setting it; the route is the only production caller, so
1314
1302
  * the default is the person at the console.
1315
- * @returns the previous mode, for a change log.
1303
+ * @returns the mode the Session was in, for a change log.
1316
1304
  */
1317
- function setMode$1(mode, actor = "user") {
1318
- const previous = current;
1319
- current = mode;
1305
+ function setMode(session, mode, actor = "user") {
1306
+ const previous = getMode(session);
1307
+ modes.set(session, mode);
1320
1308
  if (previous !== mode) recordChange?.({
1309
+ session,
1321
1310
  previous,
1322
1311
  mode,
1323
1312
  actor
1324
1313
  });
1325
1314
  return previous;
1326
1315
  }
1327
- /** Whether mutations are currently permitted. */
1328
- function writesAllowed() {
1329
- return current === "read_write";
1316
+ /**
1317
+ * Whether one Session may mutate the cloud.
1318
+ *
1319
+ * `undefined` is "no Session" — a call outside a conversation, which answers
1320
+ * with the posture. Every production tool call carries a Session, so that arm
1321
+ * describes a call this plugin does not place in any conversation; it is not a
1322
+ * separate policy, and a deployment that widened the posture widened it too.
1323
+ */
1324
+ function writesAllowed(session) {
1325
+ return getMode(session) === "read_write";
1326
+ }
1327
+ /**
1328
+ * Give one Session its own mode, decided by the posture in force at creation.
1329
+ *
1330
+ * Every Session carries an entry from the moment it exists, which is what makes
1331
+ * a posture change reach only Sessions that have not started. A Session pinned
1332
+ * here keeps the answer it was created with, so a conversation on screen is
1333
+ * never widened from underneath the person reading it.
1334
+ *
1335
+ * @param session - the Session being created.
1336
+ */
1337
+ function pinSession(session) {
1338
+ if (!modes.has(session)) modes.set(session, posture);
1339
+ }
1340
+ /**
1341
+ * Set the posture new Sessions start in.
1342
+ *
1343
+ * Every Session already has an entry of its own, so this decides what Sessions
1344
+ * created from now on begin with and leaves existing conversations as they are.
1345
+ *
1346
+ * @param mode - the posture to apply.
1347
+ * @returns the posture it replaced.
1348
+ */
1349
+ function setDefaultPosture(mode) {
1350
+ const previous = posture;
1351
+ posture = mode;
1352
+ if (previous !== mode) recordChange?.({
1353
+ session: void 0,
1354
+ previous,
1355
+ mode,
1356
+ actor: "user"
1357
+ });
1358
+ return previous;
1359
+ }
1360
+ /**
1361
+ * Forget one Session's mode.
1362
+ *
1363
+ * Called when the Session is disposed: the map is keyed by an identity that
1364
+ * will not be seen again, and a long-running process opens sessions for as long
1365
+ * as it runs.
1366
+ */
1367
+ function forgetSession(session) {
1368
+ modes.delete(session);
1369
+ }
1370
+
1371
+ //#endregion
1372
+ //#region src/permission/call-context.ts
1373
+ /** One call's Session, as read inside the asynchronous chain serving it. */
1374
+ const storage = new AsyncLocalStorage();
1375
+ /**
1376
+ * Run one call with its Session in scope.
1377
+ *
1378
+ * @param session - the Session the call is made for.
1379
+ * @param body - the work; anything it awaits reads the same Session.
1380
+ * @returns whatever `body` returns.
1381
+ */
1382
+ function runForSession(session, body) {
1383
+ return storage.run(session, body);
1330
1384
  }
1331
- /** The mode this process started in, for logging and for `permission/get_mode`. */
1332
- function defaultMode() {
1333
- return STARTUP_MODE;
1385
+ /**
1386
+ * Run one call that belongs to no Session.
1387
+ *
1388
+ * The store would otherwise be inherited from whatever call is already in
1389
+ * scope, which would credit this call to a conversation it is not part of. A
1390
+ * call the harness gave no Session belongs to no conversation, and the gates
1391
+ * judge it by the posture — the same answer as a call made outside any tool
1392
+ * execution.
1393
+ *
1394
+ * @param body - the work.
1395
+ * @returns whatever `body` returns.
1396
+ */
1397
+ function runWithoutSession(body) {
1398
+ return storage.exit(body);
1399
+ }
1400
+ /**
1401
+ * The Session the current call serves, if any.
1402
+ *
1403
+ * `undefined` outside any call this plugin placed in scope: at module level, on
1404
+ * work detached from the process, or inside a call the harness gave no Session.
1405
+ * The gate treats that as a call with no Session rather than inventing one.
1406
+ *
1407
+ * @returns the Session key, or `undefined`.
1408
+ */
1409
+ function currentSession() {
1410
+ return storage.getStore();
1334
1411
  }
1335
1412
 
1336
1413
  //#endregion
@@ -1568,26 +1645,34 @@ function logDenial(detail) {
1568
1645
  * Check a tool call against read-only mode.
1569
1646
  *
1570
1647
  * @param toolName - the tool about to run.
1648
+ * @param session - the Session it runs for; the executor has it, so it is passed
1649
+ * rather than read from the call context.
1571
1650
  * @returns a message to return as a failed tool result, or `undefined` to proceed.
1572
1651
  */
1573
- function denyTool(toolName) {
1574
- if (writesAllowed()) return void 0;
1652
+ function denyTool(toolName, session) {
1653
+ if (writesAllowed(session)) return void 0;
1575
1654
  if (!CLOUD_MUTATING_TOOLS.has(toolName)) return void 0;
1576
- logDenial(`refused tool ${toolName} (mode=${getMode$1()})`);
1655
+ logDenial(`refused tool ${toolName} (session=${session ?? "none"}, mode=${getMode(session)})`);
1577
1656
  return `Refused: ${toolName} changes HuaweiCloud resources, and this session is in read-only mode.\n\nRead-only mode is controlled outside this conversation — a person switches it in the client UI, and no tool or argument can change it. To run ${toolName}, ask the user to switch the session to read-write mode.\n\nOperations that only inspect state remain available: terraform_plan, terraform_state, terraform_refresh, apiexplorer, existing_resources, balance_summary, and read-only openapi_request calls.`;
1578
1657
  }
1579
1658
  /**
1580
1659
  * Check a signed HTTP request against read-only mode.
1581
1660
  *
1661
+ * The Session comes from the call context: every signed request is made inside a
1662
+ * tool execution, and the context carries that tool's Session down to this
1663
+ * funnel. See `./call-context.ts` for why it travels with the call rather than
1664
+ * as an argument.
1665
+ *
1582
1666
  * @param method - HTTP method.
1583
1667
  * @param url - the full request URL.
1584
1668
  * @returns a message describing the refusal, or `undefined` to proceed.
1585
1669
  */
1586
1670
  function denyHttp(method, url) {
1587
- if (writesAllowed()) return void 0;
1671
+ const session = currentSession();
1672
+ if (writesAllowed(session)) return void 0;
1588
1673
  const decision = isReadOnlyPermitted(method, url);
1589
1674
  if (decision.allowed) return void 0;
1590
- logDenial(`refused ${method.toUpperCase()} ${url.hostname}${url.pathname} (mode=${getMode$1()}, reason=${decision.reason})`);
1675
+ logDenial(`refused ${method.toUpperCase()} ${url.hostname}${url.pathname} (session=${session ?? "none"}, mode=${getMode(session)}, reason=${decision.reason})`);
1591
1676
  switch (decision.reason) {
1592
1677
  case "registry-unavailable": return "Refused: this session is in read-only mode and the permission registry could not be loaded, so the request cannot be cleared. GET and HEAD requests still work.\n\nReinstall this plugin; the packaged build is missing its registry artifact.";
1593
1678
  case "registry-miss":
@@ -1674,15 +1759,20 @@ function fail(message) {
1674
1759
  * not reach any part of its implementation, including argument validation that
1675
1760
  * might touch the filesystem. A tool declared in `CLOUD_MUTATING_TOOLS` is
1676
1761
  * refused here in read-only mode and never starts.
1762
+ *
1763
+ * The handler then runs inside the Session's call context, so the signed-HTTP
1764
+ * funnel — several layers down, with no Session parameter to pass — refuses
1765
+ * against the same Session this gate just read.
1677
1766
  */
1678
1767
  function guard(fn, toolName) {
1679
1768
  return async (args, ctx) => {
1680
1769
  if (toolName !== void 0) {
1681
- const refusal = denyTool(toolName);
1770
+ const refusal = denyTool(toolName, ctx.sessionId);
1682
1771
  if (refusal !== void 0) return fail(refusal);
1683
1772
  }
1684
1773
  try {
1685
- return await fn(withAnchoredPaths(args, ctx), ctx);
1774
+ const body = () => fn(withAnchoredPaths(args, ctx), ctx);
1775
+ return await (ctx.sessionId === void 0 ? runWithoutSession(body) : runForSession(ctx.sessionId, body));
1686
1776
  } catch (err) {
1687
1777
  const msg = err instanceof Error ? err.message : String(err);
1688
1778
  return fail(msg);
@@ -1745,7 +1835,7 @@ function withAnchoredPaths(args, ctx) {
1745
1835
  * written by earlier releases carry it — so it is kept even though there is no
1746
1836
  * server.
1747
1837
  */
1748
- const SERVER_VERSION = "aishell-deploy 0.0.35";
1838
+ const SERVER_VERSION = "aishell-deploy 0.0.37";
1749
1839
 
1750
1840
  //#endregion
1751
1841
  //#region src/deployment-state.ts
@@ -2324,7 +2414,7 @@ async function fileExists(path) {
2324
2414
  * @returns a refusal message, or `undefined` to proceed.
2325
2415
  */
2326
2416
  function denyTerraformMutation(args) {
2327
- if (writesAllowed()) return void 0;
2417
+ if (writesAllowed(currentSession())) return void 0;
2328
2418
  const subcommand = args[0];
2329
2419
  if (subcommand !== "apply" && subcommand !== "destroy") return void 0;
2330
2420
  if (args.includes("-refresh-only")) return void 0;
@@ -3300,8 +3390,8 @@ async function assertPlanApproved(directory, readState, hashConfiguration) {
3300
3390
  const state = await readState(directory);
3301
3391
  const record = state?.status.plan_check;
3302
3392
  if (record === void 0) throw new Error(`this deployment has a ${PLAN_FILE} but no record of which configuration produced it. Call terraform_plan again — it records the digest of the configuration it planned.`);
3303
- const current$1 = await hashConfiguration(directory);
3304
- if (current$1 !== record.tf_hash) throw new Error("the .tf files changed after the plan was computed. The saved plan describes a different configuration from the one on disk, so applying it would make changes nobody reviewed. Call terraform_plan again and show the user the new changes.");
3393
+ const current = await hashConfiguration(directory);
3394
+ if (current !== record.tf_hash) throw new Error("the .tf files changed after the plan was computed. The saved plan describes a different configuration from the one on disk, so applying it would make changes nobody reviewed. Call terraform_plan again and show the user the new changes.");
3305
3395
  }
3306
3396
  /** Where `terraform_plan({ destroy: true })` writes the destruction it previewed. */
3307
3397
  const DESTROY_PLAN_FILE = "destroy.plan.tfplan";
@@ -3338,8 +3428,8 @@ async function assertDestroyPreviewed(directory, readState, hashConfiguration, t
3338
3428
  const described = (list) => list.length === 0 ? "the whole deployment" : `only ${list.join(", ")}`;
3339
3429
  throw new Error(`the teardown previewed ${described(previewed)}, but this call asks to destroy ${described(requested)}. That is a different set of resources from the one the user approved. Call terraform_plan with destroy: true and the targets you intend to destroy, show that list, and then call terraform_destroy with the same targets.`);
3340
3430
  }
3341
- const current$1 = await hashConfiguration(directory);
3342
- if (current$1 !== record.tf_hash) throw new Error("the .tf files changed after the teardown was previewed. The saved destroy plan describes a different configuration. Call terraform_plan with destroy: true again and show the new list before destroying.");
3431
+ const current = await hashConfiguration(directory);
3432
+ if (current !== record.tf_hash) throw new Error("the .tf files changed after the teardown was previewed. The saved destroy plan describes a different configuration. Call terraform_plan with destroy: true again and show the new list before destroying.");
3343
3433
  }
3344
3434
 
3345
3435
  //#endregion
@@ -9163,8 +9253,8 @@ async function assertDesignChecked(directory, readState, hashConfiguration) {
9163
9253
  const check = state?.status.design_check;
9164
9254
  if (check === void 0) throw new Error("this deployment's network design has never been checked. Call validate_design — it runs terraform validate, reports the network problems terraform cannot see, and draws the topology for the user to approve. Then apply.");
9165
9255
  if (!check.ok) throw new Error("the last validate_design run on this configuration FAILED. Fix the diagnostics it reported, call it again, and get the user's agreement on the corrected design. A failed design is not an approved one.");
9166
- const current$1 = await hashConfiguration(directory);
9167
- if (current$1 !== check.tf_hash) throw new Error("the .tf files changed after the network design was checked. Call validate_design again: it re-checks the configuration and shows the user the current topology. Applying a design nobody reviewed is what this refusal prevents.");
9256
+ const current = await hashConfiguration(directory);
9257
+ if (current !== check.tf_hash) throw new Error("the .tf files changed after the network design was checked. Call validate_design again: it re-checks the configuration and shows the user the current topology. Applying a design nobody reviewed is what this refusal prevents.");
9168
9258
  }
9169
9259
  /**
9170
9260
  * How many network resources the configuration declares.
@@ -9368,8 +9458,8 @@ async function runCostGate(dir, hashConfiguration = computeTfHash) {
9368
9458
  if (record.priced_at === void 0) throw new Error(`${COST_FILE} carries no inquiry timestamp, so there is no telling when its figures were true. Call price_resources to record a dated quote.`);
9369
9459
  const recorded = typeof record.tf_hash === "string" ? record.tf_hash : void 0;
9370
9460
  if (recorded === void 0) throw new Error(`${COST_FILE} does not record which configuration it priced. Call price_resources to re-quote the current .tf.`);
9371
- const current$1 = await hashConfiguration(dir);
9372
- if (current$1 !== recorded) throw new Error("the .tf files changed after they were priced. The recorded total describes a configuration that will not be built. Call price_resources again and show the user the new figure before applying.");
9461
+ const current = await hashConfiguration(dir);
9462
+ if (current !== recorded) throw new Error("the .tf files changed after they were priced. The recorded total describes a configuration that will not be built. Call price_resources again and show the user the new figure before applying.");
9373
9463
  }
9374
9464
 
9375
9465
  //#endregion
@@ -10223,9 +10313,11 @@ async function spendPlan(deployment) {
10223
10313
  /**
10224
10314
  * Register this plugin's tools on the DSH tool registry.
10225
10315
  *
10226
- * Tool count: 18.
10316
+ * ## What the set covers
10227
10317
  *
10228
- * 部署目录 2 + 设计校验 1 + 规格 1 + 报价 1 + 华为云能力 4 + terraform 9 = 18
10318
+ * A deployment's lifecycle end to end: the workspace, the design check, the
10319
+ * flavour and image lookup, the quote, the HuaweiCloud capability surface, and
10320
+ * the terraform family that runs it.
10229
10321
  *
10230
10322
  * ## No tool accepts a price
10231
10323
  *
@@ -10297,28 +10389,58 @@ const PERMISSION_MODES = ["read_only", "read_write"];
10297
10389
  //#region src/permission-route.ts
10298
10390
  /** Route path, mounted under the host's authenticated `/api` fence. */
10299
10391
  const PERMISSION_PATH = "/api/aishell/permission";
10392
+ /**
10393
+ * Path for the posture new Sessions start in.
10394
+ *
10395
+ * A child of {@link PERMISSION_PATH}, registered separately: the fetch registry
10396
+ * matches whole paths rather than prefixes, so a posture request cannot land on
10397
+ * the conversation route by accident.
10398
+ */
10399
+ const PERMISSION_DEFAULT_PATH = `${PERMISSION_PATH}/default`;
10300
10400
  /** JSON response helper. */
10301
10401
  function json(body, status = 200) {
10302
10402
  return Response.json(body, { status });
10303
10403
  }
10404
+ /** A Session id as this route accepts one: non-empty, and nothing more. */
10405
+ function asSession(value) {
10406
+ return typeof value === "string" && value.trim().length > 0 ? value.trim() : void 0;
10407
+ }
10408
+ /** The Session a GET names in its query string. */
10409
+ function sessionOf(request) {
10410
+ return asSession(new URL(request.url, "http://dsh.invalid").searchParams.get("session"));
10411
+ }
10412
+ /** A mode as this route accepts one from a request. */
10413
+ function asMode(value) {
10414
+ return typeof value === "string" && PERMISSION_MODES.includes(value) ? value : void 0;
10415
+ }
10304
10416
  /**
10305
- * Report the current mode.
10417
+ * Report one Session's mode.
10306
10418
  *
10307
10419
  * @param deps - route collaborators.
10420
+ * @param request - the incoming GET; `session` names the conversation.
10308
10421
  */
10309
- function getMode(deps) {
10422
+ function handleGet(deps, request) {
10423
+ const session = sessionOf(request);
10424
+ if (session === void 0) return Promise.resolve(json({
10425
+ ok: false,
10426
+ error: "session is required"
10427
+ }, 400));
10428
+ if (!deps.known(session)) return Promise.resolve(json({
10429
+ ok: false,
10430
+ error: "session is not live"
10431
+ }, 404));
10310
10432
  return Promise.resolve(json({
10311
10433
  ok: true,
10312
- ...deps.read()
10434
+ ...deps.read(session)
10313
10435
  }));
10314
10436
  }
10315
10437
  /**
10316
- * Apply a mode.
10438
+ * Apply one Session's mode.
10317
10439
  *
10318
10440
  * @param deps - route collaborators.
10319
- * @param request - the incoming POST; its body carries `{ mode }`.
10441
+ * @param request - the incoming POST; its body carries `{ session, mode }`.
10320
10442
  */
10321
- async function setMode(deps, request) {
10443
+ async function handleSet(deps, request) {
10322
10444
  let body;
10323
10445
  try {
10324
10446
  body = await request.json();
@@ -10328,18 +10450,65 @@ async function setMode(deps, request) {
10328
10450
  error: "Request body is not valid JSON."
10329
10451
  }, 400);
10330
10452
  }
10331
- const mode = body?.mode;
10332
- if (typeof mode !== "string" || !PERMISSION_MODES.includes(mode)) return json({
10453
+ const fields = body;
10454
+ const session = asSession(fields?.session);
10455
+ if (session === void 0) return json({
10456
+ ok: false,
10457
+ error: "session is required"
10458
+ }, 400);
10459
+ if (!deps.known(session)) return json({
10460
+ ok: false,
10461
+ error: "session is not live"
10462
+ }, 404);
10463
+ const mode = asMode(fields?.mode);
10464
+ if (mode === void 0) return json({
10333
10465
  ok: false,
10334
10466
  error: `mode must be one of: ${PERMISSION_MODES.join(", ")}`
10335
10467
  }, 400);
10336
- const change = deps.write(mode);
10468
+ const change = deps.write(session, mode);
10337
10469
  return json({
10338
10470
  ok: true,
10339
10471
  ...change
10340
10472
  });
10341
10473
  }
10342
10474
  /**
10475
+ * Report the posture new Sessions start in.
10476
+ *
10477
+ * @param deps - route collaborators.
10478
+ */
10479
+ function handleGetDefault(deps) {
10480
+ return Promise.resolve(json({
10481
+ ok: true,
10482
+ mode: deps.readDefault()
10483
+ }));
10484
+ }
10485
+ /**
10486
+ * Set the posture new Sessions start in.
10487
+ *
10488
+ * @param deps - route collaborators.
10489
+ * @param request - the incoming POST; its body carries `{ mode }`.
10490
+ */
10491
+ async function handleSetDefault(deps, request) {
10492
+ let body;
10493
+ try {
10494
+ body = await request.json();
10495
+ } catch {
10496
+ return json({
10497
+ ok: false,
10498
+ error: "Request body is not valid JSON."
10499
+ }, 400);
10500
+ }
10501
+ const mode = asMode(body?.mode);
10502
+ if (mode === void 0) return json({
10503
+ ok: false,
10504
+ error: `mode must be one of: ${PERMISSION_MODES.join(", ")}`
10505
+ }, 400);
10506
+ return json({
10507
+ ok: true,
10508
+ mode: deps.writeDefault(mode)
10509
+ });
10510
+ }
10511
+ /**
10343
10512
  * Build the route handlers.
10344
10513
  *
10345
10514
  * @param deps - route collaborators.
@@ -10347,8 +10516,10 @@ async function setMode(deps, request) {
10347
10516
  */
10348
10517
  function createPermissionRoutes(deps) {
10349
10518
  return {
10350
- get: () => getMode(deps),
10351
- set: (request) => setMode(deps, request)
10519
+ get: (request) => handleGet(deps, request),
10520
+ set: (request) => handleSet(deps, request),
10521
+ getDefault: () => handleGetDefault(deps),
10522
+ setDefault: (request) => handleSetDefault(deps, request)
10352
10523
  };
10353
10524
  }
10354
10525
 
@@ -10396,22 +10567,40 @@ function permissionPolicyText(mode) {
10396
10567
  *
10397
10568
  * Deferred behind `ctx.inject` rather than declared in this plugin's own
10398
10569
  * `inject`: the policy is an enhancement, and a deployment without the system
10399
- * prompt should not lose the tools over it. `current` is a function because the
10400
- * context provider is synchronous and evaluated per assembly, so the mode is
10401
- * read from the module state at that moment rather than captured once.
10570
+ * prompt should not lose the tools over it.
10571
+ *
10572
+ * `current` is called with the assembling agent's id, which is the Session the
10573
+ * prompt is being built for — so a conversation in read-write is not told it is
10574
+ * read-only because a neighbouring one is.
10402
10575
  *
10403
10576
  * @param ctx - host context.
10404
- * @param current - the mode last read or applied, or `undefined` if not yet read.
10577
+ * @param current - the mode of the Session the assembly is for.
10405
10578
  */
10406
- function registerPermissionPolicyContext(ctx, current$1) {
10579
+ function registerPermissionPolicyContext(ctx, current) {
10407
10580
  ctx.inject(["systemPrompt"], (scope) => {
10408
10581
  scope.systemPrompt.context({
10409
10582
  name: PERMISSION_CONTEXT_NAME,
10410
10583
  order: scope.systemPrompt.getContextOrder("APPROVAL_POLICY"),
10411
- text: () => permissionPolicyText(current$1())
10584
+ text: (context) => permissionPolicyText(current(agentSession(context)))
10412
10585
  });
10413
10586
  });
10414
10587
  }
10588
+ /**
10589
+ * The Session one assembly is for.
10590
+ *
10591
+ * Every real assembly carries its agent — the harness sets agent and scope
10592
+ * together, so an agent-scoped contribution cannot be silently omitted (see
10593
+ * `assembleContextFor` in dsh-agent). A diagnostic assembly carries none, and
10594
+ * then the policy is asked for with no Session rather than guessing one.
10595
+ *
10596
+ * The parameter is the framework's own `AssembleContext`, whose `agent` arrives
10597
+ * through a type merge owned by dsh-agent: reading it through the declared type
10598
+ * is what keeps this function and that contract in step.
10599
+ */
10600
+ function agentSession(context) {
10601
+ const id = context.agent?.id;
10602
+ return typeof id === "string" && id.length > 0 ? id : void 0;
10603
+ }
10415
10604
 
10416
10605
  //#endregion
10417
10606
  //#region src/prompt.ts
@@ -10778,8 +10967,15 @@ const name = "aishell-deploy";
10778
10967
  * `connection` is required because the permission route registers on the host's
10779
10968
  * authenticated fetch registry, and a plugin that silently lost its permission
10780
10969
  * switch would leave every mutation at the default.
10781
- */
10782
- const inject = ["tools", "connection"];
10970
+ * `sessions` is required because the permission mode is filed per Session: a
10971
+ * conversation is pinned to the posture when it is created, and the store is
10972
+ * what makes that possible for Sessions that exist before this plugin mounts.
10973
+ */
10974
+ const inject = [
10975
+ "tools",
10976
+ "connection",
10977
+ "sessions"
10978
+ ];
10783
10979
  function apply(ctx, config) {
10784
10980
  const log = ctx.logger("aishell-deploy");
10785
10981
  const store = createCredentialsStore();
@@ -10805,7 +11001,14 @@ function apply(ctx, config) {
10805
11001
  for (const dispose of disposers) dispose();
10806
11002
  }, "aishell-deploy: tools");
10807
11003
  log.info(`registered ${disposers.length} Huawei Cloud tool(s)`);
10808
- log.info(`permission mode: ${getMode$1()}`);
11004
+ log.info(`permission posture for new sessions: ${defaultPosture()}`);
11005
+ ctx.effect(() => ctx.on("session/disposed", (session) => {
11006
+ forgetSession(session.id);
11007
+ }), "aishell-deploy: forget disposed session modes");
11008
+ ctx.effect(() => ctx.on("session/created", (session) => {
11009
+ pinSession(session.id);
11010
+ }), "aishell-deploy: pin created session modes");
11011
+ for (const session of ctx.sessions.list()) pinSession(session.id);
10809
11012
  /**
10810
11013
  * The account name `aishell-credentials` recorded after verifying the pair
10811
11014
  * against IAM.
@@ -10833,47 +11036,58 @@ function apply(ctx, config) {
10833
11036
  * would be the wrong attribution.
10834
11037
  */
10835
11038
  const recordChange$1 = (change) => {
10836
- const ak = readStoredPair(store)?.ak;
10837
- auditCtx.audit.record({
10838
- action: "permission.mode",
10839
- outcome: change.mode === "read_write" ? "granted" : "revoked",
10840
- ...ak === void 0 ? {} : { subject: auditSubject(ak, accountName()) },
10841
- actor: change.actor,
10842
- detail: change.previous === void 0 ? { to: change.mode } : {
10843
- from: change.previous,
10844
- to: change.mode
10845
- }
10846
- });
11039
+ try {
11040
+ const ak = readStoredPair(store)?.ak;
11041
+ auditCtx.audit.record({
11042
+ action: "permission.mode",
11043
+ outcome: change.mode === "read_write" ? "granted" : "revoked",
11044
+ ...ak === void 0 ? {} : { subject: auditSubject(ak, accountName()) },
11045
+ actor: change.actor,
11046
+ detail: {
11047
+ ...change.previous === void 0 ? { to: change.mode } : {
11048
+ from: change.previous,
11049
+ to: change.mode
11050
+ },
11051
+ ...change.session === void 0 ? {} : { session: change.session }
11052
+ }
11053
+ });
11054
+ } catch {}
10847
11055
  };
10848
- if (defaultMode() === "read_write") recordChange$1({
11056
+ recordChange$1({
11057
+ session: void 0,
10849
11058
  previous: void 0,
10850
- mode: "read_write",
11059
+ mode: defaultPosture(),
10851
11060
  actor: "startup"
10852
11061
  });
10853
11062
  auditCtx.effect(() => installPermissionRecorder(recordChange$1), "aishell-deploy: permission audit recorder");
10854
11063
  });
10855
11064
  const routes = createPermissionRoutes({
10856
- read: () => ({
10857
- mode: getMode$1(),
10858
- default: defaultMode(),
10859
- writable: writesAllowed()
10860
- }),
10861
- write: (next) => {
10862
- const previous = setMode$1(next);
11065
+ known: (session) => ctx.sessions.get(session) !== void 0,
11066
+ read: (session) => ({ mode: getMode(session) }),
11067
+ write: (session, next) => {
11068
+ const previous = setMode(session, next);
10863
11069
  return {
10864
- mode: getMode$1(),
11070
+ mode: getMode(session),
10865
11071
  previous,
10866
11072
  changed: previous !== next
10867
11073
  };
10868
- }
11074
+ },
11075
+ readDefault: () => defaultPosture(),
11076
+ writeDefault: (next) => setDefaultPosture(next)
10869
11077
  });
10870
11078
  ctx.effect(() => ctx.connection.fetch.register({
10871
11079
  path: PERMISSION_PATH,
10872
11080
  methods: ["GET", "POST"],
10873
11081
  requestBody: "buffered",
10874
- fetch: (request) => request.method === "GET" ? routes.get() : routes.set(request)
11082
+ fetch: (request) => request.method === "GET" ? routes.get(request) : routes.set(request)
10875
11083
  }), "aishell-deploy: permission route");
10876
- registerPermissionPolicyContext(ctx, () => getMode$1());
11084
+ ctx.effect(() => ctx.connection.fetch.register({
11085
+ path: PERMISSION_DEFAULT_PATH,
11086
+ methods: ["GET", "POST"],
11087
+ requestBody: "buffered",
11088
+ fetch: (request) => request.method === "GET" ? routes.getDefault() : routes.setDefault(request)
11089
+ }), "aishell-deploy: permission posture route");
11090
+ registerPermissionPolicyContext(ctx, (session) => getMode(session));
10877
11091
  registerDeployWorkflow(ctx);
10878
11092
  ctx.effect(() => ctx.on("aishell/credentials-updated", () => {
10879
11093
  forgetAccount();