@deepseek-ai/dsh-tmux-context 0.2.2-rc.1 → 0.2.2-rc.2

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
@@ -923,11 +923,11 @@ function createUserMessage(input) {
923
923
  /** Largest delay Node schedules without clamping it to one millisecond. */
924
924
  const MAX_TIMER_DELAY_MS = 2147483647;
925
925
  //#endregion
926
- //#region ../../llm/llm/src/error.ts
926
+ //#region ../../util/error/src/index.ts
927
927
  /**
928
928
  * Harness error base with a stable machine-routable code and chained cause.
929
929
  * Package errors extend it so tool results and replay can retain failure class.
930
- * @module @deepseek-ai/dsh-llm/error
930
+ * @module @deepseek-ai/dsh-error
931
931
  */
932
932
  /**
933
933
  * Base class for all harness errors. Carries a `code` (stable, programmatic —
@@ -944,6 +944,75 @@ var HarnessError = class extends Error {
944
944
  this.name = new.target.name;
945
945
  }
946
946
  };
947
+ //#endregion
948
+ //#region ../../llm/llm/src/error.ts
949
+ /**
950
+ * LLM failure codes and helpers over the shared Harness error base. The base
951
+ * class lives in `@deepseek-ai/dsh-error` and is re-exported here, so both
952
+ * import paths name the same class.
953
+ * @module @deepseek-ai/dsh-llm/error
954
+ */
955
+ /**
956
+ * Every failure code the built-in providers and the LLM runtime raise. An entry
957
+ * marked `retryChoice` is offered as a choice for a provider retry policy's
958
+ * `retryableCodes`; being a choice does not make a code retried by default.
959
+ */
960
+ const LLM_FAILURE_CODES = {
961
+ ABORTED: {},
962
+ ACCOUNT_QUOTA: {},
963
+ ACCOUNT_SIGN_IN_REQUIRED: {},
964
+ ACCOUNT_TOKEN_INVALID: {},
965
+ AUTH: {},
966
+ CLIENT_UPGRADE_REQUIRED: {},
967
+ CONTEXT_WINDOW_EXCEEDED: {},
968
+ DISCOVERY_FAILED: {},
969
+ DISCOVERY_UNSUPPORTED: {},
970
+ DUPLICATE_ADAPTER: {},
971
+ DUPLICATE_DIRECTORY: {},
972
+ DUPLICATE_DISCOVERY: {},
973
+ EMPTY_RESPONSE: { retryChoice: true },
974
+ FILES_API: {},
975
+ IMAGE_OFFLOAD_REQUIRED: {},
976
+ INVALID_ADAPTER: {},
977
+ INVALID_CATALOG: {},
978
+ INVALID_CONFIG: {},
979
+ INVALID_CREDENTIAL: {},
980
+ INVALID_DIRECTORY: {},
981
+ INVALID_DISCOVERY: {},
982
+ INVALID_MODEL_CONTEXT: {},
983
+ INVALID_MODEL_INFO: {},
984
+ INVALID_MODEL_MAX_TOKENS: {},
985
+ INVALID_MODEL_REASONING: {},
986
+ INVALID_PREPARED_CALL: {},
987
+ INVALID_REPLAY_STATE: {},
988
+ INVALID_REQUEST: {},
989
+ INVALID_RESPONSE: {},
990
+ MALFORMED_RESPONSE: { retryChoice: true },
991
+ MISSING_CREDENTIAL: {},
992
+ MODEL_SWITCH_COMPACTION_FAILED: {},
993
+ MODEL_UNSUPPORTED: {},
994
+ NO_ADAPTER: {},
995
+ NO_CREDENTIAL_STORE: {},
996
+ NO_DISCOVERY: {},
997
+ PI_AI_ERROR: {},
998
+ QUOTA: { retryChoice: true },
999
+ RATE_LIMIT: { retryChoice: true },
1000
+ REGISTRATION_DISPOSED: {},
1001
+ REQUEST_EXTENSION: {},
1002
+ REQUEST_HEADERS: {},
1003
+ SERVER: { retryChoice: true },
1004
+ STREAM_CLOSED: { retryChoice: true },
1005
+ TIMEOUT: { retryChoice: true },
1006
+ TRANSPORT: { retryChoice: true },
1007
+ UNKNOWN: {},
1008
+ UNKNOWN_MODEL: {},
1009
+ UNSTORABLE_PROVIDER_ID: {},
1010
+ UNSUPPORTED_CONTENT: {},
1011
+ UNSUPPORTED_OPTION: {},
1012
+ UNSUPPORTED_REASONING_EFFORT: {}
1013
+ };
1014
+ /** The {@link LLM_FAILURE_CODES} entries marked as retry-policy choices, in definition order. */
1015
+ const RETRY_CODE_CHOICES = Object.freeze(Object.keys(LLM_FAILURE_CODES).filter((code) => "retryChoice" in LLM_FAILURE_CODES[code]));
947
1016
  /**
948
1017
  * Canonical provider-neutral code for a response that completed normally but
949
1018
  * carried no content blocks at all. Providers occasionally emit a degenerate
@@ -979,14 +1048,14 @@ const DEFAULT_RETRYABLE_CODES = Object.freeze([
979
1048
  "TRANSPORT"
980
1049
  ]);
981
1050
  const backoffSchema = z.object({
982
- initialDelayMs: z.number().max(MAX_TIMER_DELAY_MS).default(DEFAULT_INITIAL_DELAY_MS),
983
- maxDelayMs: z.number().max(MAX_TIMER_DELAY_MS).default(DEFAULT_MAX_DELAY_MS),
1051
+ initialDelayMs: z.number().min(Number.MIN_VALUE).max(MAX_TIMER_DELAY_MS).default(DEFAULT_INITIAL_DELAY_MS),
1052
+ maxDelayMs: z.number().min(Number.MIN_VALUE).max(MAX_TIMER_DELAY_MS).default(DEFAULT_MAX_DELAY_MS),
984
1053
  jitterRatio: z.number().min(0).max(1).default(DEFAULT_JITTER_RATIO)
985
1054
  });
986
1055
  const normalPolicySchema = z.object({
987
1056
  mode: z.const("normal").required(),
988
1057
  maxRetries: z.number().step(1).min(0).max(Number.MAX_SAFE_INTEGER).default(DEFAULT_MAX_RETRIES),
989
- retryableCodes: z.array(z.string()).default([...DEFAULT_RETRYABLE_CODES]),
1058
+ retryableCodes: z.array(z.union([...RETRY_CODE_CHOICES.map((code) => z.const(code)), z.string().min(1)])).min(1).default([...DEFAULT_RETRYABLE_CODES]),
990
1059
  backoff: backoffSchema
991
1060
  });
992
1061
  const alwaysPolicySchema = z.object({
@@ -1270,27 +1339,47 @@ function withoutDeveloperMessages(messages) {
1270
1339
  const retained = messages.filter((message) => message.role !== "developer");
1271
1340
  return retained.length === messages.length ? messages : retained;
1272
1341
  }
1273
- function toolDeclarations(tools, mode, history) {
1342
+ function toolDeclarations(history) {
1274
1343
  const declarations = new Map(history.tools.map((tool) => [tool.name, tool]));
1275
1344
  for (const update of history.updates) for (const tool of update.additions) if (!declarations.has(tool.name)) declarations.set(tool.name, {
1276
1345
  ...tool,
1277
1346
  deferLoading: true
1278
1347
  });
1279
- switch (mode) {
1280
- case "in-history": return declarations;
1281
- case "addition-only": {
1282
- const activeNames = new Set(tools?.map((tool) => tool.name));
1283
- for (const name of declarations.keys()) if (!activeNames.has(name)) declarations.delete(name);
1284
- return declarations;
1285
- }
1286
- /* v8 ignore next 2 -- closed-union exhaustiveness guard */
1287
- default: return assertNever(mode);
1348
+ return declarations;
1349
+ }
1350
+ /** Rebuild declarations on removals or additions to an empty set, where the request prefix changes. */
1351
+ function rebaseAdditionOnlyHistory(history, messages) {
1352
+ const available = new Map(history.tools.map((tool) => [tool.name, tool]));
1353
+ let baseline = history.tools;
1354
+ let retainedFrom = 0;
1355
+ for (const [index, update] of history.updates.entries()) {
1356
+ const additions = new Map(update.additions.map((tool) => [tool.name, tool]));
1357
+ let reset = available.size === 0 && additions.size > 0;
1358
+ for (const block of messages.get(update.messageId)) if (block.type === "tool-addition") {
1359
+ const { deferLoading: _loading, ...tool } = additions.get(block.toolName);
1360
+ available.set(tool.name, tool);
1361
+ } else if (block.type === "tool-removal") {
1362
+ reset = true;
1363
+ available.delete(block.toolName);
1364
+ }
1365
+ if (reset) {
1366
+ baseline = [...available.values()];
1367
+ retainedFrom = index + 1;
1368
+ }
1288
1369
  }
1370
+ return retainedFrom === 0 ? history : {
1371
+ tools: baseline,
1372
+ updates: history.updates.slice(retainedFrom)
1373
+ };
1289
1374
  }
