@huaweidevtools/aishell-dsh-deploy 0.0.36 → 0.0.38

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,40 @@ function installPermissionRecorder(record) {
1246
1251
  };
1247
1252
  }
1248
1253
  /**
1249
- * Environment variable holding the startup default.
1254
+ * What a module answers before any deployment statement is applied.
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, and the value {@link resetMode} restores: a restart must come back
1257
+ * to a state the process can defend without having been told anything, not to
1258
+ * whatever a caller happened to set last.
1255
1259
  */
1256
- const DEFAULT_MODE_ENV = "HW_DEFAULT_PERMISSION";
1257
- /** The mode when nothing overrides it. */
1258
- const FALLBACK_MODE = "read_only";
1260
+ const DEFAULT_POSTURE = "read_only";
1259
1261
  /**
1260
- * Parse a mode string.
1262
+ * The posture new Sessions are pinned to.
1261
1263
  *
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.
1264
+ * Starts at {@link DEFAULT_POSTURE} and is set from the deployment's
1265
+ * `startupPosture` once the plugin mounts, then by a running override
1266
+ * afterwards. Not retroactive — see the module header.
1268
1267
  */
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
- }
1268
+ let posture = DEFAULT_POSTURE;
1269
+ /** Modes by Session. Every created Session has an entry; `posture` covers the rest. */
1270
+ const modes = new Map();
1271
+ /** The mode one Session may act under. */
1272
+ function getMode(session) {
1273
+ if (session === void 0) return posture;
1274
+ return modes.get(session) ?? posture;
1282
1275
  }
1283
1276
  /**
1284
- * The mode this process started in.
1277
+ * The posture new Sessions start in.
1285
1278
  *
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.
1279
+ * Read through a function rather than exported as a value: the route and the
1280
+ * client both report it, and a snapshot taken at import time would go stale the
1281
+ * first time a deployment sets it.
1290
1282
  */
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;
1283
+ function defaultPosture() {
1284
+ return posture;
1297
1285
  }
1298
1286
  /**
1299
- * Set the mode.
1287
+ * Set one Session's mode.
1300
1288
  *
1301
1289
  * ## Why the notification lives here
1302
1290
  *
@@ -1309,28 +1297,144 @@ function getMode$1() {
1309
1297
  * notified: the chip re-reads the state after every call, and recording those
1310
1298
  * would fill the trail with actions nobody took.
1311
1299
  *
1300
+ * A mode is stored under its Session for as long as that Session lives, whatever
1301
+ * its value. Only a Session that has never been given one follows the posture;
1302
+ * once a conversation has an answer of its own, that answer is the one it keeps,
1303
+ * so a later posture change cannot revise a decision already made about it.
1304
+ *
1305
+ * @param session - the Session the mode applies to.
1312
1306
  * @param mode - the mode to apply.
1313
1307
  * @param actor - who is setting it; the route is the only production caller, so
1314
1308
  * the default is the person at the console.
1315
- * @returns the previous mode, for a change log.
1309
+ * @returns the mode the Session was in, for a change log.
1316
1310
  */
