@orchestraworks/worker-win32-x64 0.0.134
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/LICENSE +202 -0
- package/package.json +17 -0
- package/script-harness/fetch-failure.js +44 -0
- package/script-harness/index.js +757 -0
- package/script-harness/package.json +8 -0
- package/worker.exe +4 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
|
|
2
|
+
Apache License
|
|
3
|
+
Version 2.0, January 2004
|
|
4
|
+
http://www.apache.org/licenses/
|
|
5
|
+
|
|
6
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
7
|
+
|
|
8
|
+
1. Definitions.
|
|
9
|
+
|
|
10
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
11
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
12
|
+
|
|
13
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
14
|
+
the copyright owner that is granting the License.
|
|
15
|
+
|
|
16
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
17
|
+
other entities that control, are controlled by, or are under common
|
|
18
|
+
control with that entity. For the purposes of this definition,
|
|
19
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
20
|
+
direction or management of such entity, whether by contract or
|
|
21
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
22
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
23
|
+
|
|
24
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
25
|
+
exercising permissions granted by this License.
|
|
26
|
+
|
|
27
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
28
|
+
including but not limited to software source code, documentation
|
|
29
|
+
source, and configuration files.
|
|
30
|
+
|
|
31
|
+
"Object" form shall mean any form resulting from mechanical
|
|
32
|
+
transformation or translation of a Source form, including but
|
|
33
|
+
not limited to compiled object code, generated documentation,
|
|
34
|
+
and conversions to other media types.
|
|
35
|
+
|
|
36
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
37
|
+
Object form, made available under the License, as indicated by a
|
|
38
|
+
copyright notice that is included in or attached to the work
|
|
39
|
+
(an example is provided in the Appendix below).
|
|
40
|
+
|
|
41
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
42
|
+
form, that is based on (or derived from) the Work and for which the
|
|
43
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
44
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
45
|
+
of this License, Derivative Works shall not include works that remain
|
|
46
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
47
|
+
the Work and Derivative Works thereof.
|
|
48
|
+
|
|
49
|
+
"Contribution" shall mean any work of authorship, including
|
|
50
|
+
the original version of the Work and any modifications or additions
|
|
51
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
52
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
53
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
54
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
55
|
+
means any form of electronic, verbal, or written communication sent
|
|
56
|
+
to the Licensor or its representatives, including but not limited to
|
|
57
|
+
communication on electronic mailing lists, source code control systems,
|
|
58
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
59
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
60
|
+
excluding communication that is conspicuously marked or otherwise
|
|
61
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
62
|
+
|
|
63
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
64
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
65
|
+
subsequently incorporated within the Work.
|
|
66
|
+
|
|
67
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
68
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
69
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
70
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
71
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
72
|
+
Work and such Derivative Works in Source or Object form.
|
|
73
|
+
|
|
74
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
75
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
76
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
77
|
+
(except as stated in this section) patent license to make, have made,
|
|
78
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
79
|
+
where such license applies only to those patent claims licensable
|
|
80
|
+
by such Contributor that are necessarily infringed by their
|
|
81
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
82
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
83
|
+
institute patent litigation against any entity (including a
|
|
84
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
85
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
86
|
+
or contributory patent infringement, then any patent licenses
|
|
87
|
+
granted to You under this License for that Work shall terminate
|
|
88
|
+
as of the date such litigation is filed.
|
|
89
|
+
|
|
90
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
91
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
92
|
+
modifications, and in Source or Object form, provided that You
|
|
93
|
+
meet the following conditions:
|
|
94
|
+
|
|
95
|
+
(a) You must give any other recipients of the Work or
|
|
96
|
+
Derivative Works a copy of this License; and
|
|
97
|
+
|
|
98
|
+
(b) You must cause any modified files to carry prominent notices
|
|
99
|
+
stating that You changed the files; and
|
|
100
|
+
|
|
101
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
102
|
+
that You distribute, all copyright, patent, trademark, and
|
|
103
|
+
attribution notices from the Source form of the Work,
|
|
104
|
+
excluding those notices that do not pertain to any part of
|
|
105
|
+
the Derivative Works; and
|
|
106
|
+
|
|
107
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
108
|
+
distribution, then any Derivative Works that You distribute must
|
|
109
|
+
include a readable copy of the attribution notices contained
|
|
110
|
+
within such NOTICE file, excluding those notices that do not
|
|
111
|
+
pertain to any part of the Derivative Works, in at least one
|
|
112
|
+
of the following places: within a NOTICE text file distributed
|
|
113
|
+
as part of the Derivative Works; within the Source form or
|
|
114
|
+
documentation, if provided along with the Derivative Works; or,
|
|
115
|
+
within a display generated by the Derivative Works, if and
|
|
116
|
+
wherever such third-party notices normally appear. The contents
|
|
117
|
+
of the NOTICE file are for informational purposes only and
|
|
118
|
+
do not modify the License. You may add Your own attribution
|
|
119
|
+
notices within Derivative Works that You distribute, alongside
|
|
120
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
121
|
+
that such additional attribution notices cannot be construed
|
|
122
|
+
as modifying the License.
|
|
123
|
+
|
|
124
|
+
You may add Your own copyright statement to Your modifications and
|
|
125
|
+
may provide additional or different license terms and conditions
|
|
126
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
127
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
128
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
129
|
+
the conditions stated in this License.
|
|
130
|
+
|
|
131
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
132
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
133
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
134
|
+
this License, without any additional terms or conditions.
|
|
135
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
136
|
+
the terms of any separate license agreement you may have executed
|
|
137
|
+
with Licensor regarding such Contributions.
|
|
138
|
+
|
|
139
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
140
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
141
|
+
except as required for reasonable and customary use in describing the
|
|
142
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
143
|
+
|
|
144
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
145
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
146
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
147
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
148
|
+
implied, including, without limitation, any warranties or conditions
|
|
149
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
150
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
151
|
+
appropriateness of using or redistributing the Work and assume any
|
|
152
|
+
risks associated with Your exercise of permissions under this License.
|
|
153
|
+
|
|
154
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
155
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
156
|
+
unless required by applicable law (such as deliberate and grossly
|
|
157
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
158
|
+
liable to You for damages, including any direct, indirect, special,
|
|
159
|
+
incidental, or consequential damages of any character arising as a
|
|
160
|
+
result of this License or out of the use or inability to use the
|
|
161
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
162
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
163
|
+
other commercial damages or losses), even if such Contributor
|
|
164
|
+
has been advised of the possibility of such damages.
|
|
165
|
+
|
|
166
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
167
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
168
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
169
|
+
or other liability obligations and/or rights consistent with this
|
|
170
|
+
License. However, in accepting such obligations, You may act only
|
|
171
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
172
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
173
|
+
defend, and hold each Contributor harmless for any liability
|
|
174
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
175
|
+
of your accepting any such warranty or additional liability.
|
|
176
|
+
|
|
177
|
+
END OF TERMS AND CONDITIONS
|
|
178
|
+
|
|
179
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
180
|
+
|
|
181
|
+
To apply the Apache License to your work, attach the following
|
|
182
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
183
|
+
replaced with your own identifying information. (Don't include
|
|
184
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
185
|
+
comment syntax for the file format. We also recommend that a
|
|
186
|
+
file or class name and description of purpose be included on the
|
|
187
|
+
same "printed page" as the copyright notice for easier
|
|
188
|
+
identification within third-party archives.
|
|
189
|
+
|
|
190
|
+
Copyright 2026 Living Computers
|
|
191
|
+
|
|
192
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
193
|
+
you may not use this file except in compliance with the License.
|
|
194
|
+
You may obtain a copy of the License at
|
|
195
|
+
|
|
196
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
197
|
+
|
|
198
|
+
Unless required by applicable law or agreed to in writing, software
|
|
199
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
200
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
201
|
+
See the License for the specific language governing permissions and
|
|
202
|
+
limitations under the License.
|
package/package.json
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@orchestraworks/worker-win32-x64",
|
|
3
|
+
"version": "0.0.134",
|
|
4
|
+
"description": "The Software Factory worker binary for win32 x64.",
|
|
5
|
+
"license": "Apache-2.0",
|
|
6
|
+
"author": "Living Computers",
|
|
7
|
+
"repository": {
|
|
8
|
+
"type": "git",
|
|
9
|
+
"url": "https://github.com/livingcomputers/software-factory.git"
|
|
10
|
+
},
|
|
11
|
+
"os": [
|
|
12
|
+
"win32"
|
|
13
|
+
],
|
|
14
|
+
"cpu": [
|
|
15
|
+
"x64"
|
|
16
|
+
]
|
|
17
|
+
}
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
// Node's `fetch` (undici) reports EVERY transport failure with the same four characterless words,
|
|
2
|
+
// "fetch failed", and puts the diagnosis on `error.cause`: an errno-style `code` (ECONNREFUSED,
|
|
3
|
+
// UNABLE_TO_VERIFY_LEAF_SIGNATURE, …) and, for a connect failure, the `address`/`port` it could not
|
|
4
|
+
// reach. A throw built from `error.message` alone discards the one fact that names the LAYER that broke.
|
|
5
|
+
//
|
|
6
|
+
// Its own module rather than a helper inside index.js: importing `index.js` installs a readline interface
|
|
7
|
+
// on `process.stdin` and exits the process when that closes. This file is plain Node with no imports.
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* Deliberately a *cause* renderer and not a message formatter: the caller keeps owning the sentence, so a
|
|
11
|
+
* call site that already says which request failed does not have that repeated back to it.
|
|
12
|
+
*
|
|
13
|
+
* @param {unknown} error the value `fetch` threw.
|
|
14
|
+
* @returns {string} e.g. `"ECONNREFUSED 10.0.1.5:443"`, the cause's own message when it carries no code,
|
|
15
|
+
* or `""`.
|
|
16
|
+
*/
|
|
17
|
+
export function describeFetchFailure(error) {
|
|
18
|
+
const cause = error?.cause;
|
|
19
|
+
if (!cause) return "";
|
|
20
|
+
// A string cause is legal (`new Error(msg, { cause: "reset by peer" })`) and is
|
|
21
|
+
// the whole diagnosis when it happens.
|
|
22
|
+
if (typeof cause === "string") return cause.trim();
|
|
23
|
+
if (typeof cause !== "object") return "";
|
|
24
|
+
|
|
25
|
+
const code = typeof cause.code === "string" ? cause.code.trim() : "";
|
|
26
|
+
const peer = peerOf(cause);
|
|
27
|
+
if (code) return peer ? `${code} ${peer}` : code;
|
|
28
|
+
|
|
29
|
+
// No code: undici's aggregate causes and TLS alerts carry only a message, and
|
|
30
|
+
// that message is still strictly more than "fetch failed".
|
|
31
|
+
return typeof cause.message === "string" ? cause.message.trim() : "";
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* `address:port` when the cause names the peer it could not reach, `""` otherwise. An IPv6 literal is
|
|
36
|
+
* bracketed, because `fd00:a::17:443` reads as an address.
|
|
37
|
+
*/
|
|
38
|
+
function peerOf(cause) {
|
|
39
|
+
const address = typeof cause.address === "string" ? cause.address.trim() : "";
|
|
40
|
+
if (!address) return "";
|
|
41
|
+
const port = Number.isInteger(cause.port) ? String(cause.port) : "";
|
|
42
|
+
if (!port) return address;
|
|
43
|
+
return address.includes(":") ? `[${address}]:${port}` : `${address}:${port}`;
|
|
44
|
+
}
|
|
@@ -0,0 +1,757 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// The script agent runtime harness: a zero-dependency Node 22 ESM server speaking the Go bridge's
|
|
3
|
+
// line-delimited stdio JSON-RPC. One process per bridge multiplexes every session over one stdio pipe,
|
|
4
|
+
// so the read loop must never block on an in-flight command.
|
|
5
|
+
//
|
|
6
|
+
// Each turn ends by setting the session's outcome claim from the command's exit code. A machine the
|
|
7
|
+
// customer enrolled, which the worker declares by setting `SFDK_MACHINE_ENROLLED`, has no edge of ours in
|
|
8
|
+
// front of it, so every claim there would be refused: the harness makes no call at all and ends the turn
|
|
9
|
+
// on the script's own answer.
|
|
10
|
+
|
|
11
|
+
import { spawn } from "node:child_process";
|
|
12
|
+
import { randomUUID } from "node:crypto";
|
|
13
|
+
import { appendFileSync, mkdirSync, readFileSync } from "node:fs";
|
|
14
|
+
import { homedir } from "node:os";
|
|
15
|
+
import path from "node:path";
|
|
16
|
+
import { createInterface } from "node:readline";
|
|
17
|
+
|
|
18
|
+
import { describeFetchFailure } from "./fetch-failure.js";
|
|
19
|
+
|
|
20
|
+
const HARNESS_NAME = "software-factory-script-harness";
|
|
21
|
+
const HARNESS_VERSION = "0.0.134";
|
|
22
|
+
|
|
23
|
+
const IS_WINDOWS = process.platform === "win32";
|
|
24
|
+
|
|
25
|
+
// -32001 matches the bridge's own code for a failed runtime request.
|
|
26
|
+
const SCRIPT_FAILURE_CODE = -32001;
|
|
27
|
+
const INVALID_PARAMS_CODE = -32602;
|
|
28
|
+
const METHOD_NOT_FOUND_CODE = -32601;
|
|
29
|
+
const INTERNAL_ERROR_CODE = -32603;
|
|
30
|
+
const TURN_RUNNING_CODE = -32002;
|
|
31
|
+
|
|
32
|
+
// The bridge's stdout scanner caps a line at 1MB, so every tail the harness emits — and every
|
|
33
|
+
// `session/update` chunk below — stays far inside that bound.
|
|
34
|
+
const STDERR_TAIL_ERROR = 2000;
|
|
35
|
+
const STDERR_TAIL_SUMMARY = 500;
|
|
36
|
+
const STDOUT_TAIL_CONTENT = 2000;
|
|
37
|
+
|
|
38
|
+
const UPDATE_CHUNK_LIMIT = 32000;
|
|
39
|
+
|
|
40
|
+
// A SIBLING of the controller's `.software-factory/` rather than nested inside it: the capture walk
|
|
41
|
+
// refuses two roots where one contains the other, because the outer root's walk would reach the inner
|
|
42
|
+
// root's files under an exclusion list that does not name them. Also the descriptor's `home` and its
|
|
43
|
+
// `storeLayout.directory`, authored in `agents/runtime/assembly/manifest.json`.
|
|
44
|
+
const TRANSCRIPT_DIRECTORY = [".script-harness"];
|
|
45
|
+
const INSTRUCTIONS_FILE = ".script-harness/instructions.sh";
|
|
46
|
+
|
|
47
|
+
const TRANSCRIPT_SUFFIX = ".jsonl";
|
|
48
|
+
|
|
49
|
+
// A session id becomes a FILE NAME. This harness mints filesystem-safe ids, but `session/load` carries
|
|
50
|
+
// whatever id the caller handed the bridge, and a `/` or a `..` in one would address a file outside the
|
|
51
|
+
// transcript directory. Anything outside this alphabet is not recorded and not replayed.
|
|
52
|
+
const SAFE_SESSION_ID = /^[A-Za-z0-9_.-]+$/;
|
|
53
|
+
|
|
54
|
+
// Counted in WIRE bytes. Per-frame slicing bounds the bridge's line scanner but not the volume: the
|
|
55
|
+
// platform holds every frame of a turn in memory and this runtime's output is arbitrary customer job
|
|
56
|
+
// output (`make 2>&1`), so an unbounded build log is an OOM shape. Past the ceiling exactly ONE
|
|
57
|
+
// truncation notice is emitted; the command still runs and the exit-code contract is unchanged.
|
|
58
|
+
const TURN_OUTPUT_LIMIT_BYTES = 5 * 1024 * 1024;
|
|
59
|
+
const TURN_OUTPUT_TRUNCATION_NOTICE =
|
|
60
|
+
`\n[${HARNESS_NAME}] output truncated: this turn exceeded the ` +
|
|
61
|
+
`${TURN_OUTPUT_LIMIT_BYTES} byte streaming ceiling. The command is still running to ` +
|
|
62
|
+
`completion and its exit status is unaffected; only further streamed output is dropped.\n`;
|
|
63
|
+
|
|
64
|
+
// A lingering grandchild can hold the pipes open forever, which must never wedge a turn.
|
|
65
|
+
const STDIO_FLUSH_GRACE_MS = 250;
|
|
66
|
+
|
|
67
|
+
// Undici's default headers timeout is 300s, half the platform's own ACP response timeout (600s): an
|
|
68
|
+
// unreachable agent API would hold the turn that long before surfacing as the claim failure it is.
|
|
69
|
+
const PLATFORM_REQUEST_TIMEOUT_MS = 30000;
|
|
70
|
+
|
|
71
|
+
const sessions = new Map();
|
|
72
|
+
|
|
73
|
+
function sessionState(sessionId) {
|
|
74
|
+
let state = sessions.get(sessionId);
|
|
75
|
+
if (!state) {
|
|
76
|
+
state = { context: null, turn: null, prompting: null, cwd: null };
|
|
77
|
+
sessions.set(sessionId, state);
|
|
78
|
+
}
|
|
79
|
+
return state;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/**
|
|
83
|
+
* The bridge has already mapped `cwd` to the runtime's NATIVE filesystem by the time it arrives, so no
|
|
84
|
+
* path handling of any kind belongs here. Anything that is not a non-empty string is `null`: the bridge
|
|
85
|
+
* forwards a non-string `cwd` untouched on purpose (it translates, it does not police), so this reader
|
|
86
|
+
* must not invent a failure for a frame the bridge tolerated.
|
|
87
|
+
*/
|
|
88
|
+
function declaredCwd(params) {
|
|
89
|
+
const cwd = params?.cwd;
|
|
90
|
+
return typeof cwd === "string" && cwd !== "" ? cwd : null;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
function write(message) {
|
|
94
|
+
process.stdout.write(`${JSON.stringify(message)}\n`);
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
function respondResult(id, result) {
|
|
98
|
+
write({ jsonrpc: "2.0", id, result });
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
function respondError(id, code, message, data) {
|
|
102
|
+
const error = data === undefined ? { code, message } : { code, message, data };
|
|
103
|
+
write({ jsonrpc: "2.0", id, error });
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
function sessionUpdateFrame(sessionId, update) {
|
|
107
|
+
return { jsonrpc: "2.0", method: "session/update", params: { sessionId, update } };
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/**
|
|
111
|
+
* The wire write comes first and the transcript append second: the frame is the contract and the
|
|
112
|
+
* transcript is a fidelity nicety, so a slow or broken filesystem can never delay or drop what the
|
|
113
|
+
* bridge sees.
|
|
114
|
+
*/
|
|
115
|
+
function agentMessageChunk(text) {
|
|
116
|
+
return { sessionUpdate: "agent_message_chunk", content: { type: "text", text } };
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
function notifySessionUpdate(sessionId, text) {
|
|
120
|
+
const update = agentMessageChunk(text);
|
|
121
|
+
write(sessionUpdateFrame(sessionId, update));
|
|
122
|
+
recordSessionUpdate(sessionId, update);
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
/**
|
|
126
|
+
* Bounded twice: each frame is sliced at [UPDATE_CHUNK_LIMIT], because the bridge reads this process's
|
|
127
|
+
* stdout with a 1MB LINE cap and one over-long line would stop its scanner and kill every session on
|
|
128
|
+
* the pipe; and the turn's TOTAL streamed volume is capped at [TURN_OUTPUT_LIMIT_BYTES].
|
|
129
|
+
*
|
|
130
|
+
* The ceiling counts the JSON-ENCODED size, because what the platform retains is the wire frame. JSON
|
|
131
|
+
* escaping inflates control-heavy output by up to ~6x (one NUL byte is six wire bytes), so raw
|
|
132
|
+
* accounting let a binary-ish `make 2>&1` push ~30 MB through a "5 MiB" ceiling.
|
|
133
|
+
*/
|
|
134
|
+
function emitOutput(turn, sessionId, text) {
|
|
135
|
+
if (turn.outputTruncated) return;
|
|
136
|
+
const bytes = Buffer.byteLength(JSON.stringify(text), "utf8");
|
|
137
|
+
if (turn.emittedBytes + bytes > TURN_OUTPUT_LIMIT_BYTES) {
|
|
138
|
+
turn.outputTruncated = true;
|
|
139
|
+
notifySessionUpdate(sessionId, TURN_OUTPUT_TRUNCATION_NOTICE);
|
|
140
|
+
return;
|
|
141
|
+
}
|
|
142
|
+
turn.emittedBytes += bytes;
|
|
143
|
+
for (let offset = 0; offset < text.length; offset += UPDATE_CHUNK_LIMIT) {
|
|
144
|
+
notifySessionUpdate(sessionId, text.slice(offset, offset + UPDATE_CHUNK_LIMIT));
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
function logDiagnostic(text) {
|
|
149
|
+
process.stderr.write(`[${HARNESS_NAME}] ${text}\n`);
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
// The platform grades a resume on REPLAY FIDELITY: it counts the `session/update` frames a runtime
|
|
153
|
+
// emits between its `session/load` request and that request's response, and a session with a prior
|
|
154
|
+
// completed turn that replays ZERO frames is downgraded from RESUMED to RECONSTRUCTED. `$HOME` is the
|
|
155
|
+
// carrier because it is the one thing the compute plane keeps across a machine's death. One line per
|
|
156
|
+
// frame, holding `params.update` verbatim; appends are SYNCHRONOUS because order is the point, and
|
|
157
|
+
// every failure is reported once on stderr and swallowed, because the exit code is the contract.
|
|
158
|
+
|
|
159
|
+
function sessionFile(sessionId, suffix) {
|
|
160
|
+
if (typeof sessionId !== "string" || !SAFE_SESSION_ID.test(sessionId) || sessionId.startsWith(".")) {
|
|
161
|
+
return null;
|
|
162
|
+
}
|
|
163
|
+
return path.join(homedir(), ...TRANSCRIPT_DIRECTORY, `${sessionId}${suffix}`);
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
function transcriptFile(sessionId) {
|
|
167
|
+
return sessionFile(sessionId, TRANSCRIPT_SUFFIX);
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
// One diagnostic per session, not one per frame, because the failure mode is "every append fails".
|
|
171
|
+
const transcriptFailures = new Set();
|
|
172
|
+
let transcriptDirectoryReady = false;
|
|
173
|
+
|
|
174
|
+
function recordSessionUpdate(sessionId, update) {
|
|
175
|
+
const file = transcriptFile(sessionId);
|
|
176
|
+
if (!file) return;
|
|
177
|
+
try {
|
|
178
|
+
if (!transcriptDirectoryReady) {
|
|
179
|
+
mkdirSync(path.dirname(file), { recursive: true });
|
|
180
|
+
transcriptDirectoryReady = true;
|
|
181
|
+
}
|
|
182
|
+
appendFileSync(file, `${JSON.stringify(update)}\n`);
|
|
183
|
+
} catch (error) {
|
|
184
|
+
// Re-arm the mkdir: the cheapest explanation for an append that suddenly fails is a directory that
|
|
185
|
+
// went away.
|
|
186
|
+
transcriptDirectoryReady = false;
|
|
187
|
+
if (!transcriptFailures.has(sessionId)) {
|
|
188
|
+
transcriptFailures.add(sessionId);
|
|
189
|
+
logDiagnostic(`recording the transcript of ${sessionId} failed (best-effort): ${error.message}`);
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
/**
|
|
195
|
+
* `write` DIRECTLY, never `notifySessionUpdate`: the recording path would append the replay back into
|
|
196
|
+
* the same file, so every resume would double the history and the next one would double that again —
|
|
197
|
+
* a conversation growing turns it never took.
|
|
198
|
+
*/
|
|
199
|
+
function replaySessionTranscript(sessionId) {
|
|
200
|
+
const file = transcriptFile(sessionId);
|
|
201
|
+
if (!file) return;
|
|
202
|
+
let raw;
|
|
203
|
+
try {
|
|
204
|
+
raw = readFileSync(file, "utf8");
|
|
205
|
+
} catch (error) {
|
|
206
|
+
// A session that has never taken a turn has no file: the empty replay, not a failure.
|
|
207
|
+
if (error.code !== "ENOENT") {
|
|
208
|
+
logDiagnostic(`reading the transcript of ${sessionId} failed (best-effort): ${error.message}`);
|
|
209
|
+
}
|
|
210
|
+
return;
|
|
211
|
+
}
|
|
212
|
+
for (const line of raw.split("\n")) {
|
|
213
|
+
if (!line.trim()) continue;
|
|
214
|
+
let update;
|
|
215
|
+
try {
|
|
216
|
+
update = JSON.parse(line);
|
|
217
|
+
} catch {
|
|
218
|
+
// A truncated final line (the sandbox died mid-append) costs that one frame, never the whole replay.
|
|
219
|
+
continue;
|
|
220
|
+
}
|
|
221
|
+
if (!update || typeof update !== "object") continue;
|
|
222
|
+
write(sessionUpdateFrame(sessionId, update));
|
|
223
|
+
}
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
function endTurn(text) {
|
|
227
|
+
return { stopReason: "end_turn", content: [{ type: "text", text }] };
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
function tail(value, limit) {
|
|
231
|
+
return value.length <= limit ? value : value.slice(value.length - limit);
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
/**
|
|
235
|
+
* `settled` makes a second settle a no-op, so a path that answers and then throws cannot write two
|
|
236
|
+
* frames for one request.
|
|
237
|
+
*/
|
|
238
|
+
function turnResponder(id, errorData, settlement) {
|
|
239
|
+
const settle = (emit) => {
|
|
240
|
+
if (settlement.settled) return;
|
|
241
|
+
settlement.settled = true;
|
|
242
|
+
releasePrompt(settlement);
|
|
243
|
+
emit();
|
|
244
|
+
};
|
|
245
|
+
return {
|
|
246
|
+
succeed: (text) => settle(() => respondResult(id, endTurn(text))),
|
|
247
|
+
fail: (message) => settle(() => respondError(id, SCRIPT_FAILURE_CODE, message, errorData)),
|
|
248
|
+
};
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
// Installation can change the file while this harness lives; only a new spawn reads those bytes.
|
|
252
|
+
let program;
|
|
253
|
+
let programReadError;
|
|
254
|
+
try {
|
|
255
|
+
program = readFileSync(path.join(homedir(), INSTRUCTIONS_FILE), "utf8");
|
|
256
|
+
} catch (error) {
|
|
257
|
+
programReadError = `cannot read instructions file: ${error.message}`;
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
// NO Authorization header is ever attached — the egress broker mints and injects the short-lived agent
|
|
261
|
+
// bearer for the agent-API destination (the agent runtime must never hold credentials).
|
|
262
|
+
function agentApiBaseUrl() {
|
|
263
|
+
const configured = (process.env.PLATFORM_BASE_URL || "").trim().replace(/\/+$/, "");
|
|
264
|
+
if (!configured) {
|
|
265
|
+
throw new Error("PLATFORM_BASE_URL is not set");
|
|
266
|
+
}
|
|
267
|
+
return configured;
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
// The worker declares this on a machine the customer enrolled, and on no machine the platform launched.
|
|
271
|
+
// Presence is the declaration. The worker answers it from that machine's own bootstrap rather than
|
|
272
|
+
// passing a value through, so nothing running inside the machine can declare it of itself.
|
|
273
|
+
const MACHINE_ENROLLED = "SFDK_MACHINE_ENROLLED";
|
|
274
|
+
|
|
275
|
+
function machineIsEnrolled() {
|
|
276
|
+
return (process.env[MACHINE_ENROLLED] || "").trim() !== "";
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
async function platformRequest(method, path, organizationId, body) {
|
|
280
|
+
let response;
|
|
281
|
+
try {
|
|
282
|
+
response = await fetch(`${agentApiBaseUrl()}${path}`, {
|
|
283
|
+
method,
|
|
284
|
+
headers: {
|
|
285
|
+
"Content-Type": "application/json",
|
|
286
|
+
Accept: "application/json",
|
|
287
|
+
"X-Organization-Id": organizationId,
|
|
288
|
+
},
|
|
289
|
+
body: body === undefined ? undefined : JSON.stringify(body),
|
|
290
|
+
signal: AbortSignal.timeout(PLATFORM_REQUEST_TIMEOUT_MS),
|
|
291
|
+
});
|
|
292
|
+
} catch (error) {
|
|
293
|
+
if (error?.name === "TimeoutError" || error?.name === "AbortError") {
|
|
294
|
+
throw new Error(`${method} ${path} timed out after ${PLATFORM_REQUEST_TIMEOUT_MS}ms`);
|
|
295
|
+
}
|
|
296
|
+
// `fetch` says only "fetch failed"; the layer that broke is on `error.cause`. Carried in the MESSAGE
|
|
297
|
+
// because that is what reaches an operator, and re-thrown with `{ cause }` so a local chain still leads
|
|
298
|
+
// to the original.
|
|
299
|
+
const detail = describeFetchFailure(error);
|
|
300
|
+
throw new Error(`${method} ${path} failed: ${error.message}${detail ? ` (${detail})` : ""}`, {
|
|
301
|
+
cause: error,
|
|
302
|
+
});
|
|
303
|
+
}
|
|
304
|
+
// Read to the end so the connection goes back to the pool; only the status is the answer.
|
|
305
|
+
await response.text();
|
|
306
|
+
return { status: response.status, ok: response.ok };
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
// ONE contract, two spellings, because "the OS shell" is not the same program on the two operating
|
|
310
|
+
// systems this family ships on: `bash -c <prompt>` on POSIX, `detached` so the command owns its process
|
|
311
|
+
// GROUP; `powershell.exe … -EncodedCommand <base64 of the UTF-16LE prompt>` on win32, not detached,
|
|
312
|
+
// because that image carries no POSIX shell at all and `bash` there is an unconditional ENOENT. On
|
|
313
|
+
// PowerShell a terminating error exits 1 and an explicit `exit N` propagates N, so the exit-code
|
|
314
|
+
// mapping needs no per-OS arm.
|
|
315
|
+
|
|
316
|
+
/**
|
|
317
|
+
* Windows PowerShell 5.1 decodes its STDIN with the console's OEM code page, and writes its output the
|
|
318
|
+
* same way, so a UTF-8 turn payload arrives mojibaked. Both are process-local settings with no
|
|
319
|
+
* command-line switch, so the harness states them as a fixed preamble ahead of the prompt inside the
|
|
320
|
+
* encoded command. A NESTED PowerShell the prompt itself starts gets its own defaults back — ASCII-
|
|
321
|
+
* safe, and left as a stated residual rather than papered over.
|
|
322
|
+
*/
|
|
323
|
+
const WINDOWS_ENCODING_PREAMBLE =
|
|
324
|
+
"[Console]::InputEncoding = [Console]::OutputEncoding = [System.Text.UTF8Encoding]::new($false); ";
|
|
325
|
+
|
|
326
|
+
/**
|
|
327
|
+
* `-EncodedCommand` rather than `-Command "<prompt>"` removes the quoting layer entirely: base64 of
|
|
328
|
+
* UTF-16LE carries no metacharacters, so no escaping rule of ours can silently run a DIFFERENT
|
|
329
|
+
* command that still exits 0. The cost is Windows' 32767-character command-line ceiling, which that
|
|
330
|
+
* encoding reaches at roughly 12000 prompt characters; past it the spawn error lands on the turn as
|
|
331
|
+
* an ordinary exit-127 failure. `detached` is POSIX-only — on Windows the cancel path walks the
|
|
332
|
+
* process TREE instead — and `cwd` is an option rather than a default, so omitting the key is Node's
|
|
333
|
+
* "inherit this process's directory".
|
|
334
|
+
*/
|
|
335
|
+
function shellInvocation(command, cwd, env) {
|
|
336
|
+
const stdio = ["pipe", "pipe", "pipe"];
|
|
337
|
+
const where = cwd ? { cwd } : {};
|
|
338
|
+
if (!IS_WINDOWS) {
|
|
339
|
+
return {
|
|
340
|
+
file: "bash",
|
|
341
|
+
args: ["-c", command],
|
|
342
|
+
options: { env, stdio, detached: true, ...where },
|
|
343
|
+
};
|
|
344
|
+
}
|
|
345
|
+
const encoded = Buffer.from(`${WINDOWS_ENCODING_PREAMBLE}${command}`, "utf16le").toString("base64");
|
|
346
|
+
return {
|
|
347
|
+
file: "powershell.exe",
|
|
348
|
+
args: ["-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass", "-EncodedCommand", encoded],
|
|
349
|
+
options: { env, stdio, windowsHide: true, ...where },
|
|
350
|
+
};
|
|
351
|
+
}
|
|
352
|
+
|
|
353
|
+
/**
|
|
354
|
+
* POSIX: SIGTERM the whole process GROUP (the command runs `detached`, so the group id is the child's
|
|
355
|
+
* pid); signalling `bash` alone leaves its children running. The guard is the VALUE-shaped
|
|
356
|
+
* `!(pid > 0)`, not a `=== undefined` check, because `process.kill(-0, sig)` signals the CALLER'S OWN
|
|
357
|
+
* process group — this harness process, and with it every session it is multiplexing.
|
|
358
|
+
*
|
|
359
|
+
* win32: `child.kill()` is a `TerminateProcess` of the SHELL alone, so the tree walk is `taskkill /T`,
|
|
360
|
+
* with `/F` because plain `taskkill` posts WM_CLOSE to windows a console job does not have. The
|
|
361
|
+
* liveness probe is a REQUIREMENT there — Windows recycles pids — and its answer is also the CANCEL
|
|
362
|
+
* DISCRIMINATOR: a `TerminateProcess`d process reports an exit CODE and no signal.
|
|
363
|
+
*/
|
|
364
|
+
function terminateCommandTree(child, turn, reason) {
|
|
365
|
+
if (!child || !(child.pid > 0)) return;
|
|
366
|
+
if (!IS_WINDOWS) {
|
|
367
|
+
try {
|
|
368
|
+
process.kill(-child.pid, "SIGTERM");
|
|
369
|
+
} catch {
|
|
370
|
+
try {
|
|
371
|
+
child.kill("SIGTERM");
|
|
372
|
+
} catch (error) {
|
|
373
|
+
logDiagnostic(`failed to signal the command process group (${reason}): ${error.message}`);
|
|
374
|
+
}
|
|
375
|
+
}
|
|
376
|
+
return;
|
|
377
|
+
}
|
|
378
|
+
try {
|
|
379
|
+
process.kill(child.pid, 0);
|
|
380
|
+
} catch {
|
|
381
|
+
return;
|
|
382
|
+
}
|
|
383
|
+
if (turn) turn.treeKilled = true;
|
|
384
|
+
try {
|
|
385
|
+
const killer = spawn("taskkill", ["/T", "/F", "/PID", String(child.pid)], {
|
|
386
|
+
stdio: "ignore",
|
|
387
|
+
windowsHide: true,
|
|
388
|
+
});
|
|
389
|
+
killer.on("error", (error) => {
|
|
390
|
+
logDiagnostic(`failed to run taskkill (${reason}): ${error.message}`);
|
|
391
|
+
});
|
|
392
|
+
} catch (error) {
|
|
393
|
+
logDiagnostic(`failed to run taskkill (${reason}): ${error.message}`);
|
|
394
|
+
}
|
|
395
|
+
}
|
|
396
|
+
|
|
397
|
+
function runCommand({ acpSessionId, command, cwd, organizationId, promptText, turn }) {
|
|
398
|
+
return new Promise((resolve) => {
|
|
399
|
+
let stdoutTail = "";
|
|
400
|
+
let stderrTail = "";
|
|
401
|
+
let settled = false;
|
|
402
|
+
|
|
403
|
+
// The worker already composed this process's whole environment, its session included, so the child
|
|
404
|
+
// adds only the organization, which the worker does not provide. On POSIX `detached` puts the command in
|
|
405
|
+
// its OWN process group so a cancel — or the orphan sweep below — can signal the whole script tree.
|
|
406
|
+
const invocation = shellInvocation(command, cwd, {
|
|
407
|
+
...process.env,
|
|
408
|
+
SFDK_ORGANIZATION_ID: organizationId,
|
|
409
|
+
});
|
|
410
|
+
const child = spawn(invocation.file, invocation.args, invocation.options);
|
|
411
|
+
turn.child = child;
|
|
412
|
+
|
|
413
|
+
// Detaching the stream listeners is part of settling, not an optimization: a backgrounded grandchild
|
|
414
|
+
// (`cmd &` is idiomatic) keeps the pipes open and would otherwise emit `session/update` frames into the
|
|
415
|
+
// NEXT turn's transcript, unreachable by `session/cancel` because that turn is gone.
|
|
416
|
+
const detachStreams = () => {
|
|
417
|
+
for (const stream of [child.stdout, child.stderr]) {
|
|
418
|
+
if (!stream) continue;
|
|
419
|
+
stream.removeAllListeners("data");
|
|
420
|
+
stream.destroy();
|
|
421
|
+
}
|
|
422
|
+
};
|
|
423
|
+
|
|
424
|
+
const finish = (exitCode, signal) => {
|
|
425
|
+
if (settled) return;
|
|
426
|
+
settled = true;
|
|
427
|
+
detachStreams();
|
|
428
|
+
resolve({ exitCode, signal, stdoutTail, stderrTail });
|
|
429
|
+
};
|
|
430
|
+
|
|
431
|
+
const streamTo = (stream, onChunk) => {
|
|
432
|
+
stream.setEncoding("utf8");
|
|
433
|
+
stream.on("data", (chunk) => {
|
|
434
|
+
onChunk(chunk);
|
|
435
|
+
emitOutput(turn, acpSessionId, chunk);
|
|
436
|
+
});
|
|
437
|
+
};
|
|
438
|
+
streamTo(child.stdout, (chunk) => {
|
|
439
|
+
stdoutTail = tail(stdoutTail + chunk, STDOUT_TAIL_CONTENT);
|
|
440
|
+
});
|
|
441
|
+
streamTo(child.stderr, (chunk) => {
|
|
442
|
+
stderrTail = tail(stderrTail + chunk, STDERR_TAIL_ERROR);
|
|
443
|
+
});
|
|
444
|
+
|
|
445
|
+
// A signalled child reports code null; map it to a conventional non-zero status so the exit-code
|
|
446
|
+
// contract has a single shape.
|
|
447
|
+
const statusOf = (code, signal) => (code === null ? (signal ? 128 : 1) : code);
|
|
448
|
+
|
|
449
|
+
child.on("error", (error) => {
|
|
450
|
+
stderrTail = tail(`${stderrTail}${error.message}\n`, STDERR_TAIL_ERROR);
|
|
451
|
+
finish(127, null);
|
|
452
|
+
});
|
|
453
|
+
// `close` (stdio drained) is the fidelity-preserving settle, but a command that leaves a child holding
|
|
454
|
+
// the pipes open would never reach it — so `exit` starts a short flush grace and then settles
|
|
455
|
+
// regardless, killing the orphaned group on the way out.
|
|
456
|
+
child.on("close", (code, signal) => finish(statusOf(code, signal), signal));
|
|
457
|
+
child.on("exit", (code, signal) => {
|
|
458
|
+
setTimeout(() => {
|
|
459
|
+
if (settled) return;
|
|
460
|
+
terminateCommandTree(child, null, "post-exit orphan sweep");
|
|
461
|
+
finish(statusOf(code, signal), signal);
|
|
462
|
+
}, STDIO_FLUSH_GRACE_MS);
|
|
463
|
+
});
|
|
464
|
+
|
|
465
|
+
// A command that ignores stdin closes the pipe early; EPIPE there is expected, not a turn failure.
|
|
466
|
+
child.stdin.on("error", () => {});
|
|
467
|
+
if (promptText) child.stdin.write(promptText);
|
|
468
|
+
child.stdin.end();
|
|
469
|
+
});
|
|
470
|
+
}
|
|
471
|
+
|
|
472
|
+
/** Concatenate the prompt's text content blocks verbatim (no marker parsing). */
|
|
473
|
+
function promptTextOf(params) {
|
|
474
|
+
const prompt = params?.prompt;
|
|
475
|
+
if (typeof prompt === "string") return prompt;
|
|
476
|
+
if (!Array.isArray(prompt)) return "";
|
|
477
|
+
return prompt
|
|
478
|
+
.filter((block) => block && block.type === "text" && typeof block.text === "string")
|
|
479
|
+
.map((block) => block.text)
|
|
480
|
+
.join("");
|
|
481
|
+
}
|
|
482
|
+
|
|
483
|
+
/**
|
|
484
|
+
* Checked field by field against the pinned ACP schema (`fwp/schema/acp/acp-schema.json`).
|
|
485
|
+
* `agentCapabilities.loadSession` is a boolean that DEFAULTS TO FALSE, and `LoadSessionRequest` is
|
|
486
|
+
* "Only available if the Agent supports the `loadSession` capability" — so declaring it is what makes a
|
|
487
|
+
* client send the request at all. `promptCapabilities` stays absent, which is the schema's all-false
|
|
488
|
+
* default and the truth: an image, audio or embedded-context block would be dropped.
|
|
489
|
+
*/
|
|
490
|
+
function handleInitialize(id) {
|
|
491
|
+
respondResult(id, {
|
|
492
|
+
protocolVersion: 1,
|
|
493
|
+
agentCapabilities: { loadSession: true },
|
|
494
|
+
agentInfo: { name: HARNESS_NAME, version: HARNESS_VERSION },
|
|
495
|
+
});
|
|
496
|
+
}
|
|
497
|
+
|
|
498
|
+
function handleSessionNew(id, params) {
|
|
499
|
+
const sessionId = `script-session-${randomUUID()}`;
|
|
500
|
+
const state = sessionState(sessionId);
|
|
501
|
+
state.cwd = declaredCwd(params);
|
|
502
|
+
state.context = params?._meta?.sfdk;
|
|
503
|
+
respondResult(id, { sessionId });
|
|
504
|
+
}
|
|
505
|
+
|
|
506
|
+
/**
|
|
507
|
+
* `session/load` answers this session's REPLAY: the platform counts the `session/update` frames emitted
|
|
508
|
+
* between this request and its response, and zero frames for a session with a prior completed turn
|
|
509
|
+
* downgrades the resume from RESUMED to RECONSTRUCTED. Still no execution and no platform call.
|
|
510
|
+
*/
|
|
511
|
+
function handleSessionLoad(id, params) {
|
|
512
|
+
const sessionId = params?.sessionId;
|
|
513
|
+
if (!sessionId) {
|
|
514
|
+
respondError(id, INVALID_PARAMS_CODE, "missing sessionId in params");
|
|
515
|
+
return;
|
|
516
|
+
}
|
|
517
|
+
// A revival carries the same anchored `cwd` the original `session/new` did, and the bridge maps the
|
|
518
|
+
// field on BOTH methods.
|
|
519
|
+
const state = sessionState(sessionId);
|
|
520
|
+
state.cwd = declaredCwd(params);
|
|
521
|
+
state.context = params?._meta?.sfdk;
|
|
522
|
+
replaySessionTranscript(sessionId);
|
|
523
|
+
respondResult(id, { sessionId });
|
|
524
|
+
}
|
|
525
|
+
|
|
526
|
+
/**
|
|
527
|
+
* Unconditional on purpose: whether the command is still running is not knowable here without racing
|
|
528
|
+
* node's `waitpid`, and signalling an already-exited group is a no-op that still reaches exactly the
|
|
529
|
+
* orphaned grandchildren the post-exit sweep would have swept. Whether the turn ANSWERS cancelled is
|
|
530
|
+
* decided later from the command's observed exit shape, not from this flag.
|
|
531
|
+
*/
|
|
532
|
+
function handleSessionCancel(id, params) {
|
|
533
|
+
const sessionId = params?.sessionId;
|
|
534
|
+
const turn = sessions.get(sessionId)?.turn;
|
|
535
|
+
if (turn && turn.child) {
|
|
536
|
+
turn.cancelled = true;
|
|
537
|
+
terminateCommandTree(turn.child, turn, `cancel of ${sessionId}`);
|
|
538
|
+
}
|
|
539
|
+
if (isRoutable(id)) respondResult(id, {});
|
|
540
|
+
}
|
|
541
|
+
|
|
542
|
+
// The session's turn runs from its prompt's arrival until its answer is written.
|
|
543
|
+
function releasePrompt(settlement) {
|
|
544
|
+
if (settlement.state.prompting === settlement) settlement.state.prompting = null;
|
|
545
|
+
}
|
|
546
|
+
|
|
547
|
+
async function handleSessionPrompt(id, params) {
|
|
548
|
+
const acpSessionId = params?.sessionId;
|
|
549
|
+
if (!acpSessionId) {
|
|
550
|
+
respondError(id, INVALID_PARAMS_CODE, "missing sessionId in params");
|
|
551
|
+
return;
|
|
552
|
+
}
|
|
553
|
+
const state = sessionState(acpSessionId);
|
|
554
|
+
// One prompt at a time per session: a second one run beside the first would execute the command twice
|
|
555
|
+
// at once, and overwriting `state.turn` would leave the first unreachable by a cancel.
|
|
556
|
+
if (state.prompting) {
|
|
557
|
+
respondError(id, TURN_RUNNING_CODE, `a turn is already running for session ${acpSessionId}`);
|
|
558
|
+
return;
|
|
559
|
+
}
|
|
560
|
+
// Carried through every path that can answer the turn, so exactly one answer is written per request.
|
|
561
|
+
const settlement = { state, settled: false };
|
|
562
|
+
state.prompting = settlement;
|
|
563
|
+
try {
|
|
564
|
+
await runPrompt(id, params, acpSessionId, state, settlement);
|
|
565
|
+
} finally {
|
|
566
|
+
releasePrompt(settlement);
|
|
567
|
+
}
|
|
568
|
+
}
|
|
569
|
+
|
|
570
|
+
async function runPrompt(id, params, acpSessionId, state, settlement) {
|
|
571
|
+
const { fail } = turnResponder(id, undefined, settlement);
|
|
572
|
+
|
|
573
|
+
const command = program;
|
|
574
|
+
const context = state.context;
|
|
575
|
+
const platformSessionId = context?.sessionId;
|
|
576
|
+
const organizationId = context?.organizationId;
|
|
577
|
+
const cwd = state.cwd;
|
|
578
|
+
if (programReadError || typeof command !== "string" || command.trim() === "") {
|
|
579
|
+
fail(programReadError || "agent.instructions is empty — the script runtime has nothing to execute");
|
|
580
|
+
return;
|
|
581
|
+
}
|
|
582
|
+
if (!context || Array.isArray(context) ||
|
|
583
|
+
![platformSessionId, organizationId].every(value =>
|
|
584
|
+
typeof value === "string" && value.trim() !== "" && !/[\x00-\x1f\x7f-\x9f]/.test(value))) {
|
|
585
|
+
fail("handshake context requires nonblank sessionId and organizationId without control characters");
|
|
586
|
+
return;
|
|
587
|
+
}
|
|
588
|
+
try {
|
|
589
|
+
// A missing base URL must fail before execution; otherwise a retry can repeat unclaimed work.
|
|
590
|
+
agentApiBaseUrl();
|
|
591
|
+
} catch (error) {
|
|
592
|
+
fail(error.message);
|
|
593
|
+
return;
|
|
594
|
+
}
|
|
595
|
+
|
|
596
|
+
const turn = { child: null, cancelled: false, treeKilled: false, emittedBytes: 0, outputTruncated: false };
|
|
597
|
+
state.turn = turn;
|
|
598
|
+
let outcome;
|
|
599
|
+
try {
|
|
600
|
+
outcome = await runCommand({
|
|
601
|
+
acpSessionId,
|
|
602
|
+
command,
|
|
603
|
+
cwd,
|
|
604
|
+
organizationId,
|
|
605
|
+
promptText: promptTextOf(params),
|
|
606
|
+
turn,
|
|
607
|
+
});
|
|
608
|
+
} finally {
|
|
609
|
+
if (state.turn === turn) state.turn = null;
|
|
610
|
+
}
|
|
611
|
+
|
|
612
|
+
const { exitCode, signal, stdoutTail, stderrTail } = outcome;
|
|
613
|
+
const answerText = stdoutTail ? `exit ${exitCode}\n${stdoutTail}` : `exit ${exitCode}`;
|
|
614
|
+
// The accumulator already caps at STDERR_TAIL_ERROR, so this is the tail.
|
|
615
|
+
const errorData = { stderrTail };
|
|
616
|
+
|
|
617
|
+
// "Cancelled" is an observed FACT about the kill, never the arrival of the cancel message: deciding on
|
|
618
|
+
// the flag alone raced node's `waitpid` — a cancel dispatched between the script's `exit 0` and the
|
|
619
|
+
// reap failed a turn whose script had SUCCEEDED, with zero claims. Each OS supplies the
|
|
620
|
+
// reap-order-independent fact it can: on POSIX the EXIT SHAPE, since a signal-killed command reports
|
|
621
|
+
// `code === null, signal === "SIGTERM"`; on win32 the KILL's own answer, since `terminateCommandTree`
|
|
622
|
+
// sets `treeKilled` only after `GetExitCodeProcess` proved the shell was still running.
|
|
623
|
+
if (turn.cancelled && (signal || turn.treeKilled)) {
|
|
624
|
+
// A cancelled turn claims nothing.
|
|
625
|
+
turnResponder(id, errorData, settlement).fail(`script cancelled (${signal ?? `exit ${exitCode}`})`);
|
|
626
|
+
return;
|
|
627
|
+
}
|
|
628
|
+
|
|
629
|
+
try {
|
|
630
|
+
await claimPlatformState({
|
|
631
|
+
id,
|
|
632
|
+
settlement,
|
|
633
|
+
platformSessionId,
|
|
634
|
+
organizationId,
|
|
635
|
+
exitCode,
|
|
636
|
+
stderrTail,
|
|
637
|
+
answerText,
|
|
638
|
+
errorData,
|
|
639
|
+
});
|
|
640
|
+
} catch (error) {
|
|
641
|
+
turnResponder(id, errorData, settlement).fail(`platform claim failed: ${error.message}`);
|
|
642
|
+
}
|
|
643
|
+
}
|
|
644
|
+
|
|
645
|
+
/**
|
|
646
|
+
* Sets the flat outcome claim, which is the handled failure path too, so a non-zero exit still answers
|
|
647
|
+
* `end_turn`. A `409` is benign: the session has ended, and there is nothing left to claim.
|
|
648
|
+
*/
|
|
649
|
+
async function claimPlatformState({
|
|
650
|
+
id,
|
|
651
|
+
settlement,
|
|
652
|
+
platformSessionId,
|
|
653
|
+
organizationId,
|
|
654
|
+
exitCode,
|
|
655
|
+
stderrTail,
|
|
656
|
+
answerText,
|
|
657
|
+
errorData,
|
|
658
|
+
}) {
|
|
659
|
+
const { succeed, fail } = turnResponder(id, errorData, settlement);
|
|
660
|
+
|
|
661
|
+
// On a machine the customer enrolled there is no edge of ours, so nothing authorizes a call to the
|
|
662
|
+
// platform's API and every claim here would come back refused — failing a turn whose script succeeded
|
|
663
|
+
// and whose answer is already on the session. The answer is then the whole of what the turn reports.
|
|
664
|
+
// Read off the worker's declaration and not off a missing edge stamp: a machine the platform launched
|
|
665
|
+
// can be missing that stamp too, and there the refusal is a deployment fault to surface rather than a
|
|
666
|
+
// turn to settle quietly.
|
|
667
|
+
if (machineIsEnrolled()) {
|
|
668
|
+
logDiagnostic(
|
|
669
|
+
`${MACHINE_ENROLLED} is set, so this machine is one the platform did not launch and nothing ` +
|
|
670
|
+
`authorizes its calls to the platform: this turn claims no session state and settles on its answer`,
|
|
671
|
+
);
|
|
672
|
+
succeed(answerText);
|
|
673
|
+
return;
|
|
674
|
+
}
|
|
675
|
+
|
|
676
|
+
const body =
|
|
677
|
+
exitCode === 0
|
|
678
|
+
? { outcome: "ACHIEVED", summary: "exit 0" }
|
|
679
|
+
: { outcome: "FAILED", summary: `exit ${exitCode}: ${tail(stderrTail, STDERR_TAIL_SUMMARY)}` };
|
|
680
|
+
const sessionPath = `/sessions/${encodeURIComponent(platformSessionId)}`;
|
|
681
|
+
const response = await platformRequest("PATCH", sessionPath, organizationId, body);
|
|
682
|
+
if (!response.ok && response.status !== 409) {
|
|
683
|
+
fail(`claim rejected: ${response.status}`);
|
|
684
|
+
return;
|
|
685
|
+
}
|
|
686
|
+
succeed(answerText);
|
|
687
|
+
}
|
|
688
|
+
|
|
689
|
+
// Dispatch is fire-and-forget: a `session/prompt` awaits its command inside its own async task, so no
|
|
690
|
+
// other session is head-of-line blocked.
|
|
691
|
+
function isRoutable(id) {
|
|
692
|
+
return id !== undefined && id !== null;
|
|
693
|
+
}
|
|
694
|
+
|
|
695
|
+
async function dispatch(line) {
|
|
696
|
+
const trimmed = line.trim();
|
|
697
|
+
if (!trimmed) return;
|
|
698
|
+
let message;
|
|
699
|
+
try {
|
|
700
|
+
message = JSON.parse(trimmed);
|
|
701
|
+
} catch (error) {
|
|
702
|
+
logDiagnostic(`ignoring a non-JSON stdin line: ${error.message}`);
|
|
703
|
+
return;
|
|
704
|
+
}
|
|
705
|
+
if (!message || typeof message !== "object" || typeof message.method !== "string") {
|
|
706
|
+
// A response to a request the harness never makes — nothing to do.
|
|
707
|
+
return;
|
|
708
|
+
}
|
|
709
|
+
|
|
710
|
+
const { id, method, params } = message;
|
|
711
|
+
// An id-less request is unroutable: its answer is dropped on the floor and the frame the harness wrote
|
|
712
|
+
// is noise on a pipe the bridge is scanning. So the guard is DISPATCH-WIDE, not per-method.
|
|
713
|
+
// `session/cancel` is the one method exempt by contract: it is legitimately a notification, and it
|
|
714
|
+
// answers only when addressed.
|
|
715
|
+
if (method !== "session/cancel" && !isRoutable(id)) {
|
|
716
|
+
logDiagnostic(`ignoring an id-less ${method} (its answer would be unroutable)`);
|
|
717
|
+
return;
|
|
718
|
+
}
|
|
719
|
+
try {
|
|
720
|
+
switch (method) {
|
|
721
|
+
case "initialize":
|
|
722
|
+
handleInitialize(id);
|
|
723
|
+
return;
|
|
724
|
+
case "session/new":
|
|
725
|
+
handleSessionNew(id, params);
|
|
726
|
+
return;
|
|
727
|
+
case "session/load":
|
|
728
|
+
handleSessionLoad(id, params);
|
|
729
|
+
return;
|
|
730
|
+
case "session/prompt":
|
|
731
|
+
await handleSessionPrompt(id, params);
|
|
732
|
+
return;
|
|
733
|
+
case "session/cancel":
|
|
734
|
+
handleSessionCancel(id, params);
|
|
735
|
+
return;
|
|
736
|
+
default:
|
|
737
|
+
respondError(id, METHOD_NOT_FOUND_CODE, `Unknown method: ${method}`);
|
|
738
|
+
}
|
|
739
|
+
} catch (error) {
|
|
740
|
+
logDiagnostic(`unhandled failure in ${method}: ${error.stack || error.message}`);
|
|
741
|
+
if (isRoutable(id)) {
|
|
742
|
+
respondError(id, INTERNAL_ERROR_CODE, `harness failure: ${error.message}`);
|
|
743
|
+
}
|
|
744
|
+
}
|
|
745
|
+
}
|
|
746
|
+
|
|
747
|
+
process.stdout.on("error", (error) => {
|
|
748
|
+
if (error.code === "EPIPE") process.exit(0);
|
|
749
|
+
});
|
|
750
|
+
|
|
751
|
+
const stdinLines = createInterface({ input: process.stdin });
|
|
752
|
+
stdinLines.on("line", (line) => {
|
|
753
|
+
void dispatch(line);
|
|
754
|
+
});
|
|
755
|
+
stdinLines.on("close", () => {
|
|
756
|
+
process.exit(0);
|
|
757
|
+
});
|
package/worker.exe
ADDED