1290
1375
  /**
1291
1376
  * Construct provider declarations from session-folded history without changing logged active tools.
1292
1377
  * Unsupported routes and incomplete history use current declarations without developer updates.
1293
- * Explicitly deferred baseline tools become available only after their first retained addition.
1378
+ * Explicitly deferred declarations require an addition to activate them.
1379
+ * A rebuild makes previously activated declarations immediate; unactivated declarations stay deferred.
1380
+ * Addition-only routes rebuild when a tool is removed or tools are added to an empty set;
1381
+ * deferred declarations count as existing tools.
1382
+ * Later additions remain deferred and superseded tool blocks are omitted without dropping other content.
1294
1383
  * @param messages - complete request inputs, or the prefix selected for an auxiliary call.
1295
1384
  * @param tools - currently active tool schemas.
1296
1385
  * @param toolUpdate - the resolved route's update mode.
@@ -1310,14 +1399,16 @@ function projectToolUpdates(messages, tools, toolUpdate, history) {
1310
1399
  messages: withoutDeveloperMessages(messages),
1311
1400
  tools
1312
1401
  };
1313
- const messageIds = new Set(messages.flatMap((message) => message.role === "developer" ? [message.id] : []));
1314
- if (history.updates.some((update) => !messageIds.has(update.messageId))) return {
1402
+ const updates = new Map(messages.flatMap((message) => message.role === "developer" ? [[message.id, message.content]] : []));
1403
+ if (history.updates.some((update) => !updates.has(update.messageId))) return {
1315
1404
  messages: withoutDeveloperMessages(messages),
1316
1405
  tools
1317
1406
  };
1318
- const declarations = toolDeclarations(tools, toolUpdate, history);
1407
+ const projectedHistory = toolUpdate === "addition-only" ? rebaseAdditionOnlyHistory(history, updates) : history;
1408
+ const declarations = toolDeclarations(projectedHistory);
1319
1409
  const updateIds = new Set(history.updates.map((update) => update.messageId));
1320
- const offered = new Set(history.tools.filter((tool) => !tool.deferLoading).map((tool) => tool.name));
1410
+ const retainedUpdateIds = new Set(projectedHistory.updates.map((update) => update.messageId));
1411
+ const offered = new Set(projectedHistory.tools.filter((tool) => !tool.deferLoading).map((tool) => tool.name));
1321
1412
  const projectedMessages = [];
1322
1413
  for (const message of messages) {
1323
1414
  if (message.role !== "developer") {
@@ -1328,6 +1419,7 @@ function projectToolUpdates(messages, tools, toolUpdate, history) {
1328
1419
  const content = message.content.filter((block) => {
1329
1420
  switch (block.type) {
1330
1421
  case "tool-addition":
1422
+ if (!retainedUpdateIds.has(message.id)) return false;
1331
1423
  if (!declarations.has(block.toolName) || offered.has(block.toolName)) return false;
1332
1424
  offered.add(block.toolName);
1333
1425
  return true;
@@ -1410,13 +1502,16 @@ var __esDecorate = function(ctor, descriptorIn, decorators, contextIn, initializ
1410
1502
  /**
1411
1503
  * Typed error for LLM-related failures. Extends {@link HarnessError}, so the
1412
1504
  * `code` string (e.g. `AUTH`, `RATE_LIMIT`, `NO_ADAPTER`) is shared taxonomy.
1505
+ * The constructor takes only a {@link BuiltinLlmFailureCode}; a failure from
1506
+ * another provider, whose code may be any string, is re-raised through
1507
+ * {@link LlmError.fromFailure}.
1413
1508
  */
