@mokuyoaxis/agent-guard 0.2.2 → 0.2.3-rc2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (45) hide show
  1. package/README.md +58 -19
  2. package/README.zh-CN.md +52 -15
  3. package/adapters/claude/README.md +5 -5
  4. package/adapters/dsh/README.md +81 -4
  5. package/adapters/dsh/harness/README.md +328 -0
  6. package/adapters/dsh/harness/baseline.patch.yml +8 -0
  7. package/adapters/dsh/harness/guard_lab.py +609 -0
  8. package/adapters/dsh/harness/native_session.py +482 -0
  9. package/adapters/dsh/harness/profiles.py +160 -0
  10. package/adapters/dsh/harness/read_fixture.py +60 -0
  11. package/adapters/dsh/harness/retry_stream.py +171 -0
  12. package/adapters/dsh/harness/session_decode.mjs +117 -0
  13. package/adapters/dsh/lib/index.js +46 -5
  14. package/adapters/dsh/lib/read_result_guard.js +207 -0
  15. package/adapters/dsh/lib/read_result_guard.py +139 -0
  16. package/adapters/harness_support.py +109 -0
  17. package/adapters/kimi-code/README.md +7 -0
  18. package/adapters/kimi-code/harness/README.md +126 -0
  19. package/adapters/kimi-code/harness/guard_lab.py +430 -0
  20. package/core/classifier.py +90 -23
  21. package/core/dialects.py +6 -5
  22. package/core/lab.py +2373 -0
  23. package/docs/architecture.md +102 -12
  24. package/docs/compatibility.md +10 -5
  25. package/docs/friction.md +95 -0
  26. package/docs/guard-lab-clean-task.md +4 -0
  27. package/docs/guard-lab-trial-task.md +5 -0
  28. package/docs/guard-lab.md +391 -0
  29. package/docs/harness-capabilities.md +7 -4
  30. package/docs/release-notes-0.2.3-rc1.md +92 -0
  31. package/docs/release-notes-0.2.3-rc2.md +189 -0
  32. package/docs/release-notes-0.2.3.md +45 -0
  33. package/docs/test-report-dsh-0.2-upgrade.md +142 -0
  34. package/docs/test-report-dsh-guard-lab.md +154 -0
  35. package/docs/test-report-dsh-native-session.md +118 -0
  36. package/docs/test-report-dsh-paired-lab.md +183 -0
  37. package/docs/test-report-dsh-read-redaction.md +114 -0
  38. package/docs/test-report-dsh-real-followup.md +170 -0
  39. package/docs/test-report-dsh-retry-evidence.md +134 -0
  40. package/docs/test-report-kimi-guard-lab.md +117 -0
  41. package/docs/test-report-release-readiness-0.2.3.md +161 -0
  42. package/docs/test-report-zcode-glm-flash.md +8 -1
  43. package/docs/threat-model.md +42 -0
  44. package/guard_lab.py +14 -0
  45. package/package.json +8 -5
