tryharness 0.7.82 → 0.7.86
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/README.md +21 -19
- package/assets/dsh-plugin.mjs +75 -4
- package/assets/herdr-mod/harness/main.js +367 -0
- package/assets/herdr-mod/harness/mod.json +6 -0
- package/assets/opencode-plugin.js +87 -22
- package/assets/pi-extension.ts +81 -2
- package/cli.mjs +544 -208
- package/lib/adapters.mjs +62 -27
- package/lib/agentBinaries.mjs +6 -8
- package/lib/agentClaims.mjs +168 -0
- package/lib/agentReadTools.json +415 -0
- package/lib/agentSignIn.mjs +17 -18
- package/lib/agentWiring.mjs +114 -0
- package/lib/archetypes.js +10 -11
- package/lib/attention.mjs +100 -0
- package/lib/audit.mjs +1 -1
- package/lib/backupSetup.mjs +6 -28
- package/lib/bankrApprovals.mjs +86 -0
- package/lib/boardAccess.mjs +40 -66
- package/lib/boardBackup.mjs +86 -85
- package/lib/boardCommands.mjs +28 -0
- package/lib/boardFileCommands.mjs +29 -36
- package/lib/boardFiles.mjs +83 -15
- package/lib/boardMirror.mjs +78 -11
- package/lib/boardProtocol.json +193 -123
- package/lib/boardThreads.mjs +19 -37
- package/lib/boardTools.mjs +22 -15
- package/lib/boardWatches.mjs +43 -15
- package/lib/bridge.mjs +7 -3
- package/lib/browserAgentTools.mjs +59 -0
- package/lib/browserWake.mjs +0 -6
- package/lib/cards.mjs +57 -2
- package/lib/circling.mjs +189 -0
- package/lib/cleanup.mjs +234 -0
- package/lib/cloudBoot.mjs +21 -4
- package/lib/cloudSave.mjs +46 -5
- package/lib/compaction.mjs +8 -1
- package/lib/completion.mjs +358 -0
- package/lib/computerDevices.mjs +853 -0
- package/lib/connectionStatus.mjs +34 -0
- package/lib/connectors.mjs +139 -1
- package/lib/coordinator.mjs +108 -14
- package/lib/coreModels.mjs +36 -12
- package/lib/daemon.mjs +2435 -333
- package/lib/daemonLock.mjs +103 -0
- package/lib/deviceDoor.mjs +308 -0
- package/lib/deviceIdentity.mjs +114 -0
- package/lib/deviceList.mjs +172 -0
- package/lib/deviceSeal.mjs +74 -0
- package/lib/dispatcher.mjs +497 -26
- package/lib/dispatches.mjs +3 -3
- package/lib/environment.mjs +2 -1
- package/lib/environments.mjs +67 -41
- package/lib/events.mjs +318 -0
- package/lib/facts.mjs +170 -0
- package/lib/fileSource.mjs +540 -0
- package/lib/files.mjs +47 -2
- package/lib/gitHost.mjs +39 -1
- package/lib/goalCommands.mjs +12 -80
- package/lib/handover.mjs +21 -16
- package/lib/harnessOffers.mjs +140 -15
- package/lib/herdr.mjs +100 -15
- package/lib/herdrAppCall.mjs +19 -0
- package/lib/herdrCore.mjs +59 -0
- package/lib/herdrRuns.mjs +1126 -0
- package/lib/hookDialects.mjs +235 -50
- package/lib/identityLink.mjs +81 -0
- package/lib/inference.mjs +31 -2
- package/lib/jamAccess.mjs +82 -0
- package/lib/{projectBoard.mjs → jamBoard.mjs} +5 -4
- package/lib/{projectGit.mjs → jamGit.mjs} +53 -15
- package/lib/jamKey.mjs +274 -0
- package/lib/{projectPieces.mjs → jamPieces.mjs} +35 -29
- package/lib/{projectSettings.mjs → jamSettings.mjs} +12 -22
- package/lib/jamStore.mjs +973 -0
- package/lib/jamUpgrade.mjs +112 -0
- package/lib/jams.mjs +3079 -0
- package/lib/kanban.mjs +13 -7
- package/lib/landed.mjs +5 -1
- package/lib/library.mjs +41 -22
- package/lib/limits.mjs +91 -0
- package/lib/lineDiff.mjs +97 -0
- package/lib/lineup.mjs +18 -13
- package/lib/link.mjs +584 -0
- package/lib/localStack.mjs +75 -16
- package/lib/localmodels.mjs +58 -78
- package/lib/loopBackstop.mjs +2 -1
- package/lib/machine.mjs +544 -0
- package/lib/machineLink.mjs +446 -0
- package/lib/machineRoutes.mjs +68 -19
- package/lib/machineRuns.mjs +85 -4
- package/lib/machineSeal.mjs +6 -31
- package/lib/manager.mjs +134 -12
- package/lib/mcp-stdio.mjs +492 -215
- package/lib/mcpRelay.mjs +34 -35
- package/lib/members.json +2 -2
- package/lib/modelRoute.mjs +162 -0
- package/lib/nativeHost.mjs +81 -90
- package/lib/nativeSenses.mjs +258 -0
- package/lib/nerves.mjs +523 -0
- package/lib/network.mjs +117 -278
- package/lib/networkPlaces.mjs +578 -0
- package/lib/nextStep.mjs +95 -0
- package/lib/notify.mjs +2 -2
- package/lib/nudge.mjs +116 -10
- package/lib/onboard.mjs +6 -6
- package/lib/originals.mjs +216 -0
- package/lib/outsideEvents.mjs +383 -0
- package/lib/outsideRuns.mjs +230 -0
- package/lib/ownMachines.mjs +674 -256
- package/lib/pain.mjs +215 -0
- package/lib/pairing.mjs +91 -11
- package/lib/paths.mjs +42 -3
- package/lib/peerProcess.mjs +21 -7
- package/lib/peopleLink.mjs +268 -0
- package/lib/personNotices.mjs +3 -2
- package/lib/phones.mjs +252 -542
- package/lib/placeCards.mjs +282 -0
- package/lib/placeChecks.mjs +95 -0
- package/lib/placeCommands.mjs +8 -17
- package/lib/placeRequests.mjs +152 -0
- package/lib/placeStore.mjs +295 -0
- package/lib/placeTool.d.ts +12 -0
- package/lib/placeTool.js +40 -0
- package/lib/places.mjs +63 -14
- package/lib/plans.mjs +53 -8
- package/lib/presence.mjs +270 -0
- package/lib/privateNetwork.d.ts +2 -0
- package/lib/privateNetwork.js +93 -0
- package/lib/proposals.mjs +300 -0
- package/lib/publicFetch.d.ts +32 -0
- package/lib/publicFetch.js +248 -0
- package/lib/reach.mjs +128 -0
- package/lib/rebuildable.mjs +72 -0
- package/lib/recall.mjs +216 -0
- package/lib/record.mjs +13 -0
- package/lib/reflexes.mjs +392 -0
- package/lib/relayLimits.mjs +31 -2
- package/lib/releaseNotice.mjs +198 -0
- package/lib/removeHarness.mjs +15 -4
- package/lib/repoLinks.mjs +204 -35
- package/lib/runAuthority.mjs +102 -39
- package/lib/runBrief.mjs +93 -40
- package/lib/runRequests.mjs +52 -14
- package/lib/runUsage.mjs +31 -0
- package/lib/runWorker.mjs +74 -25
- package/lib/runner.mjs +289 -45
- package/lib/runtime-install.mjs +37 -8
- package/lib/schedules.mjs +171 -47
- package/lib/screenWatches.mjs +221 -0
- package/lib/sealed.mjs +12 -30
- package/lib/sealedThreads.mjs +198 -392
- package/lib/secretStore.mjs +178 -0
- package/lib/secrets.mjs +11 -0
- package/lib/seen.mjs +3 -9
- package/lib/selfUpdate.mjs +51 -15
- package/lib/senseCall.mjs +1514 -0
- package/lib/senseHook.mjs +114 -0
- package/lib/senseTools.mjs +1298 -0
- package/lib/sessionBriefs.mjs +87 -0
- package/lib/sessionControl.mjs +63 -13
- package/lib/sessionFiles.mjs +85 -0
- package/lib/setupChoices.mjs +12 -3
- package/lib/setupMode.mjs +70 -25
- package/lib/sharedKeys.mjs +166 -0
- package/lib/sleep.mjs +396 -0
- package/lib/sources.mjs +306 -0
- package/lib/speech.mjs +166 -411
- package/lib/spoken.mjs +210 -0
- package/lib/steerHook.mjs +3 -1
- package/lib/steerQueue.mjs +40 -11
- package/lib/store.mjs +323 -130
- package/lib/stuck.mjs +85 -7
- package/lib/swarm.mjs +157 -49
- package/lib/swarmDevices.mjs +25 -85
- package/lib/swarmMemory.mjs +93 -9
- package/lib/t3.mjs +73 -3
- package/lib/taskCommands.mjs +51 -60
- package/lib/taskRooms.mjs +30 -4
- package/lib/taskRules.json +29 -0
- package/lib/taskRules.mjs +21 -0
- package/lib/taskRuns.mjs +74 -11
- package/lib/team.mjs +2 -1
- package/lib/threadActions.mjs +37 -9
- package/lib/threadAuthority.mjs +4 -4
- package/lib/threadBriefs.mjs +173 -43
- package/lib/threadNotes.mjs +320 -0
- package/lib/threadRecord.mjs +491 -0
- package/lib/threadRuns.mjs +216 -108
- package/lib/threadView.mjs +27 -30
- package/lib/threadWatches.mjs +1962 -0
- package/lib/timeSense.mjs +839 -0
- package/lib/tripwires.mjs +454 -0
- package/lib/ui.mjs +1 -1
- package/lib/vault.mjs +560 -45
- package/lib/vaultCommands.mjs +5 -3
- package/lib/vaultPeers.mjs +165 -0
- package/lib/vaultTools.d.ts +4 -1
- package/lib/vaultTools.js +22 -1
- package/lib/verdicts.mjs +12 -26
- package/lib/versions.mjs +117 -0
- package/lib/waitTool.mjs +278 -0
- package/lib/wakePicture.mjs +268 -0
- package/lib/wakeQueue.mjs +108 -0
- package/lib/watchResponses.mjs +533 -0
- package/lib/watches.mjs +290 -145
- package/lib/windowAsks.mjs +80 -17
- package/lib/worktrees.mjs +159 -9
- package/npm-shrinkwrap.json +138 -631
- package/package.json +7 -6
- package/release.json +212 -130
- package/lib/callSessions.mjs +0 -51
- package/lib/directLink.mjs +0 -349
- package/lib/peopleBoard.mjs +0 -131
- package/lib/projects.mjs +0 -2917
- package/lib/roomChannels.mjs +0 -667
|
@@ -0,0 +1,1514 @@
|
|
|
1
|
+
import { execFileSync } from "node:child_process";
|
|
2
|
+
import crypto from "node:crypto";
|
|
3
|
+
import fs from "node:fs";
|
|
4
|
+
import path from "node:path";
|
|
5
|
+
import { harnessHome } from "./paths.mjs";
|
|
6
|
+
import { nameOf } from "./members.mjs";
|
|
7
|
+
import {
|
|
8
|
+
PARENT,
|
|
9
|
+
SENSE,
|
|
10
|
+
putSteer,
|
|
11
|
+
senseText,
|
|
12
|
+
takeSteers,
|
|
13
|
+
} from "./steerQueue.mjs";
|
|
14
|
+
import { LARGEST_BYTES, blobId, createVersions } from "./versions.mjs";
|
|
15
|
+
import { diffOf } from "./lineDiff.mjs";
|
|
16
|
+
import { outsideHeldRoot } from "./outsideRuns.mjs";
|
|
17
|
+
import {
|
|
18
|
+
awakeBetween,
|
|
19
|
+
beforeLong,
|
|
20
|
+
busyBetween,
|
|
21
|
+
endLong,
|
|
22
|
+
noteCall,
|
|
23
|
+
notePending,
|
|
24
|
+
noteRun,
|
|
25
|
+
noteTook,
|
|
26
|
+
shapeOf,
|
|
27
|
+
staleResult,
|
|
28
|
+
tookLine,
|
|
29
|
+
} from "./timeSense.mjs";
|
|
30
|
+
|
|
31
|
+
// The senses at a tool call (docs/senses-plan.md row 27, S4.2 and S4.3): what an agent read, kept with a fingerprint of
|
|
32
|
+
// the content, and the tripwire on what it writes. Every route into an agent calls here: each agent's hook before and
|
|
33
|
+
// after a tool call (senseHook.mjs), the OpenCode plugin and the pi extension in their own process. The daemon
|
|
34
|
+
// (tripwires.mjs) follows the folders, notices a change to something a session read, and leaves a trip here.
|
|
35
|
+
//
|
|
36
|
+
// The rules are the owner's (November 13). A change to a file the agent read is told at its next step: who changed it,
|
|
37
|
+
// with a small diff. A write is held only when it would destroy the changed part or replace the whole file, and any
|
|
38
|
+
// write over the user's change is held ("users edits should hold user is the director here right"). A hold clears by
|
|
39
|
+
// reading ("hold could be cleared by reading"): the diff handed over with the hold or the step's note, or the agent's own
|
|
40
|
+
// read of the file. A read is never held (S0.5: a hold that refused the read stopped the model). A version another's
|
|
41
|
+
// write replaces is kept 30 days and can be put back ("im fine with overwritten versions being kept"). A shell command
|
|
42
|
+
// is judged after it ran, since what it writes is known only then. Never tripped: the agent's own changes (its
|
|
43
|
+
// subagents share its session), a change made while its own command ran (its formatter), lockfiles and build output.
|
|
44
|
+
//
|
|
45
|
+
// Kept on the computer, one small file for each thing a session read and each trip, so two hooks running at once never
|
|
46
|
+
// write the same file:
|
|
47
|
+
// senses/reads/<session>/session.json { agent, cwd }
|
|
48
|
+
// senses/reads/<session>/step its time: when the session's last tool call ended
|
|
49
|
+
// senses/reads/<session>/<key>.json { file, blob, at, size, mtimeMs }, a file as the session last read or wrote it
|
|
50
|
+
// senses/trips/<session>/<key>.json a change to that file the session has not seen (tripwires.mjs)
|
|
51
|
+
// The trips folder is empty whenever nothing waits, so the hook before a call starts Node only then (hookDialects.mjs).
|
|
52
|
+
|
|
53
|
+
const ID = /^[A-Za-z0-9._:-]{1,128}$/;
|
|
54
|
+
// A shell command names at most this many files that are read.
|
|
55
|
+
const MOST_NAMED = 40;
|
|
56
|
+
|
|
57
|
+
export const sensesRoot = (home = harnessHome) => path.join(home, "senses");
|
|
58
|
+
export const readsRoot = (home = harnessHome) =>
|
|
59
|
+
path.join(sensesRoot(home), "reads");
|
|
60
|
+
// When each agent process last started a tool call: its hook before every call touches `calls/<its pid>` from the shell,
|
|
61
|
+
// with no Node start (hookDialects.mjs), so the hook after knows how long the call ran.
|
|
62
|
+
export const callsRoot = (home = harnessHome) =>
|
|
63
|
+
path.join(sensesRoot(home), "calls");
|
|
64
|
+
export const tripsRoot = (home = harnessHome) =>
|
|
65
|
+
path.join(sensesRoot(home), "trips");
|
|
66
|
+
export const versionsOf = (home = harnessHome) =>
|
|
67
|
+
createVersions({ root: path.join(sensesRoot(home), "versions") });
|
|
68
|
+
|
|
69
|
+
/** A file's key in a session's record. */
|
|
70
|
+
export const keyOf = (file) =>
|
|
71
|
+
crypto.createHash("sha1").update(file).digest("hex").slice(0, 20);
|
|
72
|
+
|
|
73
|
+
const readJson = (file) => {
|
|
74
|
+
try {
|
|
75
|
+
return JSON.parse(fs.readFileSync(file, "utf8"));
|
|
76
|
+
} catch {
|
|
77
|
+
return null;
|
|
78
|
+
}
|
|
79
|
+
};
|
|
80
|
+
const writeJson = (file, value) => {
|
|
81
|
+
fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 });
|
|
82
|
+
const part = `${file}.${process.pid}.part`;
|
|
83
|
+
fs.writeFileSync(part, JSON.stringify(value), { mode: 0o600 });
|
|
84
|
+
fs.renameSync(part, file);
|
|
85
|
+
};
|
|
86
|
+
const listed = (folder) => {
|
|
87
|
+
try {
|
|
88
|
+
return fs
|
|
89
|
+
.readdirSync(folder)
|
|
90
|
+
.filter((name) => /^[0-9a-f]{20}\.json$/.test(name));
|
|
91
|
+
} catch {
|
|
92
|
+
return [];
|
|
93
|
+
}
|
|
94
|
+
};
|
|
95
|
+
|
|
96
|
+
/** A file's content id now, or null when it is gone, not a file, or too large to compare. */
|
|
97
|
+
export function contentOf(file) {
|
|
98
|
+
try {
|
|
99
|
+
const stat = fs.statSync(file);
|
|
100
|
+
if (!stat.isFile() || stat.size > LARGEST_BYTES) return null;
|
|
101
|
+
return blobId(fs.readFileSync(file));
|
|
102
|
+
} catch {
|
|
103
|
+
return null;
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
// --- the record of what a session read ---
|
|
108
|
+
|
|
109
|
+
/** What a session read, by file: `{ file, blob, at, size, mtimeMs }`. */
|
|
110
|
+
export function readsOf(session, home = harnessHome) {
|
|
111
|
+
if (!ID.test(String(session))) return [];
|
|
112
|
+
const folder = path.join(readsRoot(home), session);
|
|
113
|
+
return listed(folder)
|
|
114
|
+
.map((name) => readJson(path.join(folder, name)))
|
|
115
|
+
.filter(Boolean);
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
export const sessionOf = (session, home = harnessHome) =>
|
|
119
|
+
ID.test(String(session))
|
|
120
|
+
? readJson(path.join(readsRoot(home), session, "session.json"))
|
|
121
|
+
: null;
|
|
122
|
+
|
|
123
|
+
/**
|
|
124
|
+
* Notes that a session has a file as it is now (read it, or wrote it), keeping that version. `wrote` marks the session's
|
|
125
|
+
* own write, after which a formatter may change the file again (tripwires.mjs).
|
|
126
|
+
*/
|
|
127
|
+
export function noteSeen(
|
|
128
|
+
session,
|
|
129
|
+
file,
|
|
130
|
+
home = harnessHome,
|
|
131
|
+
{ wrote = false } = {}
|
|
132
|
+
) {
|
|
133
|
+
const versions = versionsOf(home);
|
|
134
|
+
const blob = versions.keep(file);
|
|
135
|
+
if (!blob) return null;
|
|
136
|
+
const stat = fs.statSync(file, { throwIfNoEntry: false });
|
|
137
|
+
const entry = path.join(readsRoot(home), session, `${keyOf(file)}.json`);
|
|
138
|
+
// Reading back what it wrote leaves it the session's own write.
|
|
139
|
+
const before = wrote ? null : readJson(entry);
|
|
140
|
+
if (before?.wrote && before.blob === blob) wrote = true;
|
|
141
|
+
writeJson(entry, {
|
|
142
|
+
file,
|
|
143
|
+
blob,
|
|
144
|
+
at: new Date().toISOString(),
|
|
145
|
+
size: stat?.size ?? null,
|
|
146
|
+
mtimeMs: stat?.mtimeMs ?? null,
|
|
147
|
+
...(wrote ? { wrote: true } : {}),
|
|
148
|
+
});
|
|
149
|
+
return blob;
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
// Whether a file the session has may have changed since: its size or time moved (its content is read only then).
|
|
153
|
+
function movedSince(seen) {
|
|
154
|
+
const stat = fs.statSync(seen.file, { throwIfNoEntry: false });
|
|
155
|
+
if (!stat) return true;
|
|
156
|
+
if (stat.size === seen.size && stat.mtimeMs === seen.mtimeMs) return false;
|
|
157
|
+
return contentOf(seen.file) !== seen.blob;
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
/** Notes a session's place the first time it is seen. */
|
|
161
|
+
function notePlace(session, { agent, cwd, transcript = null }, home) {
|
|
162
|
+
const file = path.join(readsRoot(home), session, "session.json");
|
|
163
|
+
const kept = fs.existsSync(file) ? readJson(file) : null;
|
|
164
|
+
// The agent's own record of the session, where the daemon reads how full its context is (pain.mjs).
|
|
165
|
+
if (kept && (!transcript || kept.transcript === transcript)) return;
|
|
166
|
+
writeJson(file, {
|
|
167
|
+
...(kept ?? { agent, cwd, at: new Date().toISOString() }),
|
|
168
|
+
...(transcript ? { transcript: String(transcript) } : {}),
|
|
169
|
+
});
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
// A call's own id, as its agent names it to both its hooks: two calls at once each keep their own start (Phase T.1).
|
|
173
|
+
const CALL_ID = /^[A-Za-z0-9_.:-]{1,128}$/;
|
|
174
|
+
const callIdOf = (callId) =>
|
|
175
|
+
CALL_ID.test(String(callId ?? "")) ? String(callId) : null;
|
|
176
|
+
|
|
177
|
+
// A tool call starting, noted by the hook before it when that runs in Node (an in-process hook, or one with a trip or a
|
|
178
|
+
// hold to judge): under the session, and under the call's own id when it has one.
|
|
179
|
+
function callStarted(session, home, callId = null) {
|
|
180
|
+
const folder = path.join(readsRoot(home), session);
|
|
181
|
+
if (!fs.existsSync(folder)) return;
|
|
182
|
+
const now = new Date();
|
|
183
|
+
for (const name of ["call", ...(callId ? [`call.${callId}`] : [])])
|
|
184
|
+
try {
|
|
185
|
+
const file = path.join(folder, name);
|
|
186
|
+
fs.writeFileSync(file, "");
|
|
187
|
+
fs.utimesSync(file, now, now);
|
|
188
|
+
} catch {}
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
// When this call started: its own start, noted by its agent process's shell under its id (hookDialects.mjs) or by an
|
|
192
|
+
// in-process hook; else the latest start noted after the previous call ended; null when none was noted. Its own start
|
|
193
|
+
// is taken, so the folder keeps only calls still running.
|
|
194
|
+
function startOf(session, previousStep, home, agentPid, callId = null) {
|
|
195
|
+
const pid = /^\d+$/.test(String(agentPid ?? "")) ? String(agentPid) : null;
|
|
196
|
+
if (callId) {
|
|
197
|
+
const own = [
|
|
198
|
+
...(pid ? [path.join(callsRoot(home), `${pid}.${callId}`)] : []),
|
|
199
|
+
path.join(readsRoot(home), session, `call.${callId}`),
|
|
200
|
+
];
|
|
201
|
+
for (const file of own) {
|
|
202
|
+
const started = fs.statSync(file, { throwIfNoEntry: false })?.mtimeMs;
|
|
203
|
+
if (started == null) continue;
|
|
204
|
+
fs.rmSync(file, { force: true });
|
|
205
|
+
return started;
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
const files = [path.join(readsRoot(home), session, "call")];
|
|
209
|
+
if (pid) files.push(path.join(callsRoot(home), pid));
|
|
210
|
+
const starts = files
|
|
211
|
+
.map((file) => fs.statSync(file, { throwIfNoEntry: false })?.mtimeMs ?? 0)
|
|
212
|
+
.filter((started) => started >= previousStep);
|
|
213
|
+
return starts.length ? Math.max(...starts) : null;
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
// When the session's previous tool call ended, and now this one has.
|
|
217
|
+
function stepped(session, home) {
|
|
218
|
+
const file = path.join(readsRoot(home), session, "step");
|
|
219
|
+
let before = 0;
|
|
220
|
+
try {
|
|
221
|
+
before = fs.statSync(file).mtimeMs;
|
|
222
|
+
} catch {}
|
|
223
|
+
try {
|
|
224
|
+
fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 });
|
|
225
|
+
fs.writeFileSync(file, "");
|
|
226
|
+
const now = new Date();
|
|
227
|
+
fs.utimesSync(file, now, now);
|
|
228
|
+
} catch {}
|
|
229
|
+
return before;
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
// --- trips ---
|
|
233
|
+
|
|
234
|
+
// --- copies before a risky write (docs/senses-plan.md S5.2) ---
|
|
235
|
+
|
|
236
|
+
// Kept before the call, told after it only if the file did change or go: the agent learns where its old version is.
|
|
237
|
+
function saveBefore(session, call, home) {
|
|
238
|
+
const had = new Map(
|
|
239
|
+
readsOf(session, home).map((seen) => [seen.file, seen.blob])
|
|
240
|
+
);
|
|
241
|
+
const kept = call.writes
|
|
242
|
+
.filter((write) => write.whole && fs.existsSync(write.file))
|
|
243
|
+
// Risky: removing a file, or replacing one whose content this session never had (its read is kept already).
|
|
244
|
+
.filter(
|
|
245
|
+
(write) => write.removed || had.get(write.file) !== contentOf(write.file)
|
|
246
|
+
)
|
|
247
|
+
.map((write) => ({
|
|
248
|
+
file: write.file,
|
|
249
|
+
id: versionsOf(home).keep(write.file),
|
|
250
|
+
}))
|
|
251
|
+
.filter((each) => each.id);
|
|
252
|
+
if (kept.length) writeJson(savedFile(session, home), kept);
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
// Beside the session's record, not in it: the hook before a session's first call must not make its folder before its
|
|
256
|
+
// record is written, or the daemon finds the folder with no record to follow (tripwires.mjs join).
|
|
257
|
+
const savedFile = (session, home) =>
|
|
258
|
+
path.join(sensesRoot(home), "saved", `${session}.json`);
|
|
259
|
+
|
|
260
|
+
function savedLine(session, cwd, home) {
|
|
261
|
+
const saved = takeJson(savedFile(session, home)) ?? [];
|
|
262
|
+
const lost = saved.filter((each) => contentOf(each.file) !== each.id);
|
|
263
|
+
if (!lost.length) return "";
|
|
264
|
+
return lost
|
|
265
|
+
.map(
|
|
266
|
+
(each) =>
|
|
267
|
+
`Harness kept ${relTo(cwd, each.file)} as it was before this call ${fs.existsSync(each.file) ? "replaced" : "removed"} it: ${restoreLine(relTo(cwd, each.file), each.id)}`
|
|
268
|
+
)
|
|
269
|
+
.join("\n");
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
// --- a reflex's hold (docs/senses-plan.md S5.1): kept beside the session's trips, so the shell test before each call
|
|
273
|
+
// wakes for it too ---
|
|
274
|
+
|
|
275
|
+
const holdFile = (session, home) =>
|
|
276
|
+
path.join(tripsRoot(home), String(session), "reflex-hold.json");
|
|
277
|
+
|
|
278
|
+
/** The reflex holding a session's calls, `{ id, why, at }`, or null. */
|
|
279
|
+
export function holdOf(session, home = harnessHome) {
|
|
280
|
+
if (!ID.test(String(session ?? ""))) return null;
|
|
281
|
+
return readJson(holdFile(session, home));
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
export function putHold(session, hold, home = harnessHome) {
|
|
285
|
+
if (!ID.test(String(session ?? ""))) return false;
|
|
286
|
+
writeJson(holdFile(session, home), hold);
|
|
287
|
+
return true;
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
export function dropHold(session, home = harnessHome) {
|
|
291
|
+
if (!ID.test(String(session ?? ""))) return;
|
|
292
|
+
const folder = path.join(tripsRoot(home), String(session));
|
|
293
|
+
fs.rmSync(holdFile(session, home), { force: true });
|
|
294
|
+
for (const empty of [folder, tripsRoot(home)])
|
|
295
|
+
try {
|
|
296
|
+
fs.rmdirSync(empty);
|
|
297
|
+
} catch {}
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
/** The changes a session has not seen yet, each `{ file, rel, read, now, by, user, diff, complete, ranges, at, told }`. */
|
|
301
|
+
export function tripsOf(session, home = harnessHome) {
|
|
302
|
+
if (!ID.test(String(session))) return [];
|
|
303
|
+
const folder = path.join(tripsRoot(home), session);
|
|
304
|
+
return listed(folder)
|
|
305
|
+
.map((name) => readJson(path.join(folder, name)))
|
|
306
|
+
.filter(Boolean);
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
export function putTrip(session, trip, home = harnessHome) {
|
|
310
|
+
writeJson(
|
|
311
|
+
path.join(tripsRoot(home), session, `${keyOf(trip.file)}.json`),
|
|
312
|
+
trip
|
|
313
|
+
);
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
export function dropTrip(session, file, home = harnessHome) {
|
|
317
|
+
const folder = path.join(tripsRoot(home), session);
|
|
318
|
+
fs.rmSync(path.join(folder, `${keyOf(file)}.json`), { force: true });
|
|
319
|
+
// Empty folders go, so the shell test before each call finds nothing waiting.
|
|
320
|
+
for (const empty of [folder, tripsRoot(home)])
|
|
321
|
+
try {
|
|
322
|
+
fs.rmdirSync(empty);
|
|
323
|
+
} catch {}
|
|
324
|
+
}
|
|
325
|
+
|
|
326
|
+
/** The step's note about a trip was taken: its diff has been read, so a complete one clears the hold. */
|
|
327
|
+
export function tripTold(session, file, home = harnessHome) {
|
|
328
|
+
const trip = tripsOf(session, home).find((each) => each.file === file);
|
|
329
|
+
if (trip?.complete) putTrip(session, { ...trip, told: true }, home);
|
|
330
|
+
}
|
|
331
|
+
|
|
332
|
+
// --- a tool call, in any agent's words ---
|
|
333
|
+
|
|
334
|
+
const SHELL =
|
|
335
|
+
/^(bash|shell|run_shell_command|run_terminal_cmd|exec_command|local_shell|terminal|command)$/i;
|
|
336
|
+
const READS = /^(read|read_file|view|view_file|notebookread|open_file|cat)$/i;
|
|
337
|
+
const WHOLE =
|
|
338
|
+
/^(write|write_file|create|create_file|notebookedit|write_to_file)$/i;
|
|
339
|
+
const PART =
|
|
340
|
+
/^(edit|multiedit|str_replace|str_replace_editor|edit_file|replace|search_replace|apply_patch|patch)$/i;
|
|
341
|
+
|
|
342
|
+
const PATCH_FILE = /^\*\*\* (Update|Add|Delete) File: (.+)$/gm;
|
|
343
|
+
const REDIRECT = /(?:^|[\s;&|])(>>?|tee(?:\s+-a)?)\s+(["']?)([^\s"'|;&<>]+)\2/g;
|
|
344
|
+
const REMOVES = /(^|[;&|(]\s*)(sudo\s+)?rm\s/;
|
|
345
|
+
const SED_INPLACE = /\bsed\s+(?:-[a-zA-Z]*i[a-zA-Z]*|--in-place)\b/;
|
|
346
|
+
const PATH_WORD =
|
|
347
|
+
/(?:\.{0,2}\/)?[\w@+-][\w@+.-]*(?:\/[\w@+.-]+)*\.[\w]{1,8}\b|(?:\.{0,2}\/)?[\w@+-][\w@+.-]*(?:\/[\w@+.-]+)+/g;
|
|
348
|
+
|
|
349
|
+
const objectOf = (value) => {
|
|
350
|
+
if (value && typeof value === "object") return value;
|
|
351
|
+
if (typeof value !== "string") return {};
|
|
352
|
+
try {
|
|
353
|
+
const parsed = JSON.parse(value);
|
|
354
|
+
return parsed && typeof parsed === "object" ? parsed : {};
|
|
355
|
+
} catch {
|
|
356
|
+
return {};
|
|
357
|
+
}
|
|
358
|
+
};
|
|
359
|
+
const pathIn = (input) =>
|
|
360
|
+
input.file_path ??
|
|
361
|
+
input.filePath ??
|
|
362
|
+
input.notebook_path ??
|
|
363
|
+
input.target_file ??
|
|
364
|
+
input.path ??
|
|
365
|
+
input.absolute_path ??
|
|
366
|
+
null;
|
|
367
|
+
const commandIn = (input) => {
|
|
368
|
+
const command = input.command ?? input.cmd ?? null;
|
|
369
|
+
return Array.isArray(command) ? command.join(" ") : command;
|
|
370
|
+
};
|
|
371
|
+
|
|
372
|
+
/**
|
|
373
|
+
* A file as the computer names it, its links followed: the daemon follows a folder by its real path (macOS's /tmp is
|
|
374
|
+
* /private/tmp), so a file an agent named through a link is the same file. One not there yet: its folder's real path.
|
|
375
|
+
*/
|
|
376
|
+
function realOf(file) {
|
|
377
|
+
try {
|
|
378
|
+
return fs.realpathSync(file);
|
|
379
|
+
} catch {
|
|
380
|
+
try {
|
|
381
|
+
return path.join(
|
|
382
|
+
fs.realpathSync(path.dirname(file)),
|
|
383
|
+
path.basename(file)
|
|
384
|
+
);
|
|
385
|
+
} catch {
|
|
386
|
+
return file;
|
|
387
|
+
}
|
|
388
|
+
}
|
|
389
|
+
}
|
|
390
|
+
|
|
391
|
+
/**
|
|
392
|
+
* What a tool call does to files, whatever the agent named things: `{ shell, command, reads: [file], writes:
|
|
393
|
+
* [{ file, whole, old }] }`, paths made absolute against `cwd`. `old` is the text a part write replaces, when it says.
|
|
394
|
+
*/
|
|
395
|
+
export function callOf(tool, rawInput, cwd) {
|
|
396
|
+
const input = objectOf(rawInput);
|
|
397
|
+
const name = String(tool ?? "");
|
|
398
|
+
const at = (file) => realOf(path.resolve(cwd || process.cwd(), String(file)));
|
|
399
|
+
const call = { shell: false, command: null, reads: [], writes: [] };
|
|
400
|
+
const named = pathIn(input);
|
|
401
|
+
if (READS.test(name) && named) call.reads.push(at(named));
|
|
402
|
+
else if (WHOLE.test(name) && named)
|
|
403
|
+
call.writes.push({ file: at(named), whole: true });
|
|
404
|
+
else if (PART.test(name)) {
|
|
405
|
+
// Codex hands its patch as `command`; others as `patch`, `input`, or the whole argument.
|
|
406
|
+
const patch =
|
|
407
|
+
input.patch ??
|
|
408
|
+
input.input ??
|
|
409
|
+
input.command ??
|
|
410
|
+
(typeof rawInput === "string" ? rawInput : null);
|
|
411
|
+
if (typeof patch === "string" && patch.includes("*** ")) {
|
|
412
|
+
for (const match of patch.matchAll(PATCH_FILE))
|
|
413
|
+
call.writes.push({
|
|
414
|
+
file: at(match[2].trim()),
|
|
415
|
+
whole: match[1] !== "Update",
|
|
416
|
+
old: removedOf(patch, match[2].trim()),
|
|
417
|
+
});
|
|
418
|
+
} else if (named) {
|
|
419
|
+
const edits = Array.isArray(input.edits) ? input.edits : [input];
|
|
420
|
+
call.writes.push({
|
|
421
|
+
file: at(named),
|
|
422
|
+
whole: false,
|
|
423
|
+
old: edits
|
|
424
|
+
.map(
|
|
425
|
+
(edit) =>
|
|
426
|
+
edit.old_string ??
|
|
427
|
+
edit.oldString ??
|
|
428
|
+
edit.old_str ??
|
|
429
|
+
edit.oldText ??
|
|
430
|
+
null
|
|
431
|
+
)
|
|
432
|
+
.filter((text) => typeof text === "string" && text.length),
|
|
433
|
+
});
|
|
434
|
+
}
|
|
435
|
+
}
|
|
436
|
+
const command = commandIn(input);
|
|
437
|
+
if (
|
|
438
|
+
SHELL.test(name) ||
|
|
439
|
+
(command && !call.reads.length && !call.writes.length)
|
|
440
|
+
) {
|
|
441
|
+
call.shell = true;
|
|
442
|
+
call.command = typeof command === "string" ? command : null;
|
|
443
|
+
if (call.command) shellFiles(call, call.command, at);
|
|
444
|
+
}
|
|
445
|
+
return call;
|
|
446
|
+
}
|
|
447
|
+
|
|
448
|
+
// The lines a patch takes out of one file, as the text a part write replaces.
|
|
449
|
+
function removedOf(patch, file) {
|
|
450
|
+
const start = patch.indexOf(`File: ${file}`);
|
|
451
|
+
if (start < 0) return [];
|
|
452
|
+
const rest = patch.slice(start).split("\n").slice(1);
|
|
453
|
+
const end = rest.findIndex((line) => line.startsWith("*** "));
|
|
454
|
+
const lines = (end < 0 ? rest : rest.slice(0, end))
|
|
455
|
+
.filter((line) => line.startsWith("-") || line.startsWith(" "))
|
|
456
|
+
.map((line) => line.slice(1));
|
|
457
|
+
return lines.length ? [lines.join("\n")] : [];
|
|
458
|
+
}
|
|
459
|
+
|
|
460
|
+
// A shell command: files it names that are there are read; `>` and `tee` replace a whole file; `sed -i` and `>>` change
|
|
461
|
+
// one in part, where, is known only after.
|
|
462
|
+
function shellFiles(call, command, at) {
|
|
463
|
+
const written = new Set();
|
|
464
|
+
for (const match of command.matchAll(REDIRECT)) {
|
|
465
|
+
if (/^\/dev\//.test(match[3]) || /^&?\d$/.test(match[3])) continue;
|
|
466
|
+
const whole = match[1] === ">" || match[1] === "tee";
|
|
467
|
+
written.add(match[3]);
|
|
468
|
+
call.writes.push({
|
|
469
|
+
file: at(match[3]),
|
|
470
|
+
whole,
|
|
471
|
+
old: whole ? undefined : null,
|
|
472
|
+
});
|
|
473
|
+
}
|
|
474
|
+
const words = [...new Set(command.match(PATH_WORD) ?? [])].filter(
|
|
475
|
+
(word) => !written.has(word)
|
|
476
|
+
);
|
|
477
|
+
const sedInPlace = SED_INPLACE.test(command);
|
|
478
|
+
// `rm`: the files it names go whole.
|
|
479
|
+
const removes = REMOVES.test(command);
|
|
480
|
+
for (const word of words.slice(0, MOST_NAMED)) {
|
|
481
|
+
const file = at(word);
|
|
482
|
+
try {
|
|
483
|
+
if (!fs.statSync(file).isFile()) continue;
|
|
484
|
+
} catch {
|
|
485
|
+
continue;
|
|
486
|
+
}
|
|
487
|
+
if (removes) call.writes.push({ file, whole: true, removed: true });
|
|
488
|
+
else if (sedInPlace) call.writes.push({ file, whole: false, old: null });
|
|
489
|
+
else call.reads.push(file);
|
|
490
|
+
}
|
|
491
|
+
}
|
|
492
|
+
|
|
493
|
+
// --- whether a write is held ---
|
|
494
|
+
|
|
495
|
+
// The lines of `text` where `part` is, 1-based and inclusive; null when it is not there (the write fails on its own).
|
|
496
|
+
function linesOf(text, part) {
|
|
497
|
+
const index = text.indexOf(part);
|
|
498
|
+
if (index < 0) return null;
|
|
499
|
+
const from = text.slice(0, index).split("\n").length;
|
|
500
|
+
return { from, to: from + part.split("\n").length - 1 };
|
|
501
|
+
}
|
|
502
|
+
|
|
503
|
+
const meets = (a, b) => a.from <= b.to && b.from <= a.to;
|
|
504
|
+
|
|
505
|
+
/**
|
|
506
|
+
* Whether a write would undo a change the session has not seen: one that replaces the whole file, any write over the
|
|
507
|
+
* user's change, and a part write whose replaced text is in or next to the changed lines. A write whose place is not
|
|
508
|
+
* known before it runs (a shell command's `sed -i`) is judged after it.
|
|
509
|
+
*/
|
|
510
|
+
export function wouldUndo(trip, write) {
|
|
511
|
+
if (trip.told) return false;
|
|
512
|
+
if (write.whole || trip.user) return true;
|
|
513
|
+
if (!Array.isArray(write.old) || !write.old.length) return false;
|
|
514
|
+
let text = "";
|
|
515
|
+
try {
|
|
516
|
+
text = fs.readFileSync(trip.file, "utf8");
|
|
517
|
+
} catch {
|
|
518
|
+
return false;
|
|
519
|
+
}
|
|
520
|
+
return write.old.some((old) => {
|
|
521
|
+
const where = linesOf(text, old);
|
|
522
|
+
return where && trip.ranges.some((range) => meets(where, range));
|
|
523
|
+
});
|
|
524
|
+
}
|
|
525
|
+
|
|
526
|
+
/** What an agent reads when a write is held. */
|
|
527
|
+
export function holdText(trip) {
|
|
528
|
+
return [
|
|
529
|
+
`Harness held this write: ${trip.rel} changed after you read it, by ${trip.by}, and this write would replace that change.`,
|
|
530
|
+
trip.diff,
|
|
531
|
+
trip.complete
|
|
532
|
+
? "You have seen the change now: make the call again if it still fits, or read the file first."
|
|
533
|
+
: "More changed than is shown here: read the file again before you write it.",
|
|
534
|
+
].join("\n\n");
|
|
535
|
+
}
|
|
536
|
+
|
|
537
|
+
/** What an agent reads at its next step when a file it read changed. */
|
|
538
|
+
export function changedText(trip) {
|
|
539
|
+
return [
|
|
540
|
+
`${trip.rel} changed after you read it, by ${trip.by}:`,
|
|
541
|
+
trip.diff,
|
|
542
|
+
...(trip.complete
|
|
543
|
+
? []
|
|
544
|
+
: ["More changed than this: read it again before you write it."]),
|
|
545
|
+
].join("\n");
|
|
546
|
+
}
|
|
547
|
+
|
|
548
|
+
const restoreLine = (rel, id) =>
|
|
549
|
+
`It is kept: \`tryharness restore ${id.slice(0, 12)} ${rel}\` puts it back.`;
|
|
550
|
+
|
|
551
|
+
// --- the calls ---
|
|
552
|
+
|
|
553
|
+
// Whether what the session wrote took out or changed lines of the change it had not seen. A version not kept (too
|
|
554
|
+
// large, or binary) counts as taken out once the file differs.
|
|
555
|
+
function undid(trip, file, home) {
|
|
556
|
+
const changed = versionsOf(home).read(trip.now);
|
|
557
|
+
let written = null;
|
|
558
|
+
try {
|
|
559
|
+
written = fs.readFileSync(file, "utf8");
|
|
560
|
+
} catch {}
|
|
561
|
+
if (!changed || written == null) return true;
|
|
562
|
+
// The lines of the changed version the write did not keep, in that version's numbering, as trip.ranges are.
|
|
563
|
+
const lost = diffOf(written, changed.toString("utf8")).ranges;
|
|
564
|
+
return lost.some((range) => trip.ranges.some((each) => meets(range, each)));
|
|
565
|
+
}
|
|
566
|
+
|
|
567
|
+
// Takes back the note about a file waiting for the session's next step.
|
|
568
|
+
const unsay = (session, file, home) =>
|
|
569
|
+
takeSteers(String(session), PARENT, { event: "taken back" }, home, {
|
|
570
|
+
only: (item) => item.kind === SENSE && item.about?.trip === file,
|
|
571
|
+
});
|
|
572
|
+
|
|
573
|
+
/**
|
|
574
|
+
* Before a tool call: null, or `{ hold: text }` when the call would undo a change the session has not seen. Reads go
|
|
575
|
+
* through always. A held call has handed its diff over, so the same call made again goes through.
|
|
576
|
+
*/
|
|
577
|
+
// Commands known to send work off the computer: pushing, publishing, deploying, and posting to GitHub. Not a wall: a
|
|
578
|
+
// shell reaches the internet other ways.
|
|
579
|
+
const OUTWARD = [
|
|
580
|
+
/\bgit\s+push\b/,
|
|
581
|
+
/\b(npm|pnpm|yarn|bun)\s+publish\b/,
|
|
582
|
+
/\b(fly|flyctl)\s+deploy\b/,
|
|
583
|
+
/\bvercel\b[^\n]*(\bdeploy\b|--prod\b)/,
|
|
584
|
+
/\bgh\s+(pr|issue)\s+(create|comment|merge|close|edit)\b/,
|
|
585
|
+
/\bgh\s+release\s+create\b/,
|
|
586
|
+
];
|
|
587
|
+
|
|
588
|
+
/** Why a command waits: it sends work off the computer from a folder whose thread's turn began outside; else null. */
|
|
589
|
+
function outsideHold(cwd, command, home) {
|
|
590
|
+
if (!OUTWARD.some((pattern) => pattern.test(command))) return null;
|
|
591
|
+
const root = outsideHeldRoot(home);
|
|
592
|
+
let names = [];
|
|
593
|
+
try {
|
|
594
|
+
names = fs.readdirSync(root).filter((name) => name.endsWith(".json"));
|
|
595
|
+
} catch {
|
|
596
|
+
return null;
|
|
597
|
+
}
|
|
598
|
+
const here = path.resolve(String(cwd || "."));
|
|
599
|
+
for (const name of names) {
|
|
600
|
+
let held = null;
|
|
601
|
+
try {
|
|
602
|
+
held = JSON.parse(fs.readFileSync(path.join(root, name), "utf8"));
|
|
603
|
+
} catch {
|
|
604
|
+
continue;
|
|
605
|
+
}
|
|
606
|
+
const relative = path.relative(held?.folder ?? "", here);
|
|
607
|
+
if (!held?.folder || relative.startsWith("..") || path.isAbsolute(relative))
|
|
608
|
+
continue;
|
|
609
|
+
return `Not run: this thread's turn began with ${held.what}, which came from outside, so a command that sends work off this computer waits for the person until they write in the thread. Carry on with what stays here, and post in the thread what you would send.`;
|
|
610
|
+
}
|
|
611
|
+
return null;
|
|
612
|
+
}
|
|
613
|
+
|
|
614
|
+
export function beforeCall(
|
|
615
|
+
{ session, agent = null, cwd, tool, input, callId = null },
|
|
616
|
+
home = harnessHome
|
|
617
|
+
) {
|
|
618
|
+
if (!ID.test(String(session ?? ""))) return null;
|
|
619
|
+
callStarted(String(session), home, callIdOf(callId));
|
|
620
|
+
// A copy before a risky write (S5.2): a file this call replaces whole or removes is kept as it is now.
|
|
621
|
+
saveBefore(String(session), callOf(tool, input, cwd), home);
|
|
622
|
+
// A reflex holding the session (reflexes.mjs): every call but a read waits, with why.
|
|
623
|
+
const hold = holdOf(session, home);
|
|
624
|
+
if (hold) {
|
|
625
|
+
const asked = callOf(tool, input, cwd);
|
|
626
|
+
if (asked.shell || asked.writes.length)
|
|
627
|
+
return {
|
|
628
|
+
hold: `Harness is holding your calls: ${hold.why}. Reads still go through. It lets go by itself when that changes; to go on now, give a reason with look {release: "${hold.id}", reason}.`,
|
|
629
|
+
};
|
|
630
|
+
}
|
|
631
|
+
const trips = tripsOf(session, home);
|
|
632
|
+
const call = callOf(tool, input, cwd);
|
|
633
|
+
for (const write of trips.length ? call.writes : []) {
|
|
634
|
+
const trip = trips.find((each) => each.file === write.file);
|
|
635
|
+
if (!trip) continue;
|
|
636
|
+
const blob = contentOf(trip.file);
|
|
637
|
+
// Put back as the session read it: nothing to undo or tell.
|
|
638
|
+
if (blob === trip.read) {
|
|
639
|
+
dropTrip(session, trip.file, home);
|
|
640
|
+
unsay(session, trip.file, home);
|
|
641
|
+
continue;
|
|
642
|
+
}
|
|
643
|
+
if (!wouldUndo(trip, write)) continue;
|
|
644
|
+
if (trip.complete) putTrip(session, { ...trip, told: true }, home);
|
|
645
|
+
// The hold carries the diff, so the note about it waiting for the next step goes.
|
|
646
|
+
unsay(session, trip.file, home);
|
|
647
|
+
return { hold: holdText(trip) };
|
|
648
|
+
}
|
|
649
|
+
// What another agent left where this call is about to write or run (a mark, its intention): after the call is too
|
|
650
|
+
// late to change it, and nothing but a refusal reaches a model before its call runs. So one hold, cleared by being
|
|
651
|
+
// read: the same call made again goes through.
|
|
652
|
+
const marks = marksBefore(String(session), cwd, call, input, home);
|
|
653
|
+
if (marks.length)
|
|
654
|
+
return {
|
|
655
|
+
hold: `${marks.join("\n")}\nThis call was not run, so that you read this first. Make it again if it still stands.`,
|
|
656
|
+
};
|
|
657
|
+
if (!call.shell || !call.command) return null;
|
|
658
|
+
// A thread whose turn began with something from outside (outsideRuns.mjs, S7.5): a command known to send work off
|
|
659
|
+
// this computer, in its folder, waits for the person.
|
|
660
|
+
const outward = outsideHold(cwd, call.command, home);
|
|
661
|
+
if (outward) return { hold: outward };
|
|
662
|
+
// A commit or a push on a test or build that came before the session's changes (Phase T.4).
|
|
663
|
+
if (/\bgit\s+(commit|push)\b/.test(call.command)) {
|
|
664
|
+
const stale = staleResult(
|
|
665
|
+
{
|
|
666
|
+
session: String(session),
|
|
667
|
+
ran: readJson(sessionFile(String(session), "ran.json", home)) ?? [],
|
|
668
|
+
writes: readsOf(String(session), home).filter((seen) => seen.wrote),
|
|
669
|
+
},
|
|
670
|
+
home
|
|
671
|
+
);
|
|
672
|
+
if (stale) return stale;
|
|
673
|
+
}
|
|
674
|
+
// A command whose usual here is long: said before it runs, with what waits for the session (Phase T.3).
|
|
675
|
+
const waiting = takeSteers(String(session), PARENT, {}, home, {
|
|
676
|
+
keep: true,
|
|
677
|
+
only: [SENSE],
|
|
678
|
+
}).length;
|
|
679
|
+
return beforeLong(
|
|
680
|
+
{
|
|
681
|
+
session: String(session),
|
|
682
|
+
agent,
|
|
683
|
+
cwd,
|
|
684
|
+
command: call.command,
|
|
685
|
+
input: objectOf(input),
|
|
686
|
+
callId: callIdOf(callId),
|
|
687
|
+
notes: waiting ? () => notesAtStep(String(session), tool, home) : null,
|
|
688
|
+
},
|
|
689
|
+
home
|
|
690
|
+
);
|
|
691
|
+
}
|
|
692
|
+
|
|
693
|
+
/**
|
|
694
|
+
* After a tool call: notes what it read and wrote as the session's own, and returns what the agent should read beside
|
|
695
|
+
* its result ("" for nothing). A change seen while the session's own command ran is its own (its formatter, its build)
|
|
696
|
+
* and is taken back, note and all; a change seen before, which its command or edit then changed again, is said, with
|
|
697
|
+
* the kept version.
|
|
698
|
+
*/
|
|
699
|
+
export function afterCall(
|
|
700
|
+
{
|
|
701
|
+
session,
|
|
702
|
+
agent,
|
|
703
|
+
cwd,
|
|
704
|
+
tool,
|
|
705
|
+
input,
|
|
706
|
+
output = null,
|
|
707
|
+
failed = null,
|
|
708
|
+
agentPid = null,
|
|
709
|
+
callId = null,
|
|
710
|
+
transcript = null,
|
|
711
|
+
},
|
|
712
|
+
home = harnessHome
|
|
713
|
+
) {
|
|
714
|
+
if (!ID.test(String(session ?? ""))) return "";
|
|
715
|
+
notePlace(session, { agent, cwd, transcript }, home);
|
|
716
|
+
const previousStep = stepped(session, home);
|
|
717
|
+
const ownId = callIdOf(callId);
|
|
718
|
+
const started = startOf(session, previousStep, home, agentPid, ownId);
|
|
719
|
+
const call = callOf(tool, input, cwd);
|
|
720
|
+
const now = Date.now();
|
|
721
|
+
// How long the call took while the computer was awake (Phase T.1).
|
|
722
|
+
const ms = started ? awakeBetween(started, now, home) : null;
|
|
723
|
+
const said = [];
|
|
724
|
+
if (call.shell) {
|
|
725
|
+
noteCommand(session, started ?? previousStep, home);
|
|
726
|
+
if (call.command) {
|
|
727
|
+
const ok = outcomeOf(output, failed);
|
|
728
|
+
notePoll(session, agent, call.command, home);
|
|
729
|
+
noteRan(session, call.command, ok, home);
|
|
730
|
+
said.push(
|
|
731
|
+
timeOfCommand(
|
|
732
|
+
{
|
|
733
|
+
session,
|
|
734
|
+
agent,
|
|
735
|
+
cwd,
|
|
736
|
+
command: call.command,
|
|
737
|
+
input,
|
|
738
|
+
ok,
|
|
739
|
+
started,
|
|
740
|
+
ms,
|
|
741
|
+
now,
|
|
742
|
+
agentPid,
|
|
743
|
+
callId: ownId,
|
|
744
|
+
},
|
|
745
|
+
home
|
|
746
|
+
)
|
|
747
|
+
);
|
|
748
|
+
}
|
|
749
|
+
} else if (ms != null) said.push(tookLine({ ms, usual: null, busy: false }));
|
|
750
|
+
const takenBack = new Set();
|
|
751
|
+
const trips = new Map(
|
|
752
|
+
tripsOf(session, home).map((trip) => [trip.file, trip])
|
|
753
|
+
);
|
|
754
|
+
// A file the session reads for the first time is a shape recall looks up.
|
|
755
|
+
const firstReads = [];
|
|
756
|
+
for (const file of call.reads) {
|
|
757
|
+
if (!fs.existsSync(sessionFile(session, `${keyOf(file)}.json`, home)))
|
|
758
|
+
firstReads.push(file);
|
|
759
|
+
noteSeen(session, file, home);
|
|
760
|
+
if (trips.has(file)) dropTrip(session, file, home);
|
|
761
|
+
}
|
|
762
|
+
const touched = new Set(call.writes.map((write) => write.file));
|
|
763
|
+
// A command may change any file: each one the session read is looked at again.
|
|
764
|
+
if (call.shell)
|
|
765
|
+
for (const seen of readsOf(session, home))
|
|
766
|
+
if (movedSince(seen)) touched.add(seen.file);
|
|
767
|
+
for (const file of touched) {
|
|
768
|
+
const trip = trips.get(file);
|
|
769
|
+
const blob = contentOf(file);
|
|
770
|
+
// Made while its own command ran: its formatter, its build.
|
|
771
|
+
if (
|
|
772
|
+
trip &&
|
|
773
|
+
call.shell &&
|
|
774
|
+
(started == null || Date.parse(trip.at) >= started)
|
|
775
|
+
) {
|
|
776
|
+
takenBack.add(file);
|
|
777
|
+
dropTrip(session, file, home);
|
|
778
|
+
} else if (trip && blob !== trip.now && undid(trip, file, home)) {
|
|
779
|
+
said.push(
|
|
780
|
+
`You changed ${trip.rel} over ${trip.by}'s change, made after you read it. ${restoreLine(trip.rel, trip.now)}`
|
|
781
|
+
);
|
|
782
|
+
dropTrip(session, file, home);
|
|
783
|
+
}
|
|
784
|
+
if (blob) noteSeen(session, file, home, { wrote: true });
|
|
785
|
+
}
|
|
786
|
+
for (const file of takenBack) unsay(session, file, home);
|
|
787
|
+
if (agentPid) notePid(agentPid, session, home);
|
|
788
|
+
const near = [...call.reads, ...touched];
|
|
789
|
+
said.push(...company(session, agent, cwd, near, home));
|
|
790
|
+
said.push(...marksNear(session, cwd, near, input, home));
|
|
791
|
+
said.push(madeLine(session, home));
|
|
792
|
+
said.push(savedLine(session, cwd, home));
|
|
793
|
+
if (call.shell && call.command && STARTS.test(call.command))
|
|
794
|
+
said.push(leftRunning(started ?? previousStep, agentPid));
|
|
795
|
+
askRecall(
|
|
796
|
+
session,
|
|
797
|
+
{ agent, cwd, files: firstReads, shape: errorShapeOf(output) },
|
|
798
|
+
home
|
|
799
|
+
);
|
|
800
|
+
// The time, after a real gap or a long turn (Phase T.5).
|
|
801
|
+
said.push(...noteCall(session, { started, previousStep, ms, now }, home));
|
|
802
|
+
return said.filter(Boolean).join("\n");
|
|
803
|
+
}
|
|
804
|
+
|
|
805
|
+
// A shell command's time (Phase T.1 to T.3): kept in the table against its usual, said when it is worth saying. One
|
|
806
|
+
// sent to the background is timed when its processes end (the daemon looks), not when the call returns.
|
|
807
|
+
function timeOfCommand(
|
|
808
|
+
{
|
|
809
|
+
session,
|
|
810
|
+
agent,
|
|
811
|
+
cwd,
|
|
812
|
+
command,
|
|
813
|
+
input,
|
|
814
|
+
ok,
|
|
815
|
+
started,
|
|
816
|
+
ms,
|
|
817
|
+
now,
|
|
818
|
+
agentPid,
|
|
819
|
+
callId,
|
|
820
|
+
},
|
|
821
|
+
home
|
|
822
|
+
) {
|
|
823
|
+
endLong({ session, cwd, command, callId }, home);
|
|
824
|
+
if (started == null || ms == null) return "";
|
|
825
|
+
const shape = shapeOf(command);
|
|
826
|
+
const background =
|
|
827
|
+
objectOf(input).run_in_background === true || /&\s*$/.test(command.trim());
|
|
828
|
+
if (background) {
|
|
829
|
+
notePending(
|
|
830
|
+
{
|
|
831
|
+
session,
|
|
832
|
+
agent,
|
|
833
|
+
cwd,
|
|
834
|
+
command,
|
|
835
|
+
startedAt: started,
|
|
836
|
+
pids: startedSince(started, agentPid).map((each) => each.pid),
|
|
837
|
+
},
|
|
838
|
+
home
|
|
839
|
+
);
|
|
840
|
+
return "";
|
|
841
|
+
}
|
|
842
|
+
const busy = busyBetween(started, now, home);
|
|
843
|
+
const usual = noteRun({ cwd, shape, ms, ok, busy }, home);
|
|
844
|
+
noteTook({ session, agent, shape, ms, ok, usualMs: usual?.ms ?? null }, home);
|
|
845
|
+
return tookLine({ ms, usual, busy });
|
|
846
|
+
}
|
|
847
|
+
|
|
848
|
+
/**
|
|
849
|
+
* What Harness noticed for a session while it works (steerQueue.mjs SENSE), taken once, as the model reads it after a
|
|
850
|
+
* tool call; "" when nothing waits. A note about a changed file, once read, has handed its diff over (tripTold).
|
|
851
|
+
*/
|
|
852
|
+
export function notesAtStep(session, tool = null, home = harnessHome) {
|
|
853
|
+
if (!ID.test(String(session ?? ""))) return "";
|
|
854
|
+
const items = takeSteers(
|
|
855
|
+
String(session),
|
|
856
|
+
PARENT,
|
|
857
|
+
{ event: "step", tool: tool ?? null },
|
|
858
|
+
home,
|
|
859
|
+
{ only: [SENSE] }
|
|
860
|
+
);
|
|
861
|
+
for (const item of items)
|
|
862
|
+
if (item.about?.trip) tripTold(session, item.about.trip, home);
|
|
863
|
+
return items.length ? senseText(items) : "";
|
|
864
|
+
}
|
|
865
|
+
|
|
866
|
+
// --- the edge: what moved in the session's folder that it never read (docs/senses-plan.md S4.4) ---
|
|
867
|
+
|
|
868
|
+
// How many of a session's own commands are kept, and for how long: their output is not told back to it as the edge.
|
|
869
|
+
const COMMANDS_KEPT = 30;
|
|
870
|
+
const COMMAND_KEPT_MS = 24 * 3_600_000;
|
|
871
|
+
// The edge line names this many files and counts the rest.
|
|
872
|
+
const EDGE_NAMED = 4;
|
|
873
|
+
// Unread changes kept for one session until its next pause.
|
|
874
|
+
const ELSEWHERE_KEPT = 200;
|
|
875
|
+
|
|
876
|
+
const sessionFile = (session, name, home) =>
|
|
877
|
+
path.join(readsRoot(home), session, name);
|
|
878
|
+
|
|
879
|
+
// A shell command the session ran, as a time window: what changed in it is the command's, so not news to the session.
|
|
880
|
+
function noteCommand(session, from, home) {
|
|
881
|
+
const file = sessionFile(session, "commands.json", home);
|
|
882
|
+
const now = Date.now();
|
|
883
|
+
const kept = (readJson(file) ?? []).filter(
|
|
884
|
+
(window) => now - window.to < COMMAND_KEPT_MS
|
|
885
|
+
);
|
|
886
|
+
kept.push({ from: from || now, to: now });
|
|
887
|
+
writeJson(file, kept.slice(-COMMANDS_KEPT));
|
|
888
|
+
}
|
|
889
|
+
|
|
890
|
+
/**
|
|
891
|
+
* How loud what is outside the session's task is: "normal" (the edge line at each pause) or "quiet" (none). Pain and
|
|
892
|
+
* tripwires are never muted.
|
|
893
|
+
*/
|
|
894
|
+
export function volumeOf(session, home = harnessHome) {
|
|
895
|
+
if (!ID.test(String(session ?? ""))) return "normal";
|
|
896
|
+
return readJson(sessionFile(String(session), "volume.json", home))?.level ===
|
|
897
|
+
"quiet"
|
|
898
|
+
? "quiet"
|
|
899
|
+
: "normal";
|
|
900
|
+
}
|
|
901
|
+
|
|
902
|
+
export function setVolume(session, level, home = harnessHome) {
|
|
903
|
+
if (!ID.test(String(session ?? ""))) return false;
|
|
904
|
+
if (!["normal", "quiet"].includes(level)) return false;
|
|
905
|
+
writeJson(sessionFile(String(session), "volume.json", home), { level });
|
|
906
|
+
return true;
|
|
907
|
+
}
|
|
908
|
+
|
|
909
|
+
/**
|
|
910
|
+
* The daemon notes a change in the session's folder to a file the session never read: `{ rel, at, by }`, `by` the
|
|
911
|
+
* agent or run that made it when Harness knows, else null. Kept until the session's next pause, newest per file.
|
|
912
|
+
*/
|
|
913
|
+
export function noteElsewhere(session, change, home = harnessHome) {
|
|
914
|
+
if (!ID.test(String(session ?? ""))) return;
|
|
915
|
+
const file = sessionFile(String(session), "elsewhere.json", home);
|
|
916
|
+
const byFile = new Map(
|
|
917
|
+
(readJson(file) ?? []).map((each) => [each.rel, each])
|
|
918
|
+
);
|
|
919
|
+
byFile.delete(change.rel);
|
|
920
|
+
byFile.set(change.rel, change);
|
|
921
|
+
writeJson(file, [...byFile.values()].slice(-ELSEWHERE_KEPT));
|
|
922
|
+
}
|
|
923
|
+
|
|
924
|
+
// Takes what waits in a file once: renamed first, so a write the daemon makes meanwhile lands in a new one.
|
|
925
|
+
function takeJson(file) {
|
|
926
|
+
const taking = `${file}.${process.pid}.taking`;
|
|
927
|
+
try {
|
|
928
|
+
fs.renameSync(file, taking);
|
|
929
|
+
} catch {
|
|
930
|
+
return null;
|
|
931
|
+
}
|
|
932
|
+
const value = readJson(taking);
|
|
933
|
+
fs.rmSync(taking, { force: true });
|
|
934
|
+
return value;
|
|
935
|
+
}
|
|
936
|
+
|
|
937
|
+
/**
|
|
938
|
+
* The edge line at the session's pause (its next turn, or its next wake): one line naming what moved in its folder
|
|
939
|
+
* that it never read, "" for nothing. Left out: what its own commands made, a file told in the last line and changed
|
|
940
|
+
* again (a steady signal fades; a new one breaks through), and everything at volume "quiet".
|
|
941
|
+
*/
|
|
942
|
+
export function edgeAtPause(session, home = harnessHome) {
|
|
943
|
+
if (!ID.test(String(session ?? ""))) return "";
|
|
944
|
+
const changes =
|
|
945
|
+
takeJson(sessionFile(String(session), "elsewhere.json", home)) ?? [];
|
|
946
|
+
if (!changes.length || volumeOf(session, home) === "quiet") return "";
|
|
947
|
+
const commands =
|
|
948
|
+
readJson(sessionFile(String(session), "commands.json", home)) ?? [];
|
|
949
|
+
const toldFile = sessionFile(String(session), "edge-told.json", home);
|
|
950
|
+
const toldLast = new Set(readJson(toldFile) ?? []);
|
|
951
|
+
// A change's time is the file's own, which a coarse clock rounds down (a second on some disks), never up: so a
|
|
952
|
+
// command's window starts a second early and ends when it ended.
|
|
953
|
+
const itsOwn = (at) =>
|
|
954
|
+
commands.some((window) => at >= window.from - 1_000 && at <= window.to);
|
|
955
|
+
const news = changes.filter(
|
|
956
|
+
(change) => !itsOwn(Date.parse(change.at)) && !toldLast.has(change.rel)
|
|
957
|
+
);
|
|
958
|
+
writeJson(
|
|
959
|
+
toldFile,
|
|
960
|
+
changes.map((change) => change.rel)
|
|
961
|
+
);
|
|
962
|
+
if (!news.length) return "";
|
|
963
|
+
const named = news
|
|
964
|
+
.slice(-EDGE_NAMED)
|
|
965
|
+
.map((change) => (change.by ? `${change.rel} (${change.by})` : change.rel));
|
|
966
|
+
const more = news.length - named.length;
|
|
967
|
+
const count = `${news.length} file${news.length === 1 ? "" : "s"}`;
|
|
968
|
+
return `Elsewhere in this folder since you last looked: ${count} you have not read changed: ${named.join(", ")}${more ? ` and ${more} more` : ""}.`;
|
|
969
|
+
}
|
|
970
|
+
|
|
971
|
+
// --- what an action changed, and the receipt of a session's work (docs/senses-plan.md S4.7d) ---
|
|
972
|
+
|
|
973
|
+
const MADE_NAMED = 6;
|
|
974
|
+
const RAN_KEPT = 200;
|
|
975
|
+
const TEST =
|
|
976
|
+
/\b(test|tests|jest|vitest|pytest|mocha|playwright|rspec|phpunit|smoke|e2e)\b/i;
|
|
977
|
+
|
|
978
|
+
/** The daemon notes a file the session's own command changed in its folder (tripwires.mjs), said at its next step. */
|
|
979
|
+
export function noteMade(session, rel, home = harnessHome) {
|
|
980
|
+
if (!ID.test(String(session ?? ""))) return;
|
|
981
|
+
const file = sessionFile(String(session), "made.json", home);
|
|
982
|
+
const made = new Set(readJson(file) ?? []);
|
|
983
|
+
made.add(rel);
|
|
984
|
+
writeJson(file, [...made].slice(-200));
|
|
985
|
+
}
|
|
986
|
+
|
|
987
|
+
function madeLine(session, home) {
|
|
988
|
+
const made = takeJson(sessionFile(session, "made.json", home)) ?? [];
|
|
989
|
+
if (!made.length) return "";
|
|
990
|
+
const named = made.slice(0, MADE_NAMED).join(", ");
|
|
991
|
+
return `Your last command changed here: ${named}${made.length > MADE_NAMED ? ` and ${made.length - MADE_NAMED} more` : ""}.`;
|
|
992
|
+
}
|
|
993
|
+
|
|
994
|
+
// Whether a command worked, as the agent says it: its hook after a failed call, an exit code, an error flag. Null
|
|
995
|
+
// when it does not say.
|
|
996
|
+
function outcomeOf(output, failed) {
|
|
997
|
+
if (failed === true) return false;
|
|
998
|
+
if (failed === false) return true;
|
|
999
|
+
if (output && typeof output === "object" && !Array.isArray(output)) {
|
|
1000
|
+
const code = output.exit_code ?? output.exitCode ?? output.code;
|
|
1001
|
+
if (Number.isInteger(code)) return code === 0;
|
|
1002
|
+
if (typeof output.isError === "boolean") return !output.isError;
|
|
1003
|
+
if (typeof output.interrupted === "boolean" && output.interrupted)
|
|
1004
|
+
return false;
|
|
1005
|
+
}
|
|
1006
|
+
return null;
|
|
1007
|
+
}
|
|
1008
|
+
|
|
1009
|
+
function noteRan(session, command, ok, home) {
|
|
1010
|
+
const file = sessionFile(session, "ran.json", home);
|
|
1011
|
+
const ran = readJson(file) ?? [];
|
|
1012
|
+
ran.push({ command: command.slice(0, 300), ok, at: Date.now() });
|
|
1013
|
+
writeJson(file, ran.slice(-RAN_KEPT));
|
|
1014
|
+
}
|
|
1015
|
+
|
|
1016
|
+
/**
|
|
1017
|
+
* A session's own receipt, from what its hooks kept, in the shape of a run's (runWorker.mjs, audit.mjs): `verdict`
|
|
1018
|
+
* ("tested", "tests failing", "no changes", or "not tested after its last change"), the last test command after the
|
|
1019
|
+
* last change and whether it passed (null when the agent did not say), and the files it changed.
|
|
1020
|
+
*/
|
|
1021
|
+
export function sessionReceipt(session, home = harnessHome) {
|
|
1022
|
+
if (!ID.test(String(session ?? ""))) return null;
|
|
1023
|
+
const writes = readsOf(String(session), home).filter((seen) => seen.wrote);
|
|
1024
|
+
const lastChange = Math.max(0, ...writes.map((seen) => Date.parse(seen.at)));
|
|
1025
|
+
const ran = readJson(sessionFile(String(session), "ran.json", home)) ?? [];
|
|
1026
|
+
const tests = ran.filter(
|
|
1027
|
+
(each) => TEST.test(each.command) && each.at >= lastChange
|
|
1028
|
+
);
|
|
1029
|
+
const last = tests.at(-1) ?? null;
|
|
1030
|
+
const verdict = !writes.length
|
|
1031
|
+
? "no changes"
|
|
1032
|
+
: !last
|
|
1033
|
+
? "not tested after its last change"
|
|
1034
|
+
: last.ok === true
|
|
1035
|
+
? "tested"
|
|
1036
|
+
: last.ok === false
|
|
1037
|
+
? "tests failing"
|
|
1038
|
+
: "not tested after its last change";
|
|
1039
|
+
return {
|
|
1040
|
+
verdict,
|
|
1041
|
+
changed: writes.map((seen) => seen.file).slice(0, 50),
|
|
1042
|
+
test: last?.command ?? null,
|
|
1043
|
+
testOk: last?.ok ?? null,
|
|
1044
|
+
from: "hooks",
|
|
1045
|
+
at: new Date().toISOString(),
|
|
1046
|
+
};
|
|
1047
|
+
}
|
|
1048
|
+
|
|
1049
|
+
// A command that may leave something running: one sent to the background, or one that serves, watches or starts.
|
|
1050
|
+
const STARTS =
|
|
1051
|
+
/(&\s*($|[;)])|\bnohup\b|\b(serve|server|dev|start|up|watch|listen|daemon)\b)/;
|
|
1052
|
+
const SHOWN_RUNNING = 5;
|
|
1053
|
+
|
|
1054
|
+
/**
|
|
1055
|
+
* What a command left running: processes started while it ran that are still going, with the ports they listen on.
|
|
1056
|
+
* "" for nothing, or where the system cannot say (Windows).
|
|
1057
|
+
*/
|
|
1058
|
+
function leftRunning(since, agentPid) {
|
|
1059
|
+
if (process.platform === "win32" || !since) return "";
|
|
1060
|
+
const started = startedSince(since, agentPid);
|
|
1061
|
+
if (!started.length) return "";
|
|
1062
|
+
const ports = new Map();
|
|
1063
|
+
let pid = null;
|
|
1064
|
+
for (const line of runOutput("/usr/sbin/lsof", [
|
|
1065
|
+
"-nP",
|
|
1066
|
+
"-iTCP",
|
|
1067
|
+
"-sTCP:LISTEN",
|
|
1068
|
+
"-Fpn",
|
|
1069
|
+
]).split("\n")) {
|
|
1070
|
+
if (line.startsWith("p")) pid = Number(line.slice(1));
|
|
1071
|
+
else if (line.startsWith("n") && pid !== null) {
|
|
1072
|
+
const port = /:(\d+)$/.exec(line)?.[1];
|
|
1073
|
+
if (port) ports.set(pid, [...new Set([...(ports.get(pid) ?? []), port])]);
|
|
1074
|
+
}
|
|
1075
|
+
}
|
|
1076
|
+
const named = started.slice(0, SHOWN_RUNNING).map((each) => {
|
|
1077
|
+
const listens = ports.get(each.pid);
|
|
1078
|
+
return `${each.command.slice(0, 80)} (process ${each.pid}${listens ? `, listening on ${listens.join(", ")}` : ""})`;
|
|
1079
|
+
});
|
|
1080
|
+
return `Your command left running: ${named.join("; ")}${started.length > SHOWN_RUNNING ? ` and ${started.length - SHOWN_RUNNING} more` : ""}.`;
|
|
1081
|
+
}
|
|
1082
|
+
|
|
1083
|
+
/** The processes a command started since it began that still run: in its agent's tree, or left to launchd. */
|
|
1084
|
+
function startedSince(since, agentPid) {
|
|
1085
|
+
if (process.platform === "win32" || !since) return [];
|
|
1086
|
+
const all = runOutput("/bin/ps", ["-A", "-o", "pid=,ppid=,lstart=,command="])
|
|
1087
|
+
.split("\n")
|
|
1088
|
+
.map((line) =>
|
|
1089
|
+
/^\s*(\d+)\s+(\d+)\s+(\w{3} \w{3}\s+\d+ [\d:]+ \d{4})\s+(.*)$/.exec(line)
|
|
1090
|
+
)
|
|
1091
|
+
.filter(Boolean)
|
|
1092
|
+
.map((match) => ({
|
|
1093
|
+
pid: Number(match[1]),
|
|
1094
|
+
ppid: Number(match[2]),
|
|
1095
|
+
at: Date.parse(match[3]),
|
|
1096
|
+
command: match[4].trim(),
|
|
1097
|
+
}));
|
|
1098
|
+
// The agent's own process tree, less this hook and its shell: what its command could have started.
|
|
1099
|
+
const children = new Map();
|
|
1100
|
+
for (const each of all)
|
|
1101
|
+
children.set(each.ppid, [...(children.get(each.ppid) ?? []), each.pid]);
|
|
1102
|
+
const tree = new Set();
|
|
1103
|
+
const climb = (pid) => {
|
|
1104
|
+
for (const child of children.get(pid) ?? [])
|
|
1105
|
+
if (!tree.has(child)) {
|
|
1106
|
+
tree.add(child);
|
|
1107
|
+
climb(child);
|
|
1108
|
+
}
|
|
1109
|
+
};
|
|
1110
|
+
if (/^\d+$/.test(String(agentPid ?? ""))) climb(Number(agentPid));
|
|
1111
|
+
const mine = new Set([process.pid, process.ppid]);
|
|
1112
|
+
const started = all
|
|
1113
|
+
// A clock in whole seconds: a second's grace before the command began.
|
|
1114
|
+
.filter((each) => each.at >= since - 1_000 && !mine.has(each.pid))
|
|
1115
|
+
// In its tree, or left to launchd when its shell ended; never the system's own programs.
|
|
1116
|
+
.filter((each) => tree.has(each.pid) || each.ppid === 1)
|
|
1117
|
+
.filter(
|
|
1118
|
+
(each) =>
|
|
1119
|
+
!/^\/(System|usr\/libexec|usr\/sbin|Library\/Apple)\//.test(
|
|
1120
|
+
each.command
|
|
1121
|
+
)
|
|
1122
|
+
)
|
|
1123
|
+
.filter((each) => !/\b(ps|lsof|senseHook\.mjs)\b/.test(each.command));
|
|
1124
|
+
return started;
|
|
1125
|
+
}
|
|
1126
|
+
|
|
1127
|
+
// A system command's output, or what it printed before it failed.
|
|
1128
|
+
function runOutput(command, args) {
|
|
1129
|
+
try {
|
|
1130
|
+
return execFileSync(command, args, {
|
|
1131
|
+
encoding: "utf8",
|
|
1132
|
+
timeout: 2_000,
|
|
1133
|
+
stdio: ["ignore", "pipe", "ignore"],
|
|
1134
|
+
});
|
|
1135
|
+
} catch (error) {
|
|
1136
|
+
return String(error.stdout ?? "");
|
|
1137
|
+
}
|
|
1138
|
+
}
|
|
1139
|
+
|
|
1140
|
+
// --- polls (docs/senses-plan.md S4.7): an agent checking again and again is a sense it lacks, counted as a wish ---
|
|
1141
|
+
|
|
1142
|
+
export const pollsRoot = (home = harnessHome) =>
|
|
1143
|
+
path.join(sensesRoot(home), "polls");
|
|
1144
|
+
const POLL_WINDOW_MS = 10 * 60_000;
|
|
1145
|
+
// The same command this many times in the window is a poll; so is any command that waits first.
|
|
1146
|
+
const POLL_TIMES = 3;
|
|
1147
|
+
const WAITS = /\bsleep\s+\d/;
|
|
1148
|
+
|
|
1149
|
+
// A command as one poll is like the next: its waits taken out, its spaces made one.
|
|
1150
|
+
const pollShape = (command) =>
|
|
1151
|
+
command
|
|
1152
|
+
.replace(/\bsleep\s+[\d.]+[smh]?\s*(;|&&)?/g, "")
|
|
1153
|
+
.replace(/\s+/g, " ")
|
|
1154
|
+
.trim()
|
|
1155
|
+
.slice(0, 120);
|
|
1156
|
+
|
|
1157
|
+
function notePoll(session, agent, command, home) {
|
|
1158
|
+
const shape = pollShape(command);
|
|
1159
|
+
if (!shape) return;
|
|
1160
|
+
const now = Date.now();
|
|
1161
|
+
const recentFile = sessionFile(session, "shells.json", home);
|
|
1162
|
+
const recent = (readJson(recentFile) ?? []).filter(
|
|
1163
|
+
(each) => now - each.at < POLL_WINDOW_MS
|
|
1164
|
+
);
|
|
1165
|
+
recent.push({ shape, at: now });
|
|
1166
|
+
writeJson(recentFile, recent.slice(-30));
|
|
1167
|
+
const times = recent.filter((each) => each.shape === shape).length;
|
|
1168
|
+
if (!WAITS.test(command) && times < POLL_TIMES) return;
|
|
1169
|
+
const file = path.join(pollsRoot(home), `${session}.json`);
|
|
1170
|
+
const polls = readJson(file) ?? { agent, shapes: {} };
|
|
1171
|
+
const kept = polls.shapes[shape] ?? { count: 0, last: null };
|
|
1172
|
+
// The third time counts the two before it too.
|
|
1173
|
+
kept.count += kept.count === 0 && times >= POLL_TIMES ? times : 1;
|
|
1174
|
+
kept.last = new Date(now).toISOString();
|
|
1175
|
+
polls.shapes[shape] = kept;
|
|
1176
|
+
writeJson(file, polls);
|
|
1177
|
+
}
|
|
1178
|
+
|
|
1179
|
+
// --- recall (docs/senses-plan.md S4.6): an error's shape, or a file read for the first time, asked of the daemon ---
|
|
1180
|
+
|
|
1181
|
+
export const recallRoot = (home = harnessHome) =>
|
|
1182
|
+
path.join(sensesRoot(home), "recall");
|
|
1183
|
+
// The line that says what went wrong, in the words tools use for it.
|
|
1184
|
+
const ERROR_LINE =
|
|
1185
|
+
/(^|[\s:[(])(\w*Error|\w*Exception|ERR!|E[A-Z]{3,}|Traceback|FAIL(ED)?|fatal|panic|error)\b/;
|
|
1186
|
+
const SHAPE_LONGEST = 200;
|
|
1187
|
+
|
|
1188
|
+
const textOf = (output) => {
|
|
1189
|
+
if (output == null) return "";
|
|
1190
|
+
if (typeof output === "string") return output;
|
|
1191
|
+
if (Array.isArray(output))
|
|
1192
|
+
return output
|
|
1193
|
+
.map((part) => (typeof part === "string" ? part : (part?.text ?? "")))
|
|
1194
|
+
.join("\n");
|
|
1195
|
+
if (typeof output === "object")
|
|
1196
|
+
return [
|
|
1197
|
+
output.error,
|
|
1198
|
+
output.stderr,
|
|
1199
|
+
output.stdout,
|
|
1200
|
+
output.output,
|
|
1201
|
+
output.message,
|
|
1202
|
+
]
|
|
1203
|
+
.filter((part) => typeof part === "string")
|
|
1204
|
+
.join("\n");
|
|
1205
|
+
return String(output);
|
|
1206
|
+
};
|
|
1207
|
+
|
|
1208
|
+
/**
|
|
1209
|
+
* The shape of an error in what a tool gave back: its first line saying what went wrong, with what differs between
|
|
1210
|
+
* one time and the next taken out (paths to their last part, numbers, ids, quoted values). Null when nothing failed.
|
|
1211
|
+
*/
|
|
1212
|
+
export function errorShapeOf(output) {
|
|
1213
|
+
const line = textOf(output)
|
|
1214
|
+
.split("\n")
|
|
1215
|
+
.map((each) => each.trim())
|
|
1216
|
+
.find((each) => each.length > 3 && ERROR_LINE.test(each));
|
|
1217
|
+
if (!line) return null;
|
|
1218
|
+
return line
|
|
1219
|
+
.replace(/(?:[A-Za-z]:)?(?:[\w.@~-]*\/)+([\w.@-]+)/g, "$1")
|
|
1220
|
+
.replace(/\b[0-9a-f]{7,}\b/gi, "<id>")
|
|
1221
|
+
.replace(/\b\d+(\.\d+)?\b/g, "<n>")
|
|
1222
|
+
.replace(/(["'`])[^"'`]{1,80}\1/g, "$1…$1")
|
|
1223
|
+
.replace(/\s+/g, " ")
|
|
1224
|
+
.slice(0, SHAPE_LONGEST);
|
|
1225
|
+
}
|
|
1226
|
+
|
|
1227
|
+
// Asks the daemon once per shape for this session; the daemon answers at the session's next step.
|
|
1228
|
+
function askRecall(session, { agent, cwd, files, shape }, home) {
|
|
1229
|
+
const askedFile = sessionFile(session, "recalled.json", home);
|
|
1230
|
+
const asked = new Set(readJson(askedFile) ?? []);
|
|
1231
|
+
const keys = [
|
|
1232
|
+
...files.map((file) => `file:${file}`),
|
|
1233
|
+
...(shape ? [`error:${shape}`] : []),
|
|
1234
|
+
].filter((key) => !asked.has(key));
|
|
1235
|
+
if (!keys.length) return;
|
|
1236
|
+
for (const key of keys) asked.add(key);
|
|
1237
|
+
writeJson(askedFile, [...asked].slice(-500));
|
|
1238
|
+
writeJson(
|
|
1239
|
+
path.join(
|
|
1240
|
+
recallRoot(home),
|
|
1241
|
+
`${Date.now()}-${session}-${crypto.randomUUID().slice(0, 6)}.json`
|
|
1242
|
+
),
|
|
1243
|
+
{
|
|
1244
|
+
session,
|
|
1245
|
+
agent,
|
|
1246
|
+
cwd,
|
|
1247
|
+
files: files.filter((file) => keys.includes(`file:${file}`)),
|
|
1248
|
+
shape: shape && keys.includes(`error:${shape}`) ? shape : null,
|
|
1249
|
+
at: new Date().toISOString(),
|
|
1250
|
+
}
|
|
1251
|
+
);
|
|
1252
|
+
}
|
|
1253
|
+
|
|
1254
|
+
// --- company and marks (docs/senses-plan.md S4.5) ---
|
|
1255
|
+
|
|
1256
|
+
// Another session's work on a file counts as company for this long after it last read or wrote it.
|
|
1257
|
+
const COMPANY_MS = 30 * 60_000;
|
|
1258
|
+
// A mark fades after this many hours unless its maker says otherwise, and lasts a week at most.
|
|
1259
|
+
const MARK_HOURS = 24;
|
|
1260
|
+
const MARK_MOST_HOURS = 7 * 24;
|
|
1261
|
+
const MARK_LONGEST = 300;
|
|
1262
|
+
|
|
1263
|
+
const pidsRoot = (home) => path.join(sensesRoot(home), "pids");
|
|
1264
|
+
export const marksRoot = (home = harnessHome) =>
|
|
1265
|
+
path.join(sensesRoot(home), "marks");
|
|
1266
|
+
|
|
1267
|
+
const ago = (at, now = Date.now()) => {
|
|
1268
|
+
const minutes = Math.max(0, Math.round((now - Date.parse(at)) / 60_000));
|
|
1269
|
+
if (minutes < 1) return "just now";
|
|
1270
|
+
if (minutes < 60) return `${minutes} min ago`;
|
|
1271
|
+
const hours = Math.round(minutes / 60);
|
|
1272
|
+
return hours < 48 ? `${hours} h ago` : `${Math.round(hours / 24)} days ago`;
|
|
1273
|
+
};
|
|
1274
|
+
const relTo = (cwd, file) => {
|
|
1275
|
+
const rel = path.relative(cwd || "/", file);
|
|
1276
|
+
return rel && !rel.startsWith("..") ? rel : file;
|
|
1277
|
+
};
|
|
1278
|
+
|
|
1279
|
+
// Which session an agent's process last worked in: its MCP server, started by the same process, finds its session here.
|
|
1280
|
+
function notePid(agentPid, session, home) {
|
|
1281
|
+
if (!/^\d+$/.test(String(agentPid))) return;
|
|
1282
|
+
const file = path.join(pidsRoot(home), String(agentPid));
|
|
1283
|
+
try {
|
|
1284
|
+
if (fs.readFileSync(file, "utf8") === session) return;
|
|
1285
|
+
} catch {}
|
|
1286
|
+
try {
|
|
1287
|
+
fs.mkdirSync(pidsRoot(home), { recursive: true, mode: 0o700 });
|
|
1288
|
+
fs.writeFileSync(file, session, { mode: 0o600 });
|
|
1289
|
+
} catch {}
|
|
1290
|
+
}
|
|
1291
|
+
|
|
1292
|
+
/**
|
|
1293
|
+
* Whether a change at `at` (ms) was the session's own: inside one of its commands, or while a call of its process is
|
|
1294
|
+
* still running (its hook before the call noted the start, its hook after has not run yet).
|
|
1295
|
+
*/
|
|
1296
|
+
export function ownChange(session, at, home = harnessHome) {
|
|
1297
|
+
const commands = readJson(sessionFile(session, "commands.json", home)) ?? [];
|
|
1298
|
+
if (commands.some((window) => at >= window.from - 1_000 && at <= window.to))
|
|
1299
|
+
return true;
|
|
1300
|
+
let step = 0;
|
|
1301
|
+
try {
|
|
1302
|
+
step = fs.statSync(sessionFile(session, "step", home)).mtimeMs;
|
|
1303
|
+
} catch {}
|
|
1304
|
+
let pids = [];
|
|
1305
|
+
try {
|
|
1306
|
+
pids = fs.readdirSync(pidsRoot(home));
|
|
1307
|
+
} catch {}
|
|
1308
|
+
return pids.some((pid) => {
|
|
1309
|
+
try {
|
|
1310
|
+
if (fs.readFileSync(path.join(pidsRoot(home), pid), "utf8") !== session)
|
|
1311
|
+
return false;
|
|
1312
|
+
const started = fs.statSync(path.join(callsRoot(home), pid)).mtimeMs;
|
|
1313
|
+
return started > step && at >= started - 1_000;
|
|
1314
|
+
} catch {
|
|
1315
|
+
return false;
|
|
1316
|
+
}
|
|
1317
|
+
});
|
|
1318
|
+
}
|
|
1319
|
+
|
|
1320
|
+
/** The session an agent's process last worked in, or null. */
|
|
1321
|
+
export function sessionOfPid(agentPid, home = harnessHome) {
|
|
1322
|
+
if (!/^\d+$/.test(String(agentPid ?? ""))) return null;
|
|
1323
|
+
try {
|
|
1324
|
+
const session = fs.readFileSync(
|
|
1325
|
+
path.join(pidsRoot(home), String(agentPid)),
|
|
1326
|
+
"utf8"
|
|
1327
|
+
);
|
|
1328
|
+
return ID.test(session) ? session : null;
|
|
1329
|
+
} catch {
|
|
1330
|
+
return null;
|
|
1331
|
+
}
|
|
1332
|
+
}
|
|
1333
|
+
|
|
1334
|
+
// Company: another session at work that read or wrote a file this call touched. Both are told, once for the pair.
|
|
1335
|
+
function company(session, agent, cwd, files, home) {
|
|
1336
|
+
if (!files.length) return [];
|
|
1337
|
+
const toldFile = sessionFile(session, "company.json", home);
|
|
1338
|
+
const told = new Set(readJson(toldFile) ?? []);
|
|
1339
|
+
const now = Date.now();
|
|
1340
|
+
const lines = [];
|
|
1341
|
+
for (const other of sessionsAtWork(COMPANY_MS, home, now)) {
|
|
1342
|
+
if (other.session === session || told.has(other.session)) continue;
|
|
1343
|
+
for (const file of files) {
|
|
1344
|
+
const theirs = readJson(
|
|
1345
|
+
sessionFile(other.session, `${keyOf(file)}.json`, home)
|
|
1346
|
+
);
|
|
1347
|
+
if (!theirs || now - Date.parse(theirs.at) > COMPANY_MS) continue;
|
|
1348
|
+
const rel = relTo(cwd, file);
|
|
1349
|
+
lines.push(
|
|
1350
|
+
`${nameOf(other.agent)} is working on ${rel} too, in another session (it ${theirs.wrote ? "wrote" : "read"} it ${ago(theirs.at, now)}).`
|
|
1351
|
+
);
|
|
1352
|
+
putSteer(
|
|
1353
|
+
{
|
|
1354
|
+
session: other.session,
|
|
1355
|
+
agent: PARENT,
|
|
1356
|
+
kind: SENSE,
|
|
1357
|
+
text: `${nameOf(agent)} is working on ${relTo(other.cwd, file)} too, in another session.`,
|
|
1358
|
+
},
|
|
1359
|
+
home
|
|
1360
|
+
);
|
|
1361
|
+
told.add(other.session);
|
|
1362
|
+
const theirTold = sessionFile(other.session, "company.json", home);
|
|
1363
|
+
writeJson(theirTold, [
|
|
1364
|
+
...new Set([...(readJson(theirTold) ?? []), session]),
|
|
1365
|
+
]);
|
|
1366
|
+
break;
|
|
1367
|
+
}
|
|
1368
|
+
}
|
|
1369
|
+
if (lines.length) writeJson(toldFile, [...told]);
|
|
1370
|
+
return lines;
|
|
1371
|
+
}
|
|
1372
|
+
|
|
1373
|
+
/**
|
|
1374
|
+
* Leaves a mark on a file or a service for whichever agent comes near it next: `{ file }` (absolute) or `{ service }`
|
|
1375
|
+
* (a name a command or a tool's input would mention), `text`, `by` (the agent), `session` (its own, never told it),
|
|
1376
|
+
* `hours` until it fades. Returns the mark, or `{ error }`.
|
|
1377
|
+
*/
|
|
1378
|
+
export function putMark(
|
|
1379
|
+
{ file, service, text, by, session = null, hours, intent = false },
|
|
1380
|
+
home = harnessHome
|
|
1381
|
+
) {
|
|
1382
|
+
const words = String(text ?? "")
|
|
1383
|
+
.trim()
|
|
1384
|
+
.replace(/\s+/g, " ");
|
|
1385
|
+
if (!words) return { error: "say what the mark says" };
|
|
1386
|
+
if (words.length > MARK_LONGEST)
|
|
1387
|
+
return { error: `a mark is at most ${MARK_LONGEST} characters` };
|
|
1388
|
+
if (!file === !service) return { error: "mark a file or a service" };
|
|
1389
|
+
// A minute at least, a week at most.
|
|
1390
|
+
const lasts = Math.min(
|
|
1391
|
+
MARK_MOST_HOURS,
|
|
1392
|
+
Math.max(1 / 60, Number(hours) || MARK_HOURS)
|
|
1393
|
+
);
|
|
1394
|
+
const at = new Date();
|
|
1395
|
+
const mark = {
|
|
1396
|
+
id: crypto.randomUUID().slice(0, 8),
|
|
1397
|
+
// By its real path, as a call names what it touched (callOf).
|
|
1398
|
+
...(file
|
|
1399
|
+
? {
|
|
1400
|
+
file: path.isAbsolute(String(file))
|
|
1401
|
+
? realOf(String(file))
|
|
1402
|
+
: String(file),
|
|
1403
|
+
}
|
|
1404
|
+
: { service: String(service).trim() }),
|
|
1405
|
+
text: words,
|
|
1406
|
+
by: String(by ?? "an agent"),
|
|
1407
|
+
session: session ? String(session) : null,
|
|
1408
|
+
...(intent ? { intent: true } : {}),
|
|
1409
|
+
at: at.toISOString(),
|
|
1410
|
+
until: new Date(at.getTime() + lasts * 3_600_000).toISOString(),
|
|
1411
|
+
};
|
|
1412
|
+
writeJson(path.join(marksRoot(home), `${mark.id}.json`), mark);
|
|
1413
|
+
return mark;
|
|
1414
|
+
}
|
|
1415
|
+
|
|
1416
|
+
// The marks a call is near, by `isNear(mark)`, as the lines the session reads. Each reaches a session once; a faded one
|
|
1417
|
+
// is gone.
|
|
1418
|
+
function marksTold(session, cwd, isNear, home) {
|
|
1419
|
+
let names = [];
|
|
1420
|
+
try {
|
|
1421
|
+
names = fs
|
|
1422
|
+
.readdirSync(marksRoot(home))
|
|
1423
|
+
.filter((name) => name.endsWith(".json"));
|
|
1424
|
+
} catch {
|
|
1425
|
+
return [];
|
|
1426
|
+
}
|
|
1427
|
+
if (!names.length) return [];
|
|
1428
|
+
const now = Date.now();
|
|
1429
|
+
const toldFile = sessionFile(session, "marks-told.json", home);
|
|
1430
|
+
const told = new Set(readJson(toldFile) ?? []);
|
|
1431
|
+
const lines = [];
|
|
1432
|
+
for (const name of names) {
|
|
1433
|
+
const mark = readJson(path.join(marksRoot(home), name));
|
|
1434
|
+
if (!mark) continue;
|
|
1435
|
+
if (Date.parse(mark.until) <= now) {
|
|
1436
|
+
fs.rmSync(path.join(marksRoot(home), name), { force: true });
|
|
1437
|
+
continue;
|
|
1438
|
+
}
|
|
1439
|
+
if (mark.session === session || told.has(mark.id)) continue;
|
|
1440
|
+
if (!isNear(mark)) continue;
|
|
1441
|
+
const where = mark.file ? relTo(cwd, mark.file) : mark.service;
|
|
1442
|
+
lines.push(
|
|
1443
|
+
mark.intent
|
|
1444
|
+
? `${mark.by} means to do this next, at ${where} (its intention, ${ago(mark.at, now)}): "${mark.text}"`
|
|
1445
|
+
: `A mark ${mark.by} left on ${where} ${ago(mark.at, now)} (a note, not an instruction): "${mark.text}"`
|
|
1446
|
+
);
|
|
1447
|
+
told.add(mark.id);
|
|
1448
|
+
}
|
|
1449
|
+
if (lines.length) writeJson(toldFile, [...told]);
|
|
1450
|
+
return lines;
|
|
1451
|
+
}
|
|
1452
|
+
|
|
1453
|
+
const namesService = (input, mark) =>
|
|
1454
|
+
JSON.stringify(input ?? "")
|
|
1455
|
+
.toLowerCase()
|
|
1456
|
+
.includes(String(mark.service).toLowerCase());
|
|
1457
|
+
|
|
1458
|
+
// After a call: the marks on a file it read or wrote, or on a service its command or input names.
|
|
1459
|
+
function marksNear(session, cwd, files, input, home) {
|
|
1460
|
+
const touched = new Set(files);
|
|
1461
|
+
return marksTold(
|
|
1462
|
+
session,
|
|
1463
|
+
cwd,
|
|
1464
|
+
(mark) => (mark.file ? touched.has(mark.file) : namesService(input, mark)),
|
|
1465
|
+
home
|
|
1466
|
+
);
|
|
1467
|
+
}
|
|
1468
|
+
|
|
1469
|
+
// Before a call: the marks on a file it is about to write, an intention for a folder it is about to write in, and a
|
|
1470
|
+
// mark on a service that a command, or a tool that reads no file, names. A read is never held.
|
|
1471
|
+
function marksBefore(session, cwd, call, input, home) {
|
|
1472
|
+
const writes = call.writes.map((write) => write.file);
|
|
1473
|
+
const acts = call.shell || !call.reads.length;
|
|
1474
|
+
if (!writes.length && !acts) return [];
|
|
1475
|
+
const writesIn = (folder) =>
|
|
1476
|
+
writes.some((file) => file.startsWith(folder + path.sep));
|
|
1477
|
+
return marksTold(
|
|
1478
|
+
session,
|
|
1479
|
+
cwd,
|
|
1480
|
+
(mark) =>
|
|
1481
|
+
mark.file
|
|
1482
|
+
? writes.includes(mark.file) || (mark.intent && writesIn(mark.file))
|
|
1483
|
+
: acts && namesService(input, mark),
|
|
1484
|
+
home
|
|
1485
|
+
);
|
|
1486
|
+
}
|
|
1487
|
+
|
|
1488
|
+
/** The sessions working on this computer now: those whose last tool call ended within `withinMs`. */
|
|
1489
|
+
export function sessionsAtWork(withinMs, home = harnessHome, now = Date.now()) {
|
|
1490
|
+
let names = [];
|
|
1491
|
+
try {
|
|
1492
|
+
names = fs.readdirSync(readsRoot(home));
|
|
1493
|
+
} catch {}
|
|
1494
|
+
return names
|
|
1495
|
+
.map((session) => {
|
|
1496
|
+
let step = 0;
|
|
1497
|
+
try {
|
|
1498
|
+
step = fs.statSync(sessionFile(session, "step", home)).mtimeMs;
|
|
1499
|
+
} catch {}
|
|
1500
|
+
return { session, step, ...(sessionOf(session, home) ?? {}) };
|
|
1501
|
+
})
|
|
1502
|
+
.filter((each) => ID.test(each.session) && now - each.step <= withinMs);
|
|
1503
|
+
}
|
|
1504
|
+
|
|
1505
|
+
/** Puts a kept version back as a file, keeping what is there now. `id` may be the first 12 characters. */
|
|
1506
|
+
export function restoreVersion(id, file, home = harnessHome) {
|
|
1507
|
+
const short = String(id ?? "").toLowerCase();
|
|
1508
|
+
if (!/^[0-9a-f]{7,40}$/.test(short))
|
|
1509
|
+
return { ok: false, error: "name a kept version by its id" };
|
|
1510
|
+
const versions = versionsOf(home);
|
|
1511
|
+
const full = short.length === 40 ? short : versions.find(short);
|
|
1512
|
+
if (!full) return { ok: false, error: "that version is not kept" };
|
|
1513
|
+
return versions.restore(full, path.resolve(file));
|
|
1514
|
+
}
|