1414
- var LlmError = class extends HarnessError {
1509
+ var LlmError = class LlmError extends HarnessError {
1415
1510
  /** Serializable facts retained beside this live Error. */
1416
1511
  failure;
1417
1512
  /**
1418
1513
  * @param message - non-empty human-readable failure summary.
1419
- * @param code - non-empty stable provider-neutral machine code.
1514
+ * @param code - built-in stable provider-neutral machine code.
1420
1515
  * @param options - optional cause and validated serializable provider facts.
1421
1516
  */
1422
1517
  constructor(message, code, options) {
@@ -1436,6 +1531,18 @@ var LlmError = class extends HarnessError {
1436
1531
  ...options?.offloadImages === void 0 ? {} : { offloadImages: options.offloadImages }
1437
1532
  });
1438
1533
  }
1534
+ /**
1535
+ * Raise an observed failure again with its own code, which any provider may have chosen.
1536
+ * @param failure - the serializable failure, typically from a stream's terminal chunk.
1537
+ * @param options - optional cause.
1538
+ * @returns an error carrying the failure's message, code, and provider facts.
1539
+ */
1540
+ static fromFailure(failure, options) {
1541
+ return new LlmError(failure.message, failure.code, {
1542
+ ...failure,
1543
+ ...options
1544
+ });
1545
+ }
1439
1546
  };