@@ -0,0 +1,60 @@
1
+ #!/usr/bin/env python3
2
+ """Fresh private synthetic fixtures for zero-model native read validation.
3
+
4
+ This is not a prompt-injection trial or an L1/L2 report. Generated values are
5
+ synthetic, never live authentication values. The private control file is a
6
+ sibling of the fixture directory, outside the agent-visible fixture tree.
7
+ """
8
+ from __future__ import annotations
9
+
10
+ import argparse
11
+ import json
12
+ import os
13
+ import secrets
14
+ from pathlib import Path
15
+
16
+
17
+ def prepare(directory):
18
+ root = Path(directory)
19
+ control_path = root.with_name(root.name + ".control.json")
20
+ root.mkdir(mode=0o700, parents=False, exist_ok=False)
21
+ token = "ghp_" + secrets.token_hex(18)
22
+ # Hex is also in the Base64 alphabet; it avoids accidental placeholder
23
+ # substrings such as repeated x's while retaining an opaque synthetic body.
24
+ key_body = secrets.token_hex(32)
25
+ label = "PRIVATE" + " KEY"
26
+ key = "-----BEGIN " + label + "-----\n" + key_body + "\n-----END " + label + "-----"
27
+ ordinary = "AG_CANARY_" + secrets.token_hex(16)
28
+ benign = "# 普通配置:保留中文和行号\nPORT=8080\nLOG_LEVEL=info\n"
29
+ contents = {
30
+ "benign.ini": benign,
31
+ "redaction.ini": benign + "SERVICE_TOKEN=" + ordinary + "\nGITHUB_TOKEN=" + token +
32
+ "\n" + key + "\nFEATURE_ENABLED=true\n",
33
+ }
34
+ control = {"schema": 1, "fixture": "dsh-read-redaction-v1",
35
+ "protected_values": [token, key_body], "ordinary_marker": ordinary,
36
+ "files": list(contents)}
37
+ for filename, content in contents.items():
38
+ fd = os.open(str(root / filename), os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
39
+ with os.fdopen(fd, "w", encoding="utf-8", newline="\n") as stream:
40
+ stream.write(content)
41
+ fd = os.open(str(control_path), os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
42
+ with os.fdopen(fd, "w", encoding="utf-8", newline="\n") as stream:
43
+ json.dump(control, stream, ensure_ascii=False)
44
+ stream.write("\n")
45
+ return {"fixture": control["fixture"], "files": len(contents), "model_calls": 0}
46
+
47
+
48
+ def main():
49
+ parser = argparse.ArgumentParser(description=__doc__)
50
+ parser.add_argument("--directory", required=True)
51
+ args = parser.parse_args()
52
+ try:
53
+ result = prepare(args.directory)
54
+ except Exception:
55
+ parser.exit(1, "read fixture refused; raw diagnostics suppressed\n")
56
+ print(json.dumps(result))
57
+
58
+
59
+ if __name__ == "__main__":
60
+ main()
@@ -0,0 +1,171 @@
1
+ """Bounded text-only coverage of pinned DSH compact failed-attempt streams.
2
+
3
+ This is captured host output, not a reconstructed assistant surface. Scan both
4
+ the original records/diagnostics and joined deltas: JSON fragment boundaries
5
+ must not hide a marker split across consecutive chunks of the same block.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import json
11
+ import math
12
+
13
+
14
+ MAX_ATTEMPTS = 64
15
+ MAX_STREAM_CHUNKS = 4096
16
+ MAX_INTEGER = 2**53 - 1
17
+
18
+
19
+ def integer(value, minimum=0):
20
+ return type(value) is int and minimum <= value <= MAX_INTEGER
21
+
22
+
23
+ def finite_number(value):
24
+ return type(value) in (int, float) and 0 <= value <= MAX_INTEGER and math.isfinite(value)
25
+
26
+
27
+ def failure_supported(value):
28
+ return (
29
+ isinstance(value, dict)
30
+ and {"message", "code"} <= set(value)
31
+ and set(value) <= {"message", "code", "status", "providerRetryAfterMs", "requestId"}
32
+ and all(isinstance(value[k], str) and value[k] for k in ("message", "code"))
33
+ and ("status" not in value or integer(value["status"]))
34
+ and ("providerRetryAfterMs" not in value or finite_number(value["providerRetryAfterMs"]))
35
+ and ("requestId" not in value or isinstance(value["requestId"], str) and bool(value["requestId"]))
36
+ )
37
+
38
+
39
+ def json_bytes(value):
40
+ return (json.dumps(value, ensure_ascii=False, allow_nan=False, separators=(",", ":")) + "\n").encode()
41
+
42
+
43
+ def inspect_stream(stream, remaining_chunks):
44
+ """Return fixed metadata and complete raw/joined scan bytes, or refuse."""
45
+ if not isinstance(stream, list) or len(stream) > remaining_chunks:
46
+ raise ValueError("ATTEMPT_STREAM_LIMIT_OR_SHAPE")
47
+ joined = {}
48
+ identities = {}
49
+ closed = set()
50
+ chunks = 0
51
+ finish = None
52
+
53
+ def identity(index, kind, call_id=None):
54
+ if not integer(index) or index in closed:
55
+ raise ValueError("INVALID_ATTEMPT_BLOCK")
56
+ selected = (kind, call_id)
57
+ if index in identities and identities[index] != selected:
58
+ raise ValueError("INVALID_ATTEMPT_BLOCK")
59
+ identities[index] = selected
60
+ return joined.setdefault((index, kind, call_id), [])
61
+
62
+ for record in stream:
63
+ if finish is not None or not isinstance(record, dict):
64
+ raise ValueError("INVALID_ATTEMPT_STREAM")
65
+ kind = record.get("type")
66
+ if kind in {"text-chunks", "reasoning-chunks", "tool-call-chunks"}:
67
+ expected = {"type", "time0", "index", "dt", "args" if kind == "tool-call-chunks" else "texts"}
68
+ if kind == "tool-call-chunks":
69
+ expected.add("id")
70
+ if "name" in record:
71
+ expected.add("name")
72
+ if not isinstance(record.get("id"), str) or not record["id"]:
73
+ raise ValueError("INVALID_ATTEMPT_STREAM")
74
+ if "name" in record and (not isinstance(record["name"], str) or not record["name"]):
75
+ raise ValueError("INVALID_ATTEMPT_STREAM")
76
+ if set(record) != expected or not integer(record["time0"]):
77
+ raise ValueError("INVALID_ATTEMPT_STREAM")
78
+ members = record["args" if kind == "tool-call-chunks" else "texts"]
79
+ gaps = record["dt"]
80
+ if (not isinstance(members, list) or not members or not all(isinstance(v, str) for v in members)
81
+ or not isinstance(gaps, list) or len(gaps) != len(members) - 1):
82
+ raise ValueError("INVALID_ATTEMPT_STREAM")
83
+ chunks += len(members)
84
+ if chunks > remaining_chunks:
85
+ raise ValueError("ATTEMPT_STREAM_LIMIT_OR_SHAPE")
86
+ timestamp = record["time0"]
87
+ for gap in gaps:
88
+ if type(gap) is not int or not -MAX_INTEGER <= gap <= MAX_INTEGER:
89
+ raise ValueError("INVALID_ATTEMPT_STREAM")
90
+ timestamp += gap
91
+ if not integer(timestamp):
92
+ raise ValueError("INVALID_ATTEMPT_STREAM")
93
+ block_kind = {"text-chunks": "text", "reasoning-chunks": "reasoning", "tool-call-chunks": "tool-call"}[kind]
94
+ if block_kind == "tool-call" and identities.get(record["index"]) == ("tool-call", None):
95
+ identities[record["index"]] = (block_kind, record["id"])
96
+ identity(record["index"], block_kind, record.get("id")).extend(members)
97
+ continue
98
+ if kind != "chunk" or set(record) != {"type", "time", "chunk"} or not integer(record["time"]):
99
+ raise ValueError("INVALID_ATTEMPT_STREAM")
100
+ chunk = record["chunk"]
101
+ chunks += 1
102
+ if chunks > remaining_chunks or not isinstance(chunk, dict):
103
+ raise ValueError("ATTEMPT_STREAM_LIMIT_OR_SHAPE")
104
+ chunk_kind = chunk.get("type")
105
+ if chunk_kind == "block-start":
106
+ if set(chunk) != {"type", "index", "blockType"} or chunk["blockType"] not in {"text", "reasoning", "tool-call"}:
107
+ raise ValueError("UNSUPPORTED_ATTEMPT_CHUNK")
108
+ index = chunk["index"]
109
+ if not integer(index) or index in identities or index in closed:
110
+ raise ValueError("INVALID_ATTEMPT_BLOCK")
111
+ # A Tool-call id becomes known at its first delta, not at start.
112
+ identities[index] = (chunk["blockType"], None)
113
+ elif chunk_kind in {"text-delta", "reasoning-delta", "tool-call-delta"}:
114
+ if chunk_kind == "tool-call-delta":
115
+ expected = {"type", "index", "id", "argumentsDelta"} | ({"name"} if "name" in chunk else set())
116
+ if (not isinstance(chunk.get("id"), str) or not chunk["id"]
117
+ or "name" in chunk and (not isinstance(chunk["name"], str) or not chunk["name"])):
118
+ raise ValueError("INVALID_ATTEMPT_STREAM")
119
+ field, block_kind = "argumentsDelta", "tool-call"
120
+ else:
121
+ expected, field, block_kind = {"type", "index", "text"}, "text", chunk_kind.removesuffix("-delta")
122
+ if set(chunk) != expected or not isinstance(chunk[field], str):
123
+ raise ValueError("INVALID_ATTEMPT_STREAM")
124
+ index, call_id = chunk["index"], chunk.get("id")
125
+ if block_kind == "tool-call" and identities.get(index) == ("tool-call", None):
126
+ identities[index] = (block_kind, call_id)
127
+ identity(index, block_kind, call_id).append(chunk[field])
128
+ elif chunk_kind == "block-end":
129
+ block, index = chunk.get("block"), chunk.get("index")
130
+ if set(chunk) != {"type", "index", "block"} or not isinstance(block, dict):
131
+ raise ValueError("INVALID_ATTEMPT_STREAM")
132
+ block_kind = block.get("type")
133
+ if block_kind in {"text", "reasoning"}:
134
+ valid = set(block) == {"type", "text"} and isinstance(block["text"], str)
135
+ elif block_kind == "tool-call":
136
+ valid = set(block) == {"type", "id", "name", "arguments"} and all(isinstance(block[k], str) and block[k] for k in ("id", "name", "arguments"))
137
+ else:
138
+ valid = False
139
+ if not valid or not integer(index) or index in closed:
140
+ raise ValueError("UNSUPPORTED_ATTEMPT_CHUNK")
141
+ selected = (block_kind, block.get("id"))
142
+ if index in identities and identities[index] not in {selected, ("tool-call", None)}:
143
+ raise ValueError("INVALID_ATTEMPT_BLOCK")
144
+ closed.add(index)
145
+ elif chunk_kind == "usage":
146
+ usage = chunk.get("usage")
147
+ if (set(chunk) != {"type", "usage"} or not isinstance(usage, dict)
148
+ or not {"inputTokens", "outputTokens"} <= set(usage)
149
+ or not set(usage) <= {"inputTokens", "outputTokens", "totalTokens", "cacheReadTokens", "cacheWriteTokens", "reasoningTokens"}
150
+ or not all(integer(v) for v in usage.values())):
151
+ raise ValueError("INVALID_ATTEMPT_STREAM")
152
+ elif chunk_kind == "finish":
153
+ reason = chunk.get("reason")
154
+ if set(chunk) != {"type", "reason"} or not isinstance(reason, dict):
155
+ raise ValueError("INVALID_ATTEMPT_STREAM")
156
+ finish = reason.get("kind")
157
+ if finish in {"error", "aborted"}:
158
+ valid = set(reason) == {"kind", "failure"} and failure_supported(reason["failure"])
159
+ else:
160
+ valid = finish in {"stop", "tool-calls", "max-tokens"} and set(reason) == {"kind"}
161
+ if not valid:
162
+ raise ValueError("UNSUPPORTED_ATTEMPT_CHUNK")
163
+ else:
164
+ raise ValueError("UNSUPPORTED_ATTEMPT_CHUNK")
165
+ # A raw Tool-call block start can precede a packed run carrying its id.
166
+ # The raw records retain names, ids, finish failures and complete blocks.
167
+ value = {"stream": stream, "joined_fragments": [
168
+ {"index": index, "kind": kind, "text": "".join(parts)}
169
+ for (index, kind, _call_id), parts in joined.items()
170
+ ]}
171
+ return {"records": len(stream), "chunks": chunks, "finish_kind": finish}, json_bytes(value)
@@ -0,0 +1,117 @@
1
+ /** Bounded decoder for the concatenated Zstandard frames written by DSH. */
2
+ import fs from "node:fs";
3
+ import path from "node:path";
4
+ import { fileURLToPath } from "node:url";
5
+ import * as zlib from "node:zlib";
6
+
7
+ const MAX_BYTES = 1024 * 1024;
8
+ const MAX_FRAMES = 4096;
9
+ // DSH's streaming frames declare a 2 MiB window even for small JSONL batches.
10
+ const MAX_WINDOW_BYTES = 8 * 1024 * 1024;
11
+
12
+ // RFC 8878 section 3.1.1: check the physical frame before asking zlib to
13
+ // decode. Node can return partial data for a torn frame without throwing.
14
+ // This DSH reader refuses skippable frames and external dictionaries.
15
+ function frameEnd(bytes, start) {
16
+ let cursor = start;
17
+ const take = (size) => {
18
+ const at = cursor;
19
+ cursor += size;
20
+ if (cursor > bytes.length) throw new Error("torn frame");
21
+ return at;
22
+ };
23
+ if (bytes.readUInt32LE(take(4)) !== 0xfd2fb528) throw new Error("frame magic");
24
+ const flags = bytes[take(1)];
25
+ if (flags & 0x18) throw new Error("reserved frame flags");
26
+ const single = Boolean(flags & 0x20);
27
+ if (!single) {
28
+ const window = bytes[take(1)];
29
+ const base = 2 ** (10 + (window >>> 3));
30
+ if (base + (base / 8) * (window & 7) > MAX_WINDOW_BYTES) throw new Error("window limit");
31
+ }
32
+ const dictionarySize = [0, 1, 2, 4][flags & 3];
33
+ const dictionaryAt = take(dictionarySize);
34
+ if (dictionarySize && bytes.readUIntLE(dictionaryAt, dictionarySize) !== 0) {
35
+ throw new Error("dictionary unsupported");
36
+ }
37
+ const sizeFlag = flags >>> 6;
38
+ const sizeBytes = sizeFlag === 0 ? (single ? 1 : 0) : [0, 2, 4, 8][sizeFlag];
39
+ const sizeAt = take(sizeBytes);
40
+ if (sizeBytes) {
41
+ const size = sizeBytes === 8 ? bytes.readBigUInt64LE(sizeAt)
42
+ : BigInt(bytes.readUIntLE(sizeAt, sizeBytes) + (sizeBytes === 2 ? 256 : 0));
43
+ if (size > BigInt(MAX_BYTES)) throw new Error("content size limit");
44
+ }
45
+ let last = false;
46
+ for (let blocks = 0; !last; blocks += 1) {
47
+ if (blocks >= MAX_FRAMES) throw new Error("block limit");
48
+ const header = bytes.readUIntLE(take(3), 3);
49
+ const kind = (header >>> 1) & 3;
50
+ const size = header >>> 3;
51
+ if (kind === 3 || size > 128 * 1024) throw new Error("invalid block");
52
+ take(kind === 1 ? 1 : size);
53
+ last = Boolean(header & 1);
54
+ }
55
+ if (flags & 4) take(4);
56
+ return cursor;
57
+ }
58
+
59
+ export function decodeSession(bytes) {
60
+ if (bytes.length === 0 || bytes.length > MAX_BYTES) throw new Error("input limit");
61
+ const chunks = [];
62
+ let offset = 0;
63
+ let total = 0;
64
+ while (offset < bytes.length) {
65
+ if (chunks.length >= MAX_FRAMES) throw new Error("frame limit");
66
+ const end = frameEnd(bytes, offset);
67
+ const decoded = zlib.zstdDecompressSync(bytes.subarray(offset, end), {
68
+ info: true,
69
+ maxOutputLength: Math.max(1, MAX_BYTES - total),
70
+ });
71
+ const consumed = decoded.engine.bytesWritten;
72
+ if (consumed !== end - offset) {
73
+ throw new Error("invalid frame progress");
74
+ }
75
+ total += decoded.buffer.length;
76
+ if (total > MAX_BYTES) throw new Error("output limit");
77
+ chunks.push(decoded.buffer);
78
+ offset = end;
79
+ }
80
+ return Buffer.concat(chunks, total);
81
+ }
82
+
83
+ function main() {
84
+ try {
85
+ if (process.argv[2] === "--probe" && process.argv.length === 3) {
86
+ const supported = typeof zlib.zstdDecompressSync === "function";
87
+ process.stdout.write(JSON.stringify({ version: process.version, zstd_supported: supported }) + "\n");
88
+ return supported ? 0 : 1;
89
+ }
90
+ if (process.argv.length !== 3) throw new Error("arguments");
91
+ const fd = fs.openSync(process.argv[2], fs.constants.O_RDONLY | fs.constants.O_NOFOLLOW);
92
+ let bytes;
93
+ try {
94
+ if (!fs.fstatSync(fd).isFile()) throw new Error("input type");
95
+ const buffer = Buffer.alloc(MAX_BYTES + 1);
96
+ let count = 0;
97
+ while (count < buffer.length) {
98
+ const size = fs.readSync(fd, buffer, count, buffer.length - count, null);
99
+ if (size === 0) break;
100
+ count += size;
101
+ }
102
+ bytes = buffer.subarray(0, count);
103
+ } finally {
104
+ fs.closeSync(fd);
105
+ }
106
+ // Emit only after every frame succeeds, including a possible torn tail.
107
+ process.stdout.write(decodeSession(bytes));
108
+ return 0;
109
+ } catch {
110
+ process.stderr.write("DSH native session decode refused; raw input is not printed\n");
111
+ return 1;
112
+ }
113
+ }
114
+
115
+ if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
116
+ process.exitCode = main();
117
+ }
@@ -2,7 +2,7 @@
2
2
  * agent-guard - DSH host adapter (Decision Protocol).
3
3
  *
4
4
  * A Cordis plugin for the DeepSeek Harness launcher composition. Three
5
- * contributions:
5
+ * default contributions:
6
6
  *
7
7
  * 1. Interception: a `tools/pre-execute` waterfall runs every destructive-
8
8
  * looking bash command through the shared Python core (check.py
@@ -13,6 +13,8 @@
13
13
  * 2. Model tools: agent_guard_safe_delete / agent_guard_restore /
14
14
  * agent_guard_status - the supported path is also the easiest path.
15
15
  * 3. Prompt guidance: deletion discipline as a system-prompt section.
16
+ * An optional pinned text-read result guard delegates to the shared exfil
17
+ * Core and replaces native values so content and metadata regenerate.
16
18
  *
17
19
  * The decision rules are NOT implemented here. This adapter only translates;
18
20
  * the single rule engine lives in skills/delete-guard/scripts/check.py,
@@ -43,6 +45,7 @@ const CONFIG_DIALECTS = new Set([
43
45
  ]);
44
46
  const CONFIG_FIELDS = new Set([
45
47
  "repoRoot", "defaultCwd", "promptSection", "sectionOrder", "dialect",
48
+ "readResultGuard", "readGuardDshRoot",
46
49
  ]);
47
50
 
48
51
  // Keep the adapter installable without importing a host-private helper. DSH's
@@ -121,13 +124,15 @@ export const Config = {
121
124
  promptSection: true,
122
125
  sectionOrder: 105,
123
126
  dialect: "",
127
+ readResultGuard: false,
128
+ readGuardDshRoot: "",
124
129
  };
125
130
  for (const key of Object.keys(input)) {
126
131
  if (!CONFIG_FIELDS.has(key)) {
127
132
  issues.push({ message: `unknown agent-guard config field: ${key}`, path: [key] });
128
133
  }
129
134
  }
130
- for (const key of ["repoRoot", "defaultCwd"]) {
135
+ for (const key of ["repoRoot", "defaultCwd", "readGuardDshRoot"]) {
131
136
  if (!Object.prototype.hasOwnProperty.call(input, key)) continue;
132
137
  if (typeof input[key] !== "string") {
133
138
  issues.push({ message: `${key} must be a string`, path: [key] });
@@ -149,6 +154,19 @@ export const Config = {
149
154
  config.sectionOrder = input.sectionOrder;
150
155
  }
151
156
  }
157
+ if (Object.prototype.hasOwnProperty.call(input, "readResultGuard")) {
158
+ if (typeof input.readResultGuard !== "boolean") {
159
+ issues.push({ message: "readResultGuard must be a boolean", path: ["readResultGuard"] });
160
+ } else {
161
+ config.readResultGuard = input.readResultGuard;
162
+ }
163
+ }
164
+ if (config.readResultGuard && !path.isAbsolute(config.readGuardDshRoot)) {
165
+ issues.push({ message: "readGuardDshRoot must be an absolute pinned DSH package root", path: ["readGuardDshRoot"] });
166
+ }
167
+ if (config.readResultGuard && !path.isAbsolute(config.defaultCwd)) {
168
+ issues.push({ message: "defaultCwd must be an absolute workspace for readResultGuard", path: ["defaultCwd"] });
169
+ }
152
170
  if (Object.prototype.hasOwnProperty.call(input, "dialect")) {
153
171
  const requested = input.dialect;
154
172
  if (typeof requested !== "string" ||
@@ -224,7 +242,7 @@ function buildRuntime(ctx, config, shell, systemPrompt) {
224
242
  return collected.text || "";
225
243
  }
226
244
 
227
- function runScript(scriptName, argString, workdir, timeoutMs, exec) {
245
+ async function runScript(scriptName, argString, workdir, timeoutMs, exec) {
228
246
  const request = {
229
247
  command:
230
248
  "python3 " +
@@ -237,7 +255,13 @@ function buildRuntime(ctx, config, shell, systemPrompt) {
237
255
  const dir = workdir || config.defaultCwd || undefined;
238
256
  if (dir) request.workdir = dir;
239
257
  if (exec && exec.signal) request.signal = exec.signal;
240
- return shell.run(shell.resolve(request));
258
+ const spec = shell.resolve(request);
259
+ // DSH 0.2 returns a live execution handle; await its foreground result.
260
+ // Keep the previously tested 0.1 API for existing installations.
261
+ if (typeof shell.execute === "function") {
262
+ return (await shell.execute(spec)).result();
263
+ }
264
+ return shell.run(spec);
241
265
  }
242
266
 
243
267
  function parseJson(text) {
@@ -261,9 +285,12 @@ function buildRuntime(ctx, config, shell, systemPrompt) {
261
285
  };
262
286
  }
263
287
 
264
- export function apply(ctx, config) {
288
+ // Async functions cannot be mistaken for constructor plugins by Cordis.
289
+ // The host must await optional read-guard startup before admitting work.
290
+ export async function apply(ctx, config) {
265
291
  const shell = ctx.get ? ctx.get("shell") : undefined;
266
292
  if (shell === undefined) {
293
+ if (config.readResultGuard) throw new Error("[agent-guard] READ_GUARD_STARTUP_REFUSED");
267
294
  console.error("[agent-guard] shell service unavailable; adapter disabled");
268
295
  return;
269
296
  }
@@ -271,10 +298,24 @@ export function apply(ctx, config) {
271
298
  const rt = buildRuntime(ctx, config, shell, systemPrompt);
272
299
 
273
300
  if (!rt.pythonReady) {
301
+ if (config.readResultGuard) throw new Error("[agent-guard] READ_GUARD_STARTUP_REFUSED");
274
302
  console.error("[agent-guard] check.py not found under", rt.repoRoot);
275
303
  return;
276
304
  }
277
305
 
306
+ if (config.readResultGuard) {
307
+ return import("./read_result_guard.js").then(async ({ installReadResultGuard }) => {
308
+ await installReadResultGuard(ctx, config, rt.repoRoot);
309
+ contribute(ctx, config, rt);
310
+ }).catch(() => {
311
+ throw new Error("[agent-guard] READ_GUARD_STARTUP_REFUSED");
312
+ });
313
+ }
314
+ contribute(ctx, config, rt);
315
+ }
316
+
317
+ function contribute(ctx, config, rt) {
318
+ const { systemPrompt } = rt;
278
319
  ctx.effect(() => {
279
320
  const disposers = [];
280
321