1317
- function setMode$1(mode, actor = "user") {
1318
- const previous = current;
1319
- current = mode;
1311
+ function setMode(session, mode, actor = "user") {
1312
+ const previous = getMode(session);
1313
+ modes.set(session, mode);
1320
1314
  if (previous !== mode) recordChange?.({
1315
+ session,
1321
1316
  previous,
1322
1317
  mode,
1323
1318
  actor
1324
1319
  });
1325
1320
  return previous;
1326
1321
  }
1327
- /** Whether mutations are currently permitted. */
1328
- function writesAllowed() {
1329
- return current === "read_write";
1322
+ /**
1323
+ * Whether one Session may mutate the cloud.
1324
+ *
1325
+ * `undefined` is "no Session" — a call outside a conversation, which answers
1326
+ * with the posture. Every production tool call carries a Session, so that arm
1327
+ * describes a call this plugin does not place in any conversation; it is not a
1328
+ * separate policy, and a deployment that widened the posture widened it too.
1329
+ */
1330
+ function writesAllowed(session) {
1331
+ return getMode(session) === "read_write";
1332
+ }
1333
+ /**
1334
+ * Give one Session its own mode, decided by the posture in force at that moment.
1335
+ *
1336
+ * Every Session carries an entry from the moment it starts, which is what makes
1337
+ * a posture change reach only Sessions that have not started. A Session that
1338
+ * already has an entry keeps it, so a conversation on screen is never widened
1339
+ * from underneath the person reading it — and a restored one re-enters with no
1340
+ * entry, taking the posture the process started with.
1341
+ *
1342
+ * @param session - the Session being started.
1343
+ */
1344
+ function pinSession(session) {
1345
+ if (!modes.has(session)) modes.set(session, posture);
1346
+ }
1347
+ /**
1348
+ * Apply the posture a deployment configured, before anything else runs.
1349
+ *
1350
+ * Separate from {@link setDefaultPosture} because it describes two different
1351
+ * acts: this is the value the process starts in, which the plugin records once
1352
+ * as the trail's first entry under the `startup` actor; that one is a switch a
1353
+ * person makes, recorded under `user`. One record per act, and the trail names
1354
+ * who acted.
1355
+ *
1356
+ * Called before Sessions are pinned, so the Sessions already open when the
1357
+ * plugin mounts (and every one created afterwards) start under the value the
1358
+ * deployment declared.
1359
+ *
1360
+ * @param mode - the configured posture.
1361
+ */
1362
+ function applyStartupPosture(mode) {
1363
+ posture = mode;
1364
+ }
1365
+ /**
1366
+ * Set the posture new Sessions start in.
1367
+ *
1368
+ * Every Session already has an entry of its own, so this decides what Sessions
1369
+ * created from now on begin with and leaves existing conversations as they are.
1370
+ * It is an override of the deployment's `startupPosture` for this process: the
1371
+ * next start reads the configured value again.
1372
+ *
1373
+ * @param mode - the posture to apply.
1374
+ * @returns the posture it replaced.
1375
+ */
1376
+ function setDefaultPosture(mode) {
1377
+ const previous = posture;
1378
+ posture = mode;
1379
+ if (previous !== mode) recordChange?.({
1380
+ session: void 0,
1381
+ previous,
1382
+ mode,
1383
+ actor: "user"
1384
+ });
1385
+ return previous;
1386
+ }
1387
+ /**
1388
+ * Forget one Session's mode.
1389
+ *
1390
+ * Called when the Session is disposed: the map is keyed by an identity that
1391
+ * will not be seen again, and a long-running process opens sessions for as long
1392
+ * as it runs.
1393
+ */
1394
+ function forgetSession(session) {
1395
+ modes.delete(session);
1330
1396
  }
1331
- /** The mode this process started in, for logging and for `permission/get_mode`. */
1332
- function defaultMode() {
1333
- return STARTUP_MODE;
1397
+
1398
+ //#endregion
1399
+ //#region src/permission/call-context.ts
1400
+ /** One call's Session, as read inside the asynchronous chain serving it. */
1401
+ const storage = new AsyncLocalStorage();
1402
+ /**
1403
+ * Run one call with its Session in scope.
1404
+ *
1405
+ * @param session - the Session the call is made for.
1406
+ * @param body - the work; anything it awaits reads the same Session.
1407
+ * @returns whatever `body` returns.
1408
+ */
1409
+ function runForSession(session, body) {
1410
+ return storage.run(session, body);
1411
+ }
1412
+ /**
1413
+ * Run one call that belongs to no Session.
1414
+ *
1415
+ * The store would otherwise be inherited from whatever call is already in
1416
+ * scope, which would credit this call to a conversation it is not part of. A
1417
+ * call the harness gave no Session belongs to no conversation, and the gates
1418
+ * judge it by the posture — the same answer as a call made outside any tool
1419
+ * execution.
1420
+ *
1421
+ * @param body - the work.
1422
+ * @returns whatever `body` returns.
1423
+ */
1424
+ function runWithoutSession(body) {
1425
+ return storage.exit(body);
1426
+ }
1427
+ /**
1428
+ * The Session the current call serves, if any.
1429
+ *
1430
+ * `undefined` outside any call this plugin placed in scope: at module level, on
1431
+ * work detached from the process, or inside a call the harness gave no Session.
1432
+ * The gate treats that as a call with no Session rather than inventing one.
1433
+ *
1434
+ * @returns the Session key, or `undefined`.
1435
+ */
1436
+ function currentSession() {
1437
+ return storage.getStore();
1334
1438
  }
1335
1439
 
1336
1440
  //#endregion
@@ -1568,26 +1672,34 @@ function logDenial(detail) {
1568
1672
  * Check a tool call against read-only mode.
1569
1673
  *
1570
1674
  * @param toolName - the tool about to run.
1675
+ * @param session - the Session it runs for; the executor has it, so it is passed
1676
+ * rather than read from the call context.
1571
1677
  * @returns a message to return as a failed tool result, or `undefined` to proceed.
1572
1678
  */
1573
- function denyTool(toolName) {
1574
- if (writesAllowed()) return void 0;
1679
+ function denyTool(toolName, session) {
1680
+ if (writesAllowed(session)) return void 0;
1575
1681
  if (!CLOUD_MUTATING_TOOLS.has(toolName)) return void 0;
1576
- logDenial(`refused tool ${toolName} (mode=${getMode$1()})`);
1682
+ logDenial(`refused tool ${toolName} (session=${session ?? "none"}, mode=${getMode(session)})`);
1577
1683
  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
1684
  }
1579
1685
  /**
1580
1686
  * Check a signed HTTP request against read-only mode.
1581
1687
  *
1688
+ * The Session comes from the call context: every signed request is made inside a
1689
+ * tool execution, and the context carries that tool's Session down to this
1690
+ * funnel. See `./call-context.ts` for why it travels with the call rather than
1691
+ * as an argument.
1692
+ *
1582
1693
  * @param method - HTTP method.
1583
1694
  * @param url - the full request URL.
1584
1695
  * @returns a message describing the refusal, or `undefined` to proceed.
1585
1696
  */
1586
1697
  function denyHttp(method, url) {
1587
- if (writesAllowed()) return void 0;
1698
+ const session = currentSession();
1699
+ if (writesAllowed(session)) return void 0;
1588
1700
  const decision = isReadOnlyPermitted(method, url);
1589
1701
  if (decision.allowed) return void 0;
1590
- logDenial(`refused ${method.toUpperCase()} ${url.hostname}${url.pathname} (mode=${getMode$1()}, reason=${decision.reason})`);
1702
+ logDenial(`refused ${method.toUpperCase()} ${url.hostname}${url.pathname} (session=${session ?? "none"}, mode=${getMode(session)}, reason=${decision.reason})`);
1591
1703
  switch (decision.reason) {
1592
1704
  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
1705
  case "registry-miss":
@@ -1674,15 +1786,20 @@ function fail(message) {
1674
1786
  * not reach any part of its implementation, including argument validation that
1675
1787
  * might touch the filesystem. A tool declared in `CLOUD_MUTATING_TOOLS` is
1676
1788
  * refused here in read-only mode and never starts.
1789
+ *
1790
+ * The handler then runs inside the Session's call context, so the signed-HTTP
1791
+ * funnel — several layers down, with no Session parameter to pass — refuses
1792
+ * against the same Session this gate just read.
1677
1793
  */
1678
1794
  function guard(fn, toolName) {
1679
1795
  return async (args, ctx) => {
1680
1796
  if (toolName !== void 0) {
1681
- const refusal = denyTool(toolName);
1797
+ const refusal = denyTool(toolName, ctx.sessionId);
1682
1798
  if (refusal !== void 0) return fail(refusal);
1683
1799
  }
1684
1800
  try {
1685
- return await fn(withAnchoredPaths(args, ctx), ctx);
1801
+ const body = () => fn(withAnchoredPaths(args, ctx), ctx);
1802
+ return await (ctx.sessionId === void 0 ? runWithoutSession(body) : runForSession(ctx.sessionId, body));
1686
1803
  } catch (err) {
1687
1804
  const msg = err instanceof Error ? err.message : String(err);
1688
1805
  return fail(msg);
@@ -1745,7 +1862,7 @@ function withAnchoredPaths(args, ctx) {
1745
1862
  * written by earlier releases carry it — so it is kept even though there is no
1746
1863
  * server.
1747
1864
  */
1748
- const SERVER_VERSION = "aishell-deploy 0.0.36";
1865
+ const SERVER_VERSION = "aishell-deploy 0.0.38";
1749
1866
 
1750
1867
  //#endregion
1751
1868
  //#region src/deployment-state.ts
@@ -2324,7 +2441,7 @@ async function fileExists(path) {
2324
2441
  * @returns a refusal message, or `undefined` to proceed.
2325
2442
  */
2326
2443
  function denyTerraformMutation(args) {
2327
- if (writesAllowed()) return void 0;
2444
+ if (writesAllowed(currentSession())) return void 0;
2328
2445
  const subcommand = args[0];
2329
2446
  if (subcommand !== "apply" && subcommand !== "destroy") return void 0;
2330
2447
  if (args.includes("-refresh-only")) return void 0;
@@ -3300,8 +3417,8 @@ async function assertPlanApproved(directory, readState, hashConfiguration) {
3300
3417
  const state = await readState(directory);
3301
3418
  const record = state?.status.plan_check;
3302
3419
  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.");
3420
+ const current = await hashConfiguration(directory);
3421
+ 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
3422
  }
3306
3423
  /** Where `terraform_plan({ destroy: true })` writes the destruction it previewed. */
3307
3424
  const DESTROY_PLAN_FILE = "destroy.plan.tfplan";
@@ -3338,8 +3455,8 @@ async function assertDestroyPreviewed(directory, readState, hashConfiguration, t
3338
3455
  const described = (list) => list.length === 0 ? "the whole deployment" : `only ${list.join(", ")}`;
3339
3456
  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
3457
  }
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.");
3458
+ const current = await hashConfiguration(directory);
3459
+ 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
3460
  }
3344
3461
 
3345
3462
  //#endregion
@@ -9163,8 +9280,8 @@ async function assertDesignChecked(directory, readState, hashConfiguration) {
9163
9280
  const check = state?.status.design_check;
9164
9281
  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
9282
  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.");
9283
+ const current = await hashConfiguration(directory);
9284
+ 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
9285
  }
9169
9286
  /**
9170
9287
  * How many network resources the configuration declares.
@@ -9368,8 +9485,8 @@ async function runCostGate(dir, hashConfiguration = computeTfHash) {
9368
9485
  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
9486
  const recorded = typeof record.tf_hash === "string" ? record.tf_hash : void 0;
9370
9487
  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.");
9488
+ const current = await hashConfiguration(dir);
9489
+ 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
9490
  }
9374
9491
 
9375
9492
  //#endregion
@@ -10223,9 +10340,11 @@ async function spendPlan(deployment) {
10223
10340
  /**
10224
10341
  * Register this plugin's tools on the DSH tool registry.
10225
10342
  *
10226
- * Tool count: 18.
10343
+ * ## What the set covers
10227
10344
  *
10228
- * 部署目录 2 + 设计校验 1 + 规格 1 + 报价 1 + 华为云能力 4 + terraform 9 = 18
10345
+ * A deployment's lifecycle end to end: the workspace, the design check, the
10346
+ * flavour and image lookup, the quote, the HuaweiCloud capability surface, and
10347
+ * the terraform family that runs it.
10229
10348
  *
10230
10349
  * ## No tool accepts a price
10231
10350
  *
@@ -10297,28 +10416,58 @@ const PERMISSION_MODES = ["read_only", "read_write"];
10297
10416
  //#region src/permission-route.ts
10298
10417
  /** Route path, mounted under the host's authenticated `/api` fence. */
10299
10418
  const PERMISSION_PATH = "/api/aishell/permission";
10419
+ /**
10420
+ * Path for the posture new Sessions start in.
10421
+ *
10422
+ * A child of {@link PERMISSION_PATH}, registered separately: the fetch registry
10423
+ * matches whole paths rather than prefixes, so a posture request cannot land on
10424
+ * the conversation route by accident.
10425
+ */
10426
+ const PERMISSION_DEFAULT_PATH = `${PERMISSION_PATH}/default`;
10300
10427
  /** JSON response helper. */
10301
10428
  function json(body, status = 200) {
10302
10429
  return Response.json(body, { status });
10303
10430
  }
10431
+ /** A Session id as this route accepts one: non-empty, and nothing more. */
10432
+ function asSession(value) {
10433
+ return typeof value === "string" && value.trim().length > 0 ? value.trim() : void 0;
10434
+ }
10435
+ /** The Session a GET names in its query string. */
10436
+ function sessionOf(request) {
10437
+ return asSession(new URL(request.url, "http://dsh.invalid").searchParams.get("session"));
10438
+ }
10439
+ /** A mode as this route accepts one from a request. */
10440
+ function asMode(value) {
10441
+ return typeof value === "string" && PERMISSION_MODES.includes(value) ? value : void 0;
10442
+ }
10304
10443
  /**
10305
- * Report the current mode.
10444
+ * Report one Session's mode.
10306
10445
  *
10307
10446
  * @param deps - route collaborators.
10447
+ * @param request - the incoming GET; `session` names the conversation.
10308
10448
  */
10309
- function getMode(deps) {
10449
+ function handleGet(deps, request) {
10450
+ const session = sessionOf(request);
10451
+ if (session === void 0) return Promise.resolve(json({
10452
+ ok: false,
10453
+ error: "session is required"
10454
+ }, 400));
10455
+ if (!deps.known(session)) return Promise.resolve(json({
10456
+ ok: false,
10457
+ error: "session is not live"
10458
+ }, 404));
10310
10459
  return Promise.resolve(json({
10311
10460
  ok: true,
10312
- ...deps.read()
10461
+ ...deps.read(session)
10313
10462
  }));
10314
10463
  }
10315
10464
  /**
10316
- * Apply a mode.
10465
+ * Apply one Session's mode.
10317
10466
  *
10318
10467
  * @param deps - route collaborators.
10319
- * @param request - the incoming POST; its body carries `{ mode }`.
10468
+ * @param request - the incoming POST; its body carries `{ session, mode }`.
10320
10469
  */
10321
- async function setMode(deps, request) {
10470
+ async function handleSet(deps, request) {
10322
10471
  let body;
10323
10472
  try {
10324
10473
  body = await request.json();
@@ -10328,18 +10477,65 @@ async function setMode(deps, request) {
10328
10477
  error: "Request body is not valid JSON."
10329
10478
  }, 400);
10330
10479
  }
10331
- const mode = body?.mode;
10332
- if (typeof mode !== "string" || !PERMISSION_MODES.includes(mode)) return json({
10480
+ const fields = body;
10481
+ const session = asSession(fields?.session);
10482
+ if (session === void 0) return json({
10483
+ ok: false,
10484
+ error: "session is required"
10485
+ }, 400);
10486
+ if (!deps.known(session)) return json({
10487
+ ok: false,
10488
+ error: "session is not live"
10489
+ }, 404);
10490
+ const mode = asMode(fields?.mode);
10491
+ if (mode === void 0) return json({
10333
10492
  ok: false,
10334
10493
  error: `mode must be one of: ${PERMISSION_MODES.join(", ")}`
10335
10494
  }, 400);
10336
- const change = deps.write(mode);
10495
+ const change = deps.write(session, mode);
10337
10496
  return json({
10338
10497
  ok: true,
10339
10498
  ...change
10340
10499
  });
10341
10500
  }
10342
10501
  /**
10502
+ * Report the posture new Sessions start in.
10503
+ *
10504
+ * @param deps - route collaborators.
10505
+ */
10506
+ function handleGetDefault(deps) {
10507
+ return Promise.resolve(json({
10508
+ ok: true,
10509
+ mode: deps.readDefault()
10510
+ }));
10511
+ }
10512
+ /**
10513
+ * Set the posture new Sessions start in.
10514
+ *
10515
+ * @param deps - route collaborators.
10516
+ * @param request - the incoming POST; its body carries `{ mode }`.
10517
+ */
10518
+ async function handleSetDefault(deps, request) {
10519
+ let body;
10520
+ try {
10521
+ body = await request.json();
10522
+ } catch {
10523
+ return json({
10524
+ ok: false,
10525
+ error: "Request body is not valid JSON."
10526
+ }, 400);
10527
+ }
10528
+ const mode = asMode(body?.mode);
10529
+ if (mode === void 0) return json({
10530
+ ok: false,
10531
+ error: `mode must be one of: ${PERMISSION_MODES.join(", ")}`
10532
+ }, 400);
10533
+ return json({
10534
+ ok: true,
10535
+ mode: deps.writeDefault(mode)
10536
+ });
10537
+ }
10538
+ /**
10343
10539
  * Build the route handlers.
10344
10540
  *
10345
10541
  * @param deps - route collaborators.
@@ -10347,8 +10543,10 @@ async function setMode(deps, request) {
10347
10543
  */
10348
10544
  function createPermissionRoutes(deps) {
10349
10545
  return {
10350
- get: () => getMode(deps),
10351
- set: (request) => setMode(deps, request)
10546
+ get: (request) => handleGet(deps, request),
10547
+ set: (request) => handleSet(deps, request),
10548
+ getDefault: () => handleGetDefault(deps),
10549
+ setDefault: (request) => handleSetDefault(deps, request)
10352
10550
  };
10353
10551
  }
10354
10552
 
@@ -10396,22 +10594,40 @@ function permissionPolicyText(mode) {
10396
10594
  *
10397
10595
  * Deferred behind `ctx.inject` rather than declared in this plugin's own
10398
10596
  * `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.
10597
+ * prompt should not lose the tools over it.
10598
+ *
10599
+ * `current` is called with the assembling agent's id, which is the Session the
10600
+ * prompt is being built for — so a conversation in read-write is not told it is
10601
+ * read-only because a neighbouring one is.
10402
10602
  *
10403
10603
  * @param ctx - host context.
10404
- * @param current - the mode last read or applied, or `undefined` if not yet read.
10604
+ * @param current - the mode of the Session the assembly is for.
10405
10605
  */
10406
- function registerPermissionPolicyContext(ctx, current$1) {
10606
+ function registerPermissionPolicyContext(ctx, current) {
10407
10607
  ctx.inject(["systemPrompt"], (scope) => {
10408
10608
  scope.systemPrompt.context({
10409
10609
  name: PERMISSION_CONTEXT_NAME,
10410
10610
  order: scope.systemPrompt.getContextOrder("APPROVAL_POLICY"),
10411
- text: () => permissionPolicyText(current$1())
10611
+ text: (context) => permissionPolicyText(current(agentSession(context)))
10412
10612
  });
10413
10613
  });
10414
10614
  }
10615
+ /**
10616
+ * The Session one assembly is for.
10617
+ *
10618
+ * Every real assembly carries its agent — the harness sets agent and scope
10619
+ * together, so an agent-scoped contribution cannot be silently omitted (see
10620
+ * `assembleContextFor` in dsh-agent). A diagnostic assembly carries none, and
10621
+ * then the policy is asked for with no Session rather than guessing one.
10622
+ *
10623
+ * The parameter is the framework's own `AssembleContext`, whose `agent` arrives
10624
+ * through a type merge owned by dsh-agent: reading it through the declared type
10625
+ * is what keeps this function and that contract in step.
10626
+ */
10627
+ function agentSession(context) {
10628
+ const id = context.agent?.id;
10629
+ return typeof id === "string" && id.length > 0 ? id : void 0;
10630
+ }
10415
10631
 
10416
10632
  //#endregion
10417
10633
  //#region src/prompt.ts
@@ -10756,9 +10972,13 @@ function auditSubject(accessKey, name$1) {
10756
10972
  /**
10757
10973
  * Settings schema.
10758
10974
  *
10759
- * Every field is Volatile: each is a deployment fact that may differ between
10760
- * profiles, and a change should apply to the next call rather than require a
10761
- * restart. The bridge reads them through thunks for that reason.
10975
+ * A field is Volatile when its change should apply to the next call rather than
10976
+ * require a restart — a deployment fact that may differ between profiles. The
10977
+ * bridge reads those through thunks for that reason.
10978
+ *
10979
+ * `startupPosture` is plain: a posture is what a Session begins with, and
10980
+ * Sessions that already exist keep the answer they were pinned to, so the field
10981
+ * is read once at mount rather than per call.
10762
10982
  *
10763
10983
  * `defaultRegion` has no `.default()`. A built-in region would be a guess
10764
10984
  * dressed as configuration — the one thing this plugin must not do, because the
@@ -10768,7 +10988,8 @@ function auditSubject(accessKey, name$1) {
10768
10988
  */
10769
10989
  const Config = Schema.object({
10770
10990
  defaultRegion: Schema.string().volatile(),
10771
- toolCallTimeoutMs: Schema.number().step(1).min(1).default(DEFAULT_TOOL_CALL_TIMEOUT_MS).volatile()
10991
+ toolCallTimeoutMs: Schema.number().step(1).min(1).default(DEFAULT_TOOL_CALL_TIMEOUT_MS).volatile(),
10992
+ startupPosture: Schema.union([Schema.const("read_only"), Schema.const("read_write")]).default("read_only")
10772
10993
  });
10773
10994
  const name = "aishell-deploy";
10774
10995
  /**
@@ -10778,8 +10999,15 @@ const name = "aishell-deploy";
10778
10999
  * `connection` is required because the permission route registers on the host's
10779
11000
  * authenticated fetch registry, and a plugin that silently lost its permission
10780
11001
  * switch would leave every mutation at the default.
10781
- */
10782
- const inject = ["tools", "connection"];
11002
+ * `sessions` is required because the permission mode is filed per Session: a
11003
+ * conversation is pinned to the posture when it starts, and the store is what
11004
+ * makes that possible for Sessions that exist before this plugin mounts.
11005
+ */
11006
+ const inject = [
11007
+ "tools",
11008
+ "connection",
11009
+ "sessions"
11010
+ ];
10783
11011
  function apply(ctx, config) {
10784
11012
  const log = ctx.logger("aishell-deploy");
10785
11013
  const store = createCredentialsStore();
@@ -10805,7 +11033,26 @@ function apply(ctx, config) {
10805
11033
  for (const dispose of disposers) dispose();
10806
11034
  }, "aishell-deploy: tools");
10807
11035
  log.info(`registered ${disposers.length} Huawei Cloud tool(s)`);
10808
- log.info(`permission mode: ${getMode$1()}`);
11036
+ applyStartupPosture(config.startupPosture);
11037
+ /**
11038
+ * The posture this process started in.
11039
+ *
11040
+ * Captured here, before any switch can be accepted, because the audit trail
11041
+ * records it as its first entry — and that record is written later, when the
11042
+ * audit service becomes available. Reading `defaultPosture()` at that point
11043
+ * would report the posture in force then: a deployment that switched the
11044
+ * posture before the audit plugin mounted would have its switch recorded as
11045
+ * the start, which the trail cannot then tell from a start nobody watched.
11046
+ */
11047
+ const startupPosture = defaultPosture();
11048
+ log.info(`permission posture for new sessions: ${startupPosture}`);
11049
+ ctx.effect(() => ctx.on("session/disposed", (session) => {
11050
+ forgetSession(session.id);
11051
+ }), "aishell-deploy: forget disposed session modes");
11052
+ ctx.effect(() => ctx.on("session/created", (session) => {
11053
+ pinSession(session.id);
11054
+ }), "aishell-deploy: pin created session modes");
11055
+ for (const session of ctx.sessions.list()) pinSession(session.id);
10809
11056
  /**
10810
11057
  * The account name `aishell-credentials` recorded after verifying the pair
10811
11058
  * against IAM.
@@ -10833,47 +11080,58 @@ function apply(ctx, config) {
10833
11080
  * would be the wrong attribution.
10834
11081
  */
10835
11082
  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
- });
11083
+ try {
11084
+ const ak = readStoredPair(store)?.ak;
11085
+ auditCtx.audit.record({
11086
+ action: "permission.mode",
11087
+ outcome: change.mode === "read_write" ? "granted" : "revoked",
11088
+ ...ak === void 0 ? {} : { subject: auditSubject(ak, accountName()) },
11089
+ actor: change.actor,
11090
+ detail: {
11091
+ ...change.previous === void 0 ? { to: change.mode } : {
11092
+ from: change.previous,
11093
+ to: change.mode
11094
+ },
11095
+ ...change.session === void 0 ? {} : { session: change.session }
11096
+ }
11097
+ });
11098
+ } catch {}
10847
11099
  };
10848
- if (defaultMode() === "read_write") recordChange$1({
11100
+ recordChange$1({
11101
+ session: void 0,
10849
11102
  previous: void 0,
10850
- mode: "read_write",
11103
+ mode: startupPosture,
10851
11104
  actor: "startup"
10852
11105
  });
10853
11106
  auditCtx.effect(() => installPermissionRecorder(recordChange$1), "aishell-deploy: permission audit recorder");
10854
11107
  });
10855
11108
  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);
11109
+ known: (session) => ctx.sessions.get(session) !== void 0,
11110
+ read: (session) => ({ mode: getMode(session) }),
11111
+ write: (session, next) => {
11112
+ const previous = setMode(session, next);
10863
11113
  return {
10864
- mode: getMode$1(),
11114
+ mode: getMode(session),
10865
11115
  previous,
10866
11116
  changed: previous !== next
10867
11117
  };
10868
- }
11118
+ },
11119
+ readDefault: () => defaultPosture(),
11120
+ writeDefault: (next) => setDefaultPosture(next)
10869
11121
  });
10870
11122
  ctx.effect(() => ctx.connection.fetch.register({
10871
11123
  path: PERMISSION_PATH,
10872
11124
  methods: ["GET", "POST"],
10873
11125
  requestBody: "buffered",
10874
- fetch: (request) => request.method === "GET" ? routes.get() : routes.set(request)
11126
+ fetch: (request) => request.method === "GET" ? routes.get(request) : routes.set(request)
10875
11127
  }), "aishell-deploy: permission route");
10876
- registerPermissionPolicyContext(ctx, () => getMode$1());
11128
+ ctx.effect(() => ctx.connection.fetch.register({
11129
+ path: PERMISSION_DEFAULT_PATH,
11130
+ methods: ["GET", "POST"],
11131
+ requestBody: "buffered",
11132
+ fetch: (request) => request.method === "GET" ? routes.getDefault() : routes.setDefault(request)
11133
+ }), "aishell-deploy: permission posture route");
11134
+ registerPermissionPolicyContext(ctx, (session) => getMode(session));
10877
11135
  registerDeployWorkflow(ctx);
10878
11136
  ctx.effect(() => ctx.on("aishell/credentials-updated", () => {
10879
11137
  forgetAccount();