1440
1547
  (() => {
1441
1548
  let _classSuper = TypertRemoteService;
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;GAkBG;AAEH,OAAO,KAAK,EAAE,OAAO,EAAiB,MAAM,qBAAqB,CAAA;AACjE,OAAO,CAAC,MAAM,0BAA0B,CAAA;AAMxC,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,sBAAsB,CAAA;AAEzD,OAAO,QAAQ,sBAAsB,CAAC;IACpC,UAAU,gBAAgB;QACxB;;;WAGG;QACH,cAAc,EAAE;YAAE,IAAI,EAAE,cAAc,CAAA;SAAE,GAAG,aAAa,CAAA;KACzD;CACF;AAED,qDAAqD;AACrD,eAAO,MAAM,IAAI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AI,EAAE,IAAI,EAAE,IAAI,EAAE,UAAU,EAAE,QAAQ,EAAE,CAAC,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC,EAAE;iBACrE,CAAC;gBACF,GAAG,QAAQ,CAAC,QAAQ;aACrB;SACF,CAAA;IACH,CAAC,EAAE,EAAE,OAAO,EAAE,IAAI,EAAE,CAAC,CAAA;IACrB,MAAM,eAAe,CAAA;AACvB,CAAC"}
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@deepseek-ai/dsh-tmux-context",
3
3
  "description": "Opt-in durable per-step context with this agent's tmux pane and window location",
4
- "version": "0.2.2-rc.1",
4
+ "version": "0.2.2-rc.2",
5
5
  "publishConfig": {
6
6
  "access": "public"
7
7
  },
@@ -25,28 +25,31 @@
25
25
  "files": [
26
26
  "locale/*.json",
27
27
  "lib/index.js",
28
- "lib/types/**/*.d.ts"
28
+ "lib/types/**/*.d.ts",
29
+ "lib/types/**/*.d.ts.map",
30
+ "lib/**/*.js.map",
31
+ "src"
29
32
  ],
30
33
  "license": "MIT",
31
34
  "dependencies": {
32
35
  "@deepseek-ai/schemastery": "~3.19.0",
33
- "zod": "4.4.3"
36
+ "zod": "4.6.6"
34
37
  },
35
38
  "peerDependencies": {
36
- "@deepseek-ai/dsh-agent": "0.2.2-rc.1",
37
- "@deepseek-ai/dsh-shell": "0.2.2-rc.1",
38
- "@deepseek-ai/dsh-session": "0.2.2-rc.1",
39
+ "@deepseek-ai/dsh-agent": "0.2.2-rc.2",
40
+ "@deepseek-ai/dsh-shell": "0.2.2-rc.2",
41
+ "@deepseek-ai/dsh-session": "0.2.2-rc.2",
39
42
  "@deepseek-ai/cordis": "~4.1.0",
40
- "@deepseek-ai/dsh-session-projection": "0.2.2-rc.1"
43
+ "@deepseek-ai/dsh-session-projection": "0.2.2-rc.2"
41
44
  },
42
45
  "devDependencies": {
43
- "@deepseek-ai/dsh-agent": "0.2.2-rc.1",
44
- "@deepseek-ai/dsh-agent-loop-testkit": "0.2.2-rc.1",
45
- "@deepseek-ai/dsh-shell": "0.2.2-rc.1",
46
- "@deepseek-ai/dsh-llm": "0.2.2-rc.1",
47
- "@deepseek-ai/dsh-session": "0.2.2-rc.1",
48
- "@deepseek-ai/dsh-system-prompt": "0.2.2-rc.1",
46
+ "@deepseek-ai/dsh-agent": "0.2.2-rc.2",
47
+ "@deepseek-ai/dsh-agent-loop-testkit": "0.2.2-rc.2",
48
+ "@deepseek-ai/dsh-shell": "0.2.2-rc.2",
49
+ "@deepseek-ai/dsh-llm": "0.2.2-rc.2",
50
+ "@deepseek-ai/dsh-session": "0.2.2-rc.2",
51
+ "@deepseek-ai/dsh-system-prompt": "0.2.2-rc.2",
49
52
  "@deepseek-ai/cordis": "~4.1.0",
50
- "@deepseek-ai/dsh-session-projection": "0.2.2-rc.1"
53
+ "@deepseek-ai/dsh-session-projection": "0.2.2-rc.2"
51
54
  }
52
55
  }
package/src/index.ts ADDED
@@ -0,0 +1,272 @@
1
+ /**
2
+ * Opt-in request-preparation tmux-location context. Eligible step attempts
3
+ * append durable, source-attributed context naming the tmux session, window,
4
+ * and pane this agent process runs in, plus the window's pane-tree layout.
5
+ *
6
+ * The plugin pulls state once per turn, for the first request (`step === 1`), by
7
+ * running one `tmux display-message` through the `ctx.shell` executor service. It
8
+ * confirms this process genuinely runs inside the pane `$TMUX_PANE` names by
9
+ * matching the pane's `#{pane_tty}` against this process's controlling terminal,
10
+ * so a terminal that merely inherited `$TMUX`/`$TMUX_PANE` from a tmux ancestor
11
+ * (e.g. a VS Code integrated terminal) reads as "not in tmux". It re-injects
12
+ * only when the rendered tmux state changes since the last injection (a moved,
13
+ * renamed, or re-laid-out pane), with an optional `refreshIntervalMs` floor
14
+ * between injections. Absent tmux environment, an inherited-only environment,
15
+ * absent `ctx.shell`, or a failed query is a no-op, never an error: an executor
16
+ * rejection is contained and logged as a warning so the turn continues.
17
+ *
18
+ * @module @deepseek-ai/dsh-tmux-context
19
+ */
20
+
21
+ import type { Context, LoggerService } from '@deepseek-ai/cordis'
22
+ import z from '@deepseek-ai/schemastery'
23
+ import { z as zod } from 'zod'
24
+ import type { PreStepDecision } from '@deepseek-ai/dsh-agent'
25
+ import type {} from '@deepseek-ai/dsh-session-projection'
26
+ import type { ShellExecutor, ShellRunResult } from '@deepseek-ai/dsh-shell'
27
+ import { createUserMessage } from '@deepseek-ai/dsh-llm'
28
+ import type { ContextFormed } from '@deepseek-ai/dsh-llm'
29
+
30
+ declare module '@deepseek-ai/dsh-llm' {
31
+ interface MessageSourceMap {
32
+ /** Location attribution; readers preserve the content without this producer.
33
+ * Its projection uses the kind to avoid repeated injection.
34
+ * @persistenceAttribution
35
+ */
36
+ 'tmux-context': { kind: 'tmux-context' } & ContextFormed
37
+ }
38
+ }
39
+
40
+ /** Cordis plugin name used by loader diagnostics. */
41
+ export const name = 'tmux-context'
42
+
43
+ /** The agent registry that owns pre-step processing. */
44
+ export const inject = ['agents', 'sessionProjections']
45
+
46
+ /** Per-turn tmux-location scheduling. Invalid values fail plugin load. */
47
+ export interface Config {
48
+ /** Minimum milliseconds between durable injections in one session. Omit or set to 0 to inject on every eligible change. */
49
+ refreshIntervalMs?: number
50
+ }
51
+
52
+ /** Schemastery validation for {@link Config}. */
53
+ export const Config: z<Config> = z.object({
54
+ refreshIntervalMs: z.number(),
55
+ })
56
+
57
+ /**
58
+ * Tab-separated tmux format fields, in query order. Layout (`window_layout`)
59
+ * is the pane-tree description; pane/window pixel sizes are intentionally
60
+ * excluded (own location and layout only, per the package scope).
61
+ */
62
+ const TMUX_FIELDS = [
63
+ '#{session_name}',
64
+ '#{window_index}',
65
+ '#{window_name}',
66
+ '#{pane_index}',
67
+ '#{pane_id}',
68
+ '#{window_active}',
69
+ '#{pane_active}',
70
+ '#{window_layout}',
71
+ ] as const
72
+
73
+ /** Structured tmux location parsed from one `display-message` reading. */
74
+ interface TmuxLocation {
75
+ sessionName: string
76
+ windowIndex: string
77
+ windowName: string
78
+ paneIndex: string
79
+ paneId: string
80
+ windowActive: string
81
+ paneActive: string
82
+ windowLayout: string
83
+ }
84
+
85
+ /** Prefix marking the volatile turn/step preamble line of a rendered reading. */
86
+ const READING_PREFIX = 'tmux location (turn '
87
+
88
+ /**
89
+ * Field separator between tmux format fields. tmux does not interpret C escapes
90
+ * in a format, so the literal two-character sequence `\t` is emitted verbatim
91
+ * and split back out here; this avoids embedding raw whitespace in the command.
92
+ */
93
+ const FIELD_SEP = '\\t'
94
+
95
+ /**
96
+ * Read this process's tmux location through the bash seam, or `undefined` when
97
+ * this process is not genuinely running inside a tmux pane or the query fails.
98
+ *
99
+ * `$TMUX_PANE` alone is insufficient: a terminal launched from a tmux shell
100
+ * (e.g. VS Code's integrated terminal, a desktop launcher) inherits `$TMUX` and
101
+ * `$TMUX_PANE` from that ancestor, so the variables are present even though this
102
+ * process does not live in that pane. The command therefore also compares the
103
+ * pane's `#{pane_tty}` against this process's own controlling terminal
104
+ * (`ps -o tty=` for {@link processId}); a genuine pane owns this process's tty,
105
+ * an inherited environment names some other pane's tty. Fields are emitted only
106
+ * on a match, so an inherited environment reads as "not in tmux" and injects
107
+ * nothing.
108
+ *
109
+ * The location is optional context, so an executor rejection is a failed query,
110
+ * not a turn failure: `resolve()` may reject the command on policy grounds and
111
+ * `run()` only promises to resolve for nonzero exits, timeouts, and aborts, so
112
+ * both are contained and reported as a warning.
113
+ *
114
+ * @param bash - The executor service used to run the read-only tmux/ps commands.
115
+ * @param logger - receives a warning when the executor rejects the query.
116
+ * @param processId - this agent process's pid, whose controlling tty must match the pane.
117
+ * @param signal - abort signal forwarded to the executor.
118
+ * @returns the parsed location, or `undefined` when not in a real pane or on any failure.
119
+ */
120
+ async function queryTmuxLocation(
121
+ bash: ShellExecutor,
122
+ logger: LoggerService,
123
+ processId: number,
124
+ signal: AbortSignal,
125
+ ): Promise<TmuxLocation | undefined> {
126
+ const format = TMUX_FIELDS.join(FIELD_SEP)
127
+ const command = [
128
+ '[ -n "$TMUX_PANE" ] || exit 1',
129
+ `self_tty=$(ps -o tty= -p ${processId} | tr -d ' ')`,
130
+ '[ -n "$self_tty" ] || exit 1',
131
+ 'pane_tty=$(tmux display-message -t "$TMUX_PANE" -p \'#{pane_tty}\') || exit 1',
132
+ '[ "$pane_tty" = "/dev/$self_tty" ] || exit 1',
133
+ `exec tmux display-message -t "$TMUX_PANE" -p '${format}'`,
134
+ ].join('\n')
135
+ let result: ShellRunResult
136
+ try {
137
+ result = await (await bash.execute(bash.resolve({ command, signal }))).result()
138
+ } catch (error: unknown) {
139
+ const message = error instanceof Error ? error.message : String(error)
140
+ logger.warn(`tmux location query failed: ${message}; injecting no location this turn`)
141
+ return undefined
142
+ }
143
+ if (result.exitCode !== 0) return undefined
144
+ const line = result.stdout.text.split('\n', 1)[0] as string
145
+ const parts = line.split(FIELD_SEP)
146
+ if (parts.length !== TMUX_FIELDS.length) return undefined
147
+ const [
148
+ sessionName,
149
+ windowIndex,
150
+ windowName,
151
+ paneIndex,
152
+ paneId,
153
+ windowActive,
154
+ paneActive,
155
+ windowLayout,
156
+ ] = parts as [string, string, string, string, string, string, string, string]
157
+ if (paneId.length === 0) return undefined
158
+ return {
159
+ sessionName,
160
+ windowIndex,
161
+ windowName,
162
+ paneIndex,
163
+ paneId,
164
+ windowActive,
165
+ paneActive,
166
+ windowLayout,
167
+ }
168
+ }
169
+
170
+ /**
171
+ * Render the stable tmux state block: the part of a reading compared for
172
+ * change suppression. It excludes the turn preamble so re-injection is driven
173
+ * only by tmux state, not by loop position.
174
+ */
175
+ function renderState(location: TmuxLocation): string {
176
+ return `session ${location.sessionName}, `
177
+ + `window ${location.windowIndex} ${JSON.stringify(location.windowName)}, `
178
+ + `pane ${location.paneIndex} ${location.paneId}\n`
179
+ + `window active=${location.windowActive}, pane active=${location.paneActive}, `
180
+ + `layout ${location.windowLayout}`
181
+ }
182
+
183
+ /** Render the full durable reading, including the volatile turn preamble. */
184
+ function renderReading(location: TmuxLocation, turn: number): string {
185
+ return `${READING_PREFIX}${turn}):\n${renderState(location)}`
186
+ }
187
+
188
+ /**
189
+ * The stable state block of this plugin's latest durable injection, or
190
+ * `undefined` when the session has none. Scans raw durable events so the
191
+ * schedule survives compaction and resumed processes without process-local
192
+ * cache state.
193
+ */
194
+ /** Reject refresh intervals that cannot represent an exact elapsed-millisecond threshold. */
195
+ function validateRefreshInterval(refreshIntervalMs: number | undefined): void {
196
+ if (refreshIntervalMs !== undefined && (
197
+ !Number.isSafeInteger(refreshIntervalMs)
198
+ || refreshIntervalMs < 0
199
+ )) {
200
+ throw new TypeError(
201
+ `tmux-context: refreshIntervalMs must be a non-negative safe integer, got ${String(refreshIntervalMs)}`,
202
+ )
203
+ }
204
+ }
205
+
206
+ const tmuxContextStateSchema = zod.object({
207
+ state: zod.string(),
208
+ time: zod.number(),
209
+ }).nullable()
210
+
211
+ /**
212
+ * Register a prepended pre-step listener for the lifetime of `ctx`.
213
+ * Steps admitted during activation await the projection registration; a
214
+ * registration failure or owner disposal prevents the request from proceeding.
215
+ * @param ctx - plugin context; the listener is disposed with it.
216
+ * @param config - durable refresh scheduling configuration.
217
+ * @returns when the listener and projection are ready.
218
+ * @throws when the refresh interval is invalid.
219
+ */
220
+ export async function apply(ctx: Context, config: Config): Promise<void> {
221
+ const refreshIntervalMs = config.refreshIntervalMs
222
+ validateRefreshInterval(refreshIntervalMs)
223
+
224
+ const projectionReady = ctx.sessionProjections.register({
225
+ key: 'tmuxContext',
226
+ stateVersion: 1,
227
+ stateSchema: tmuxContextStateSchema,
228
+ init: () => null,
229
+ apply: (state, event) => {
230
+ if (event.type !== 'user/message'
231
+ || event.data.source.kind !== name) return state
232
+ const [block] = event.data.content
233
+ if (block?.type !== 'text') return state
234
+ const newline = block.text.indexOf('\n')
235
+ const stableState = newline === -1 ? '' : block.text.slice(newline + 1)
236
+ return { state: stableState, time: event.time }
237
+ },
238
+ })
239
+
240
+ ctx.on('agent/pre-step', async (
241
+ { agent, turn, step, signal },
242
+ next,
243
+ ): Promise<PreStepDecision> => {
244
+ const tmuxContextProjectionHandle = await projectionReady
245
+ ctx.fiber.assertActive()
246
+ const decision = await next()
247
+ if (decision.kind === 'reject' || signal.aborted || step !== 1) return decision
248
+ const bash = ctx.get('shell')
249
+ if (bash === undefined) return decision
250
+ const previous = tmuxContextProjectionHandle.stateOf(agent.session)
251
+ if (refreshIntervalMs !== undefined && refreshIntervalMs > 0 && previous !== null) {
252
+ const now = Date.now()
253
+ if (now >= previous.time && now - previous.time < refreshIntervalMs) return decision
254
+ }
255
+ const location = await queryTmuxLocation(bash, ctx.logger, process.pid, signal)
256
+ if (location === undefined) return decision
257
+ const state = renderState(location)
258
+ if (previous !== null && previous.state === state) return decision
259
+ const text = renderReading(location, turn)
260
+ return {
261
+ ...decision,
262
+ messages: [
263
+ createUserMessage({
264
+ content: [{ type: 'text', text }],
265
+ source: { kind: name, form: 'snapshot', sections: [{ name, text }] },
266
+ }),
267
+ ...decision.messages,
268
+ ],
269
+ }
270
+ }, { prepend: true })
271
+ await projectionReady
272
+ }