viber-channel 0.8.40 → 0.8.42

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.
@@ -190,6 +190,9 @@ export function capabilitiesText(channelVersion: string | null = null): string {
190
190
  " gemma: refused",
191
191
  " claude: leave model/effort OUT (runtime default) unless the",
192
192
  ` owner asks; codex: ${CODEX_DEFAULT_PAIR} unless the owner asks`,
193
+ " plugins claude only, optional: [\"name@marketplace\", …] ≤ 8, enabled for",
194
+ " that agent's session only (e.g. playwright@claude-plugins-official)",
195
+ " chrome claude only, optional: true launches it with Claude in Chrome",
193
196
  " update: send ONLY the fields you change plus expected_version (required); model or",
194
197
  " effort null clears it. 409 role_version_conflict: get, re-apply. 409 role_in_use",
195
198
  " (delete): templates still reference it — remove it from them first. Other 409:",
@@ -0,0 +1,86 @@
1
+ /**
2
+ * claude_runtime_publisher.ts — a claude agent's model, effort and context, left for
3
+ * the runner after each reply (#708 step-04).
4
+ *
5
+ * JP's rule (2026-10-17): the figures move on a round trip — a message in, the
6
+ * agent's answer out — and are pushed only if they changed. So nothing watches the
7
+ * session log: when the agent replies on the channel (`send_message`, or
8
+ * `message_agent` for an agent that only talks in DMs), the channel reads its own
9
+ * claude's log once and rewrites `<presenceDir>/<id>.runtime.json` if what the chip
10
+ * shows changed. The runner then pushes it, like a codex agent's file.
11
+ *
12
+ * The read waits `delayMs`: the assistant entry carrying the reply's tool call lands
13
+ * in the log within 200 ms of the call starting (measured, plan 708 step-01). Replies
14
+ * within that window are coalesced into one read.
15
+ */
16
+ import { readClaudeRuntime } from "./claude_session_log.js";
17
+ import { runtimeFilePath, writeRuntimeFile } from "./codex_runtime.js";
18
+ import { processStartTimeAsync } from "./process_start.js";
19
+ import { type RuntimeV1, sameRuntime } from "./runtime_info.js";
20
+
21
+ export const PUBLISH_DELAY_MS = 500;
22
+
23
+ export interface ClaudeRuntimePublisherOptions {
24
+ /** The claude process this channel serves (parent watchdog); null = none found. */
25
+ getClaudePid: () => number | null;
26
+ identityBaseUrl: string;
27
+ /** Read at publish time: the instance registers after the channel starts. */
28
+ getInstanceId: () => string;
29
+ lockDir?: string;
30
+ delayMs?: number;
31
+ probeStartTime?: (pid: number) => Promise<number | undefined>;
32
+ read?: (q: { pid: number; startTimeMs: number }) => RuntimeV1 | undefined;
33
+ write?: (path: string, instanceId: string, r: RuntimeV1) => void;
34
+ setTimer?: (fn: () => void, ms: number) => unknown;
35
+ log?: (line: string) => void;
36
+ }
37
+
38
+ export class ClaudeRuntimePublisher {
39
+ private startTime: number | undefined;
40
+ private startPid: number | null = null;
41
+ private pending = false;
42
+ private last: RuntimeV1 | undefined;
43
+ private lastInstance = "";
44
+
45
+ constructor(private readonly opts: ClaudeRuntimePublisherOptions) {}
46
+
47
+ /** The agent just replied on the channel. Never throws, never blocks the reply. */
48
+ afterReply(): void {
49
+ if (this.opts.getClaudePid() === null || this.pending) return;
50
+ this.pending = true;
51
+ const setTimer =
52
+ this.opts.setTimer ??
53
+ ((fn: () => void, ms: number) => {
54
+ const t = setTimeout(fn, ms);
55
+ (t as { unref?: () => void }).unref?.();
56
+ return t;
57
+ });
58
+ setTimer(() => {
59
+ this.pending = false;
60
+ void this.publish().catch((err) => this.log(`[runtime] publish failed: ${String(err)}\n`));
61
+ }, this.opts.delayMs ?? PUBLISH_DELAY_MS);
62
+ }
63
+
64
+ /** One read and, if what the chip shows changed, one write. Exposed for tests. */
65
+ async publish(): Promise<void> {
66
+ const pid = this.opts.getClaudePid();
67
+ const instanceId = this.opts.getInstanceId();
68
+ if (pid === null || instanceId === "") return;
69
+ if (this.startTime === undefined || this.startPid !== pid) {
70
+ this.startPid = pid;
71
+ this.startTime = await (this.opts.probeStartTime ?? ((p: number) => processStartTimeAsync(p)))(pid);
72
+ if (this.startTime === undefined) return; // retried on the next reply
73
+ }
74
+ const r = (this.opts.read ?? readClaudeRuntime)({ pid, startTimeMs: this.startTime });
75
+ // Unknown: keep the file as it is — a torn read is not a reason to clear the chip.
76
+ if (r === undefined) return;
77
+ if (instanceId === this.lastInstance && sameRuntime(this.last, r)) return;
78
+ (this.opts.write ?? writeRuntimeFile)(runtimeFilePath(this.opts.identityBaseUrl, instanceId, this.opts.lockDir), instanceId, r);
79
+ this.last = r;
80
+ this.lastInstance = instanceId;
81
+ }
82
+
83
+ private log(line: string): void {
84
+ (this.opts.log ?? ((l: string) => process.stderr.write(l)))(line);
85
+ }
86
+ }
@@ -0,0 +1,186 @@
1
+ /**
2
+ * claude_session_log.ts — read a Claude agent's model, effort and context from its
3
+ * session log (#708 step-02).
4
+ *
5
+ * Two files, both internal to Claude Code (undocumented, may change between
6
+ * versions — every field is optional here, and a miss yields "unknown", never 0):
7
+ *
8
+ * - `~/.claude/sessions/<pid>.json`: the live registry of a claude process. It
9
+ * names the CURRENT session (it follows `/clear` and resume), so it is re-read
10
+ * on every call, never cached. Its `procStart` (Windows FILETIME) equals the
11
+ * process start time measured by `process_start.ts` to the millisecond
12
+ * (measured, plan 708 step-01): a pid recycled by another process is refused.
13
+ * - `~/.claude/projects/<slug(cwd)>/<sessionId>.jsonl`: one entry per event. The
14
+ * last `assistant` entry carries `message.model`, `effort` and `message.usage`;
15
+ * occupation = input + cache_creation + cache_read of that LAST call (the status
16
+ * line's formula). It is written within 200 ms of a tool call starting.
17
+ *
18
+ * Known lag, by construction: after `/compact` or `/model`, the figures stay those of
19
+ * the last call until the next one is logged.
20
+ */
21
+ import { closeSync, existsSync, fstatSync, openSync, readFileSync, readSync, readdirSync } from "node:fs";
22
+ import { homedir } from "node:os";
23
+ import { join } from "node:path";
24
+ import { CLAUDE_CONTEXT_WINDOW, type RuntimeV1, buildRuntime, isEmptyRuntime } from "./runtime_info.js";
25
+
26
+ /** FILETIME epoch (1601-01-01) to Unix epoch, in ms. */
27
+ const FILETIME_UNIX_OFFSET_MS = 11_644_473_600_000;
28
+ /** `procStart` and the CIM probe agree to the ms today (measured); the slack absorbs a
29
+ * rounding change between versions — a recycled pid never starts within 5 ms. */
30
+ const START_TOLERANCE_MS = 5;
31
+ /** Tail windows, tried in order: an assistant entry carrying a big tool input can be large. */
32
+ export const TAIL_BYTES: readonly number[] = [256 * 1024, 4 * 1024 * 1024];
33
+
34
+ export interface LiveSession {
35
+ sessionId: string;
36
+ cwd: string;
37
+ }
38
+
39
+ /** The `/resume` bucket of a working directory: every non-alphanumeric char → '-'. */
40
+ export function projectSlug(cwd: string): string {
41
+ return cwd.replace(/[^A-Za-z0-9]/g, "-");
42
+ }
43
+
44
+ /** FILETIME string (100 ns ticks since 1601) → Unix ms, or undefined. */
45
+ export function fileTimeToMs(raw: unknown): number | undefined {
46
+ if (typeof raw !== "string" || !/^\d{1,20}$/.test(raw)) return undefined;
47
+ // Rounded like the CIM probe (`[int64]` of a fractional ms rounds), measured equal.
48
+ const ms = Number((BigInt(raw) + 5_000n) / 10_000n) - FILETIME_UNIX_OFFSET_MS;
49
+ return ms > 0 ? ms : undefined;
50
+ }
51
+
52
+ /**
53
+ * The live session of claude process `pid`, or undefined when the registry is
54
+ * missing, unreadable, or belongs to another process (pid recycled).
55
+ */
56
+ export function readLiveSession(home: string, pid: number, startTimeMs: number): LiveSession | undefined {
57
+ let d: Record<string, unknown>;
58
+ try {
59
+ d = JSON.parse(readFileSync(join(home, ".claude", "sessions", `${pid}.json`), "utf8"));
60
+ } catch {
61
+ return undefined;
62
+ }
63
+ if (typeof d !== "object" || d === null || d.pid !== pid) return undefined;
64
+ const started = fileTimeToMs(d.procStart);
65
+ if (started === undefined || Math.abs(started - startTimeMs) > START_TOLERANCE_MS) return undefined;
66
+ if (typeof d.sessionId !== "string" || !/^[0-9a-f-]{36}$/i.test(d.sessionId)) return undefined;
67
+ if (typeof d.cwd !== "string" || d.cwd === "") return undefined;
68
+ return { sessionId: d.sessionId, cwd: d.cwd };
69
+ }
70
+
71
+ /** The session log path: the cwd's bucket first, then any bucket holding that id. */
72
+ export function resolveSessionLog(home: string, live: LiveSession): string | undefined {
73
+ const projects = join(home, ".claude", "projects");
74
+ const file = `${live.sessionId}.jsonl`;
75
+ const direct = join(projects, projectSlug(live.cwd), file);
76
+ if (existsSync(direct)) return direct;
77
+ try {
78
+ for (const bucket of readdirSync(projects)) {
79
+ const p = join(projects, bucket, file);
80
+ if (existsSync(p)) return p;
81
+ }
82
+ } catch {
83
+ // no projects directory: unknown
84
+ }
85
+ return undefined;
86
+ }
87
+
88
+ function readTail(path: string, bytes: number): { text: string; whole: boolean } | undefined {
89
+ let fd: number | undefined;
90
+ try {
91
+ fd = openSync(path, "r");
92
+ const size = fstatSync(fd).size;
93
+ const len = Math.min(size, bytes);
94
+ const buf = Buffer.alloc(len);
95
+ readSync(fd, buf, 0, len, size - len);
96
+ return { text: buf.toString("utf8"), whole: len === size };
97
+ } catch {
98
+ return undefined;
99
+ } finally {
100
+ if (fd !== undefined) closeSync(fd);
101
+ }
102
+ }
103
+
104
+ export interface LastTurn {
105
+ model?: string;
106
+ effort?: string;
107
+ contextTokens?: number;
108
+ }
109
+
110
+ const count = (n: unknown): number | undefined =>
111
+ typeof n === "number" && Number.isInteger(n) && n >= 0 ? n : undefined;
112
+
113
+ /** The last real main-thread assistant call in a chunk of log, or undefined. */
114
+ export function lastTurnOf(text: string, whole: boolean): LastTurn | undefined {
115
+ const lines = text.split("\n");
116
+ // A tail cut mid-line: the first line is a fragment. The last may be a write in progress.
117
+ const start = whole ? 0 : 1;
118
+ for (let i = lines.length - 1; i >= start; i--) {
119
+ const line = lines[i]?.trim();
120
+ if (!line || !line.includes('"assistant"')) continue;
121
+ let e: Record<string, unknown>;
122
+ try {
123
+ e = JSON.parse(line);
124
+ } catch {
125
+ continue;
126
+ }
127
+ if (e.type !== "assistant" || e.isSidechain === true) continue;
128
+ const m = e.message as Record<string, unknown> | undefined;
129
+ // An API error is logged as a "<synthetic>" assistant entry with zero usage: not a call.
130
+ if (!m || m.model === "<synthetic>") continue;
131
+ const u = m.usage as Record<string, unknown> | undefined;
132
+ const parts = u ? [count(u.input_tokens), count(u.cache_creation_input_tokens), count(u.cache_read_input_tokens)] : [];
133
+ return {
134
+ model: typeof m.model === "string" ? m.model : undefined,
135
+ effort: typeof e.effort === "string" ? e.effort : undefined,
136
+ contextTokens: parts.length === 3 && parts.every((p) => p !== undefined)
137
+ ? (parts as number[]).reduce((a, b) => a + b, 0)
138
+ : undefined,
139
+ };
140
+ }
141
+ return undefined;
142
+ }
143
+
144
+ /** The last turn of a session log, widening the tail once if the first window holds none. */
145
+ export function readLastTurn(path: string, tails: readonly number[] = TAIL_BYTES): LastTurn | undefined {
146
+ for (const bytes of tails) {
147
+ const tail = readTail(path, bytes);
148
+ if (!tail) return undefined;
149
+ const turn = lastTurnOf(tail.text, tail.whole);
150
+ if (turn || tail.whole) return turn;
151
+ }
152
+ return undefined;
153
+ }
154
+
155
+ export interface ClaudeRuntimeQuery {
156
+ pid: number;
157
+ startTimeMs: number;
158
+ home?: string;
159
+ now?: () => number;
160
+ }
161
+
162
+ /** The runtime of a claude agent, or undefined when nothing about it is known. */
163
+ export function readClaudeRuntime(q: ClaudeRuntimeQuery): RuntimeV1 | undefined {
164
+ const home = q.home ?? homedir();
165
+ const live = readLiveSession(home, q.pid, q.startTimeMs);
166
+ if (!live) return undefined;
167
+ const log = resolveSessionLog(home, live);
168
+ if (!log) return undefined;
169
+ const turn = readLastTurn(log);
170
+ return turn ? runtimeOfTurn(turn, (q.now ?? Date.now)()) : undefined;
171
+ }
172
+
173
+ /** A claude turn as a runtime, on the fixed 1 M window; undefined when nothing is known. */
174
+ export function runtimeOfTurn(turn: LastTurn, observedAt: number): RuntimeV1 | undefined {
175
+ const r = buildRuntime(
176
+ {
177
+ model: turn.model,
178
+ effort: turn.effort,
179
+ contextTokens: turn.contextTokens,
180
+ // A window alone says nothing about this agent.
181
+ contextWindow: turn.contextTokens === undefined ? undefined : CLAUDE_CONTEXT_WINDOW,
182
+ },
183
+ observedAt,
184
+ );
185
+ return isEmptyRuntime(r) ? undefined : r;
186
+ }
@@ -0,0 +1,123 @@
1
+ /**
2
+ * codex_runtime.ts — model, effort and context of a codex agent, left for the
3
+ * runner in `<presenceDir>/<instance_id>.runtime.json` (#708 step-03).
4
+ *
5
+ * Sources, measured on codex-cli 0.163.0 (plan 708 step-01):
6
+ * - `thread/start` / `thread/resume` answer the EFFECTIVE `model` and
7
+ * `reasoningEffort` (null = not reported) — the template's pair is only what was
8
+ * asked;
9
+ * - `thread/tokenUsage/updated` carries `tokenUsage.last.totalTokens` (occupation of
10
+ * the last call, right after a compaction too) and `tokenUsage.modelContextWindow`.
11
+ * `total` is cumulative over the thread's life and `last.inputTokens` drops to a
12
+ * false 0 right after a compaction: neither is read.
13
+ *
14
+ * The file is rewritten only when a business field changes (`observed_at` excluded),
15
+ * atomically, so the runner never reads half of it.
16
+ */
17
+ import { mkdirSync, readFileSync, renameSync, unlinkSync, writeFileSync } from "node:fs";
18
+ import { dirname, join } from "node:path";
19
+ import { isInstanceId, presenceDir } from "./presence_record.js";
20
+ import { type RuntimeV1, buildRuntime, isEmptyRuntime, parseRuntime, sameRuntime } from "./runtime_info.js";
21
+
22
+ /** A runtime file name — never a presence record (`<id>.json`) nor a temp file. */
23
+ export const RUNTIME_FILE_RE = /^[0-9a-f]{32}\.runtime\.json$/;
24
+
25
+ export function runtimeFilePath(identityBaseUrl: string, instanceId: string, lockDir?: string): string {
26
+ if (!isInstanceId(instanceId)) {
27
+ throw new Error(`runtimeFilePath: not an instance id: ${JSON.stringify(instanceId)}`);
28
+ }
29
+ return join(presenceDir(identityBaseUrl, lockDir), `${instanceId.toLowerCase()}.runtime.json`);
30
+ }
31
+
32
+ export interface RuntimeFile extends RuntimeV1 {
33
+ instance_id: string;
34
+ }
35
+
36
+ /** Atomic write: a reader sees the old file or the new one, never half of one. */
37
+ export function writeRuntimeFile(path: string, instanceId: string, runtime: RuntimeV1): void {
38
+ mkdirSync(dirname(path), { recursive: true });
39
+ const tmp = `${path}.${process.pid}.tmp`;
40
+ const body: RuntimeFile = { ...runtime, instance_id: instanceId.toLowerCase() };
41
+ writeFileSync(tmp, JSON.stringify(body), "utf8");
42
+ try {
43
+ renameSync(tmp, path);
44
+ } catch (err) {
45
+ try {
46
+ unlinkSync(tmp);
47
+ } catch {
48
+ // the tmp may already be gone; the rename error is the one that matters
49
+ }
50
+ throw err;
51
+ }
52
+ }
53
+
54
+ /** The runtime in a file, or undefined when absent, torn or for another instance. */
55
+ export function readRuntimeFile(path: string, instanceId: string): RuntimeV1 | undefined {
56
+ let parsed: unknown;
57
+ try {
58
+ parsed = JSON.parse(readFileSync(path, "utf8"));
59
+ } catch {
60
+ return undefined;
61
+ }
62
+ if (typeof parsed !== "object" || parsed === null) return undefined;
63
+ const { instance_id, ...rest } = parsed as Record<string, unknown>;
64
+ if (instance_id !== instanceId.toLowerCase()) return undefined;
65
+ return parseRuntime(rest);
66
+ }
67
+
68
+ const count = (n: unknown): number | undefined =>
69
+ typeof n === "number" && Number.isInteger(n) && n >= 0 ? n : undefined;
70
+
71
+ /** Collects what codex says and writes the file when it changes. */
72
+ export class CodexRuntimeWriter {
73
+ private model?: string;
74
+ private effort?: string;
75
+ private contextTokens?: number;
76
+ private contextWindow?: number;
77
+ private last: RuntimeV1 | undefined;
78
+
79
+ constructor(
80
+ private readonly path: string,
81
+ private readonly instanceId: string,
82
+ private readonly now: () => number = Date.now,
83
+ private readonly write: (path: string, id: string, r: RuntimeV1) => void = writeRuntimeFile,
84
+ private readonly log: (line: string) => void = (l) => process.stderr.write(l),
85
+ ) {}
86
+
87
+ /** The answer to `thread/start` or `thread/resume`. */
88
+ onThread(result: unknown): void {
89
+ const r = (typeof result === "object" && result !== null ? result : {}) as Record<string, unknown>;
90
+ if (typeof r.model === "string") this.model = r.model;
91
+ // null = "not reported": keep what we knew rather than forget it.
92
+ if (typeof r.reasoningEffort === "string") this.effort = r.reasoningEffort;
93
+ this.flush();
94
+ }
95
+
96
+ /** The params of `thread/tokenUsage/updated`. */
97
+ onTokenUsage(params: unknown): void {
98
+ const usage = (params as { tokenUsage?: { last?: { totalTokens?: unknown }; modelContextWindow?: unknown } } | null)
99
+ ?.tokenUsage;
100
+ const tokens = count(usage?.last?.totalTokens);
101
+ const window = count(usage?.modelContextWindow);
102
+ // Both terms or neither: a percent from a stale numerator and a fresh window is a guess.
103
+ if (tokens === undefined || window === undefined || window === 0) return;
104
+ this.contextTokens = tokens;
105
+ this.contextWindow = window;
106
+ this.flush();
107
+ }
108
+
109
+ private flush(): void {
110
+ const next = buildRuntime(
111
+ { model: this.model, effort: this.effort, contextTokens: this.contextTokens, contextWindow: this.contextWindow },
112
+ this.now(),
113
+ );
114
+ if (isEmptyRuntime(next) || sameRuntime(this.last, next)) return;
115
+ try {
116
+ this.write(this.path, this.instanceId, next);
117
+ this.last = next;
118
+ } catch (err) {
119
+ // The file serves the web only: an agent never dies of it. Retried on the next change.
120
+ this.log(`[codex-runtime] write failed (${this.path}): ${String(err)}\n`);
121
+ }
122
+ }
123
+ }
@@ -0,0 +1,106 @@
1
+ /**
2
+ * macro_job_host.ts — the PowerShell host a user macro runs under (#709 step-05).
3
+ *
4
+ * The runner starts THIS host (PowerShell 5.1, `-EncodedCommand`), never the macro directly.
5
+ * The host creates an UNNAMED job object with `KILL_ON_JOB_CLOSE`, puts ITSELF in it, then runs
6
+ * the macro's private copy: everything the macro starts is born inside the job. The host holds
7
+ * the only handle, so when it dies — normal exit, or the runner killing it on timeout — Windows
8
+ * kills every member, grandchildren included. `taskkill /T` is NOT used: it walks PPIDs on a
9
+ * snapshot and misses a grandchild whose parent died first (#512, measured).
10
+ *
11
+ * ⚠ NO `JOB_OBJECT_LIMIT_BREAKAWAY_OK` (0x0800), ever: Git bash asks for
12
+ * `CREATE_BREAKAWAY_FROM_JOB`, so granting it lets a child leave while the guard looks active
13
+ * (#512, measured). Unnamed, so no other launch can open or share it.
14
+ *
15
+ * The structures are the ones `vibe-master/scripts/agent_job_host.ps1` already runs (#512).
16
+ * Inputs arrive in the environment and are REMOVED before the macro starts:
17
+ * VIBER_MACRO_COPY the private copy to run
18
+ * VIBER_MACRO_INTERPRETER the absolute powershell.exe (built by the runner with path.join)
19
+ * A host that cannot set the job up prints `refused=job` and exits 87 (the code
20
+ * `agent_job_host.ps1` reserves for a refusal); otherwise it exits with the macro's code.
21
+ */
22
+
23
+ /** Exit code of a host refusal, kept out of the range a script usually returns. */
24
+ export const MACRO_HOST_REFUSED_EXIT = 87;
25
+ export const MACRO_HOST_REFUSED_LINE = "refused=job";
26
+
27
+ export const MACRO_JOB_HOST_PS1 = String.raw`
28
+ $ErrorActionPreference = 'Stop'
29
+ # First line of the local log: tells a host that never started from one stuck later.
30
+ [Console]::Out.WriteLine('host=started ' + [DateTime]::Now.ToString('HH:mm:ss.fff'))
31
+ $copy = $env:VIBER_MACRO_COPY
32
+ $interpreter = $env:VIBER_MACRO_INTERPRETER
33
+ Remove-Item Env:VIBER_MACRO_COPY -ErrorAction SilentlyContinue
34
+ Remove-Item Env:VIBER_MACRO_INTERPRETER -ErrorAction SilentlyContinue
35
+ try {
36
+ Add-Type -TypeDefinition @'
37
+ using System;
38
+ using System.Runtime.InteropServices;
39
+ public static class ViberMacroJob {
40
+ [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
41
+ public static extern IntPtr CreateJobObject(IntPtr attrs, string name);
42
+ [DllImport("kernel32.dll", SetLastError = true)]
43
+ public static extern bool SetInformationJobObject(IntPtr job, int infoClass, IntPtr info, uint len);
44
+ [DllImport("kernel32.dll", SetLastError = true)]
45
+ public static extern bool AssignProcessToJobObject(IntPtr job, IntPtr process);
46
+ [DllImport("kernel32.dll")]
47
+ public static extern IntPtr GetCurrentProcess();
48
+ [StructLayout(LayoutKind.Sequential)]
49
+ public struct JOBOBJECT_BASIC_LIMIT_INFORMATION {
50
+ public long PerProcessUserTimeLimit; public long PerJobUserTimeLimit;
51
+ public uint LimitFlags; public UIntPtr MinimumWorkingSetSize;
52
+ public UIntPtr MaximumWorkingSetSize; public uint ActiveProcessLimit;
53
+ public UIntPtr Affinity; public uint PriorityClass; public uint SchedulingClass;
54
+ }
55
+ [StructLayout(LayoutKind.Sequential)]
56
+ public struct IO_COUNTERS {
57
+ public ulong ReadOperationCount; public ulong WriteOperationCount;
58
+ public ulong OtherOperationCount; public ulong ReadTransferCount;
59
+ public ulong WriteTransferCount; public ulong OtherTransferCount;
60
+ }
61
+ [StructLayout(LayoutKind.Sequential)]
62
+ public struct JOBOBJECT_EXTENDED_LIMIT_INFORMATION {
63
+ public JOBOBJECT_BASIC_LIMIT_INFORMATION BasicLimitInformation;
64
+ public IO_COUNTERS IoInfo; public UIntPtr ProcessMemoryLimit;
65
+ public UIntPtr JobMemoryLimit; public UIntPtr PeakProcessMemoryUsed;
66
+ public UIntPtr PeakJobMemoryUsed;
67
+ }
68
+ // 0x2000 = JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE. 0x0800 (BREAKAWAY_OK) is NEVER set.
69
+ public const uint KILL_ON_JOB_CLOSE = 0x2000;
70
+ public static void Enter() {
71
+ IntPtr job = CreateJobObject(IntPtr.Zero, null);
72
+ if (job == IntPtr.Zero) throw new InvalidOperationException("CreateJobObject " + Marshal.GetLastWin32Error());
73
+ var info = new JOBOBJECT_EXTENDED_LIMIT_INFORMATION();
74
+ info.BasicLimitInformation.LimitFlags = KILL_ON_JOB_CLOSE;
75
+ int len = Marshal.SizeOf(info);
76
+ IntPtr p = Marshal.AllocHGlobal(len);
77
+ try {
78
+ Marshal.StructureToPtr(info, p, false);
79
+ if (!SetInformationJobObject(job, 9, p, (uint)len)) throw new InvalidOperationException("SetInformationJobObject " + Marshal.GetLastWin32Error());
80
+ } finally { Marshal.FreeHGlobal(p); }
81
+ if (!AssignProcessToJobObject(job, GetCurrentProcess())) throw new InvalidOperationException("AssignProcessToJobObject " + Marshal.GetLastWin32Error());
82
+ // The handle is deliberately never closed: it dies with this process, and the job with it.
83
+ }
84
+ }
85
+ '@
86
+ if (-not $copy -or -not $interpreter) { throw 'missing input' }
87
+ [ViberMacroJob]::Enter()
88
+ # This line STARTS the macro's own clock in the runner (MACRO_HOST_READY_LINE): keep it.
89
+ [Console]::Out.WriteLine('job=entered ' + [DateTime]::Now.ToString('HH:mm:ss.fff'))
90
+ } catch {
91
+ [Console]::Out.WriteLine('refused=job')
92
+ exit 87
93
+ }
94
+ # Without PATHEXT, PowerShell 5.1 does NOT run a native program named by its full path: the call
95
+ # operator returns at once, nothing runs, $LASTEXITCODE stays empty and the host exits 0 (measured,
96
+ # #709 step-05, bisected over the allowlisted env). Set here, as a constant, by the host.
97
+ $env:PATHEXT = '.COM;.EXE'
98
+ & $interpreter -NoProfile -NonInteractive -ExecutionPolicy Bypass -File $copy
99
+ if ($null -eq $LASTEXITCODE) { [Console]::Out.WriteLine('refused=job not-started'); exit 87 }
100
+ exit $LASTEXITCODE
101
+ `;
102
+
103
+ /** `-EncodedCommand` takes base64 of UTF-16LE. */
104
+ export function encodedHost(): string {
105
+ return Buffer.from(MACRO_JOB_HOST_PS1, "utf16le").toString("base64");
106
+ }
@@ -0,0 +1,142 @@
1
+ /**
2
+ * macro_list.ts — the LOCAL half of a user macro (#709): `<app home>\.viber\macros.json`,
3
+ * name → absolute path of a `.ps1` + the SHA-256 of its bytes.
4
+ *
5
+ * Shared by the CLI that writes it (`viber-gateway macro add`) and the runner that reads it
6
+ * before every run, so the hash the owner pastes into the web and the hash the runner
7
+ * recomputes come from ONE function.
8
+ *
9
+ * Default-deny, like `runner-policy.json`: an ABSENT file is an empty list (no macro), a
10
+ * PRESENT file that is not exactly v1 — bad JSON, unknown version, one invalid entry — is
11
+ * `invalid` and the runner refuses every macro. A half-read list never runs anything.
12
+ */
13
+ import { createHash, randomBytes } from "node:crypto";
14
+ import { existsSync, mkdirSync, readFileSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs";
15
+ import { dirname, join, win32 } from "node:path";
16
+
17
+ /** Same grammar as the server (`viber-api/src/db/macros.ts`): lowercase slug, no dot, no
18
+ * separator. The name is a KEY — never a path, never part of a command line. */
19
+ export const MACRO_NAME_RE = /^[a-z0-9][a-z0-9-]{0,39}$/;
20
+ export const MACRO_SHA256_RE = /^[0-9a-f]{64}$/;
21
+ /** First cut (decision 3): PowerShell scripts only. */
22
+ export const MACRO_EXTENSION = ".ps1";
23
+
24
+ export interface MacroEntry {
25
+ path: string;
26
+ sha256: string;
27
+ }
28
+
29
+ export type MacroListRead =
30
+ | { kind: "ok"; macros: Map<string, MacroEntry> }
31
+ | { kind: "invalid"; reason: string };
32
+
33
+ /** SHA-256 of the raw bytes, lowercase hex — THE hash of a macro, everywhere. */
34
+ export function macroSha256(bytes: Uint8Array): string {
35
+ return createHash("sha256").update(bytes).digest("hex");
36
+ }
37
+
38
+ export function macroListPath(home: string): string {
39
+ return join(home, ".viber", "macros.json");
40
+ }
41
+
42
+ /** A local drive path: `C:` then a separator. `path.isAbsolute` also says yes to `\x.ps1` (the
43
+ * CURRENT drive: the same text names other files under another cwd) and to `\\srv\share\x.ps1`
44
+ * (a script on another machine) — both refused (review Opus, measured). */
45
+ const DRIVE_PATH_RE = /^[A-Za-z]:[\\/]/;
46
+
47
+ /** Why `path` cannot be a macro script, or null. Shape only: existence is the caller's. */
48
+ export function macroPathProblem(path: string): string | null {
49
+ if (!DRIVE_PATH_RE.test(path)) return "the path must be absolute, on a local drive (C:\\...), not a network share";
50
+ if (win32.normalize(path) !== path) return "the path must be normalized (no . or .., single separators)";
51
+ if (!path.toLowerCase().endsWith(MACRO_EXTENSION)) return `only ${MACRO_EXTENSION} scripts are accepted`;
52
+ return null;
53
+ }
54
+
55
+ function parseEntry(name: string, raw: unknown): MacroEntry | string {
56
+ if (!MACRO_NAME_RE.test(name)) return `invalid macro name: ${JSON.stringify(name.slice(0, 48))}`;
57
+ if (typeof raw !== "object" || raw === null || Array.isArray(raw)) return `macro ${name}: entry must be an object`;
58
+ const e = raw as Record<string, unknown>;
59
+ const extra = Object.keys(e).find((k) => k !== "path" && k !== "sha256");
60
+ if (extra !== undefined) return `macro ${name}: unknown field ${JSON.stringify(extra.slice(0, 32))}`;
61
+ if (typeof e.path !== "string") return `macro ${name}: path must be a string`;
62
+ const problem = macroPathProblem(e.path);
63
+ if (problem) return `macro ${name}: ${problem}`;
64
+ if (typeof e.sha256 !== "string" || !MACRO_SHA256_RE.test(e.sha256)) return `macro ${name}: sha256 must be 64 lowercase hex`;
65
+ return { path: e.path, sha256: e.sha256 };
66
+ }
67
+
68
+ export function readMacroList(home: string): MacroListRead {
69
+ const path = macroListPath(home);
70
+ if (!existsSync(path)) return { kind: "ok", macros: new Map() };
71
+ let raw: unknown;
72
+ try {
73
+ // A leading UTF-8 BOM (Notepad, PowerShell 5.1 `Set-Content`) is not an error of the content.
74
+ raw = JSON.parse(readFileSync(path, "utf-8").replace(/^/, ""));
75
+ } catch {
76
+ return { kind: "invalid", reason: "macros.json is not valid JSON" };
77
+ }
78
+ if (typeof raw !== "object" || raw === null || Array.isArray(raw)) return { kind: "invalid", reason: "macros.json must be an object" };
79
+ const top = raw as Record<string, unknown>;
80
+ if (top.v !== 1) return { kind: "invalid", reason: "macros.json: unknown version (expected v: 1)" };
81
+ const extra = Object.keys(top).find((k) => k !== "v" && k !== "macros");
82
+ if (extra !== undefined) return { kind: "invalid", reason: `macros.json: unknown field ${JSON.stringify(extra.slice(0, 32))}` };
83
+ if (typeof top.macros !== "object" || top.macros === null || Array.isArray(top.macros)) {
84
+ return { kind: "invalid", reason: "macros.json: macros must be an object" };
85
+ }
86
+ const macros = new Map<string, MacroEntry>();
87
+ for (const [name, entry] of Object.entries(top.macros as Record<string, unknown>)) {
88
+ const parsed = parseEntry(name, entry);
89
+ if (typeof parsed === "string") return { kind: "invalid", reason: parsed };
90
+ macros.set(name, parsed);
91
+ }
92
+ return { kind: "ok", macros };
93
+ }
94
+
95
+ /** Atomic write: a temp file in the same folder, then a rename over the list. */
96
+ export function writeMacroList(home: string, macros: Map<string, MacroEntry>): void {
97
+ const path = macroListPath(home);
98
+ mkdirSync(dirname(path), { recursive: true });
99
+ const body = { v: 1, macros: Object.fromEntries([...macros.entries()].sort(([a], [b]) => a.localeCompare(b))) };
100
+ const tmp = `${path}.${randomBytes(6).toString("hex")}.tmp`;
101
+ writeFileSync(tmp, `${JSON.stringify(body, null, 2)}\n`, { flag: "wx" });
102
+ try {
103
+ renameSync(tmp, path);
104
+ } catch (err) {
105
+ rmSync(tmp, { force: true }); // e.g. EPERM: the list held open without sharing
106
+ throw err;
107
+ }
108
+ }
109
+
110
+ export type MacroEdit = { ok: true; entry: MacroEntry; previous: MacroEntry | null } | { ok: false; reason: string };
111
+
112
+ /** Add (or re-hash) a macro: the script must exist now; its bytes are hashed once. */
113
+ export function addMacro(home: string, name: string, rawPath: string): MacroEdit {
114
+ // Stored normalized: `C:\a\..\x.ps1` is written as `C:\x.ps1`, so the list never holds a
115
+ // non-normal path (the reader refuses one).
116
+ const scriptPath = DRIVE_PATH_RE.test(rawPath) ? win32.resolve(rawPath) : rawPath;
117
+ if (!MACRO_NAME_RE.test(name)) return { ok: false, reason: `the name must match ${MACRO_NAME_RE} (lowercase, digits, dashes)` };
118
+ const problem = macroPathProblem(scriptPath);
119
+ if (problem) return { ok: false, reason: problem };
120
+ let bytes: Uint8Array;
121
+ try {
122
+ if (!statSync(scriptPath).isFile()) return { ok: false, reason: "the path is not a file" };
123
+ bytes = readFileSync(scriptPath);
124
+ } catch (err) {
125
+ return { ok: false, reason: `cannot read the script: ${(err as Error).message}` };
126
+ }
127
+ const list = readMacroList(home);
128
+ if (list.kind === "invalid") return { ok: false, reason: `${list.reason} — fix or remove the file first` };
129
+ const entry = { path: scriptPath, sha256: macroSha256(bytes) };
130
+ const previous = list.macros.get(name) ?? null;
131
+ list.macros.set(name, entry);
132
+ writeMacroList(home, list.macros);
133
+ return { ok: true, entry, previous };
134
+ }
135
+
136
+ export function removeMacro(home: string, name: string): { ok: true } | { ok: false; reason: string } {
137
+ const list = readMacroList(home);
138
+ if (list.kind === "invalid") return { ok: false, reason: `${list.reason} — fix or remove the file first` };
139
+ if (!list.macros.delete(name)) return { ok: false, reason: `no macro named ${JSON.stringify(name.slice(0, 48))}` };
140
+ writeMacroList(home, list.macros);
141
+ return { ok: true };
142
+ }