@evomap/evolver-cli 2.0.42 → 2.0.44
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/dist/autoRecall.d.ts +24 -5
- package/dist/autoRecall.js +233 -12
- package/dist/autoexec.d.ts +69 -10
- package/dist/autoexec.js +847 -137
- package/dist/cli.d.ts +1 -1
- package/dist/cli.js +71 -26
- package/dist/cliContracts.js +29 -7
- package/dist/cliEntry.d.ts +3 -0
- package/dist/cliEntry.js +63 -0
- package/dist/commandCatalog.d.ts +1 -0
- package/dist/commandCatalog.js +1 -0
- package/dist/contextDelivery.d.ts +12 -0
- package/dist/contextDelivery.js +139 -0
- package/dist/cycleConsumer.js +9 -1
- package/dist/dispatch.js +6 -0
- package/dist/feedbackOutbox.d.ts +96 -0
- package/dist/feedbackOutbox.js +510 -0
- package/dist/feedbackOutboxCli.d.ts +7 -0
- package/dist/feedbackOutboxCli.js +208 -0
- package/dist/index.d.ts +3 -0
- package/dist/index.js +286 -69
- package/dist/lifecycle.d.ts +18 -0
- package/dist/lifecycle.js +130 -3
- package/dist/lifecycleBootstrapTransaction.js +1 -6
- package/dist/liveStatus.d.ts +27 -0
- package/dist/liveStatus.js +197 -0
- package/dist/outboxLock.d.ts +7 -0
- package/dist/outboxLock.js +141 -0
- package/dist/promptRecallHook.d.ts +7 -22
- package/dist/promptRecallHook.js +20 -489
- package/dist/promptRecallRuntime.d.ts +24 -0
- package/dist/promptRecallRuntime.js +678 -0
- package/dist/promptRecallShared.d.ts +18 -0
- package/dist/promptRecallShared.js +119 -0
- package/dist/recall.js +27 -6
- package/dist/runtimeTelemetry.d.ts +9 -0
- package/dist/runtimeTelemetry.js +16 -0
- package/dist/sessionIngest.d.ts +25 -2
- package/dist/sessionIngest.js +196 -32
- package/dist/setupHooks.js +63 -13
- package/dist/setupHooksLifecycle.js +39 -17
- package/dist/skill2gep.d.ts +11 -0
- package/dist/skill2gep.js +23 -3
- package/dist/solo/mode.js +4 -0
- package/dist/taskCommitments.d.ts +4 -2
- package/dist/taskCommitments.js +208 -114
- package/dist/taskOutcomeOutbox.d.ts +83 -0
- package/dist/taskOutcomeOutbox.js +553 -0
- package/dist/workflowRuntime.js +12 -0
- package/package.json +11 -7
package/dist/index.js
CHANGED
|
@@ -5,7 +5,7 @@ import { assetstore, algo, signals, material as materialNs } from '@evomap/evolv
|
|
|
5
5
|
import { loadPriceTable } from '@evomap/evolver-adapter-public';
|
|
6
6
|
import { loadEnvFileFromEnv } from '@evomap/evolver-mcp';
|
|
7
7
|
import { injectEvent, makeInjectEmitter } from './autoexec.js';
|
|
8
|
-
import { listApprovedGenes, pendingGeneReviewRecords,
|
|
8
|
+
import { listApprovedGenes, pendingGeneReviewRecords, reviewLedgerForStore } from './reviewFilter.js';
|
|
9
9
|
import { ADAPTERS, parseJsonlLines } from '@evomap/evolver-runtime-adapters';
|
|
10
10
|
import { assessGeneDraft } from './distillPrimitives.js';
|
|
11
11
|
import { assessDraftAdmissionFromStore } from './distillAdmission.js';
|
|
@@ -22,7 +22,10 @@ import { formatAntiGeneEvidenceAction, formatAntiGeneEvidenceSummary, summarizeA
|
|
|
22
22
|
import { buildRuntimeSessionMaterialSnapshot } from './materialSnapshot.js';
|
|
23
23
|
import { maybeEmitNonGitWorkspaceNotice } from './nonGitWorkspaceNotice.js';
|
|
24
24
|
import { asGeneCandidate, parseDistillOutput } from './autoDistillLlm.js';
|
|
25
|
-
import { runPromptRecallHook } from './promptRecallHook.js';
|
|
25
|
+
import { runPromptRecallHook, wrapGeneContext } from './promptRecallHook.js';
|
|
26
|
+
import { deliverContextOutput, waitContextDelivery } from './contextDelivery.js';
|
|
27
|
+
import { withContextReadDiagnostics } from '@evomap/evolver-core/prompt-recall';
|
|
28
|
+
import { writeContextReadDiagnostic } from './promptRecallShared.js';
|
|
26
29
|
import { INGEST_CONSUMER_GROUP, recordSessionMaterial, resolveIngestDeps, toMaterialSourceAgent, } from './sessionIngest.js';
|
|
27
30
|
export { runSessionIngestTick, scanSessionDirs, } from './sessionIngest.js';
|
|
28
31
|
/** Minimal `--flag value` parser (last wins); bare positionals are ignored. */
|
|
@@ -69,6 +72,7 @@ export function cliUsage() {
|
|
|
69
72
|
'',
|
|
70
73
|
'Commands:',
|
|
71
74
|
...renderCommandGroups(),
|
|
75
|
+
' status --live Read-only runtime/IPC/loop diagnostics (default status is historical)',
|
|
72
76
|
'',
|
|
73
77
|
'Run evolver <command> --help for command-specific options.',
|
|
74
78
|
'',
|
|
@@ -1461,7 +1465,7 @@ export function formatGeneInjectionLine(g) {
|
|
|
1461
1465
|
return `- ${id}${cat ? ` [${cat}]` : ''}${hint ? `: ${hint.slice(0, 160)}` : ''}`;
|
|
1462
1466
|
}
|
|
1463
1467
|
function sessionContentMode(argv) {
|
|
1464
|
-
let value = process.env['EVOLVER_SESSION_INJECT_CONTENT'] ?? '
|
|
1468
|
+
let value = process.env['EVOLVER_SESSION_INJECT_CONTENT'] ?? 'context';
|
|
1465
1469
|
for (let index = 1; index < argv.length; index++) {
|
|
1466
1470
|
const arg = argv[index];
|
|
1467
1471
|
if (arg === '--content')
|
|
@@ -1469,7 +1473,7 @@ function sessionContentMode(argv) {
|
|
|
1469
1473
|
else if (arg.startsWith('--content='))
|
|
1470
1474
|
value = arg.slice('--content='.length);
|
|
1471
1475
|
}
|
|
1472
|
-
return value === 'summary' || value === 'strategy' ? value : undefined;
|
|
1476
|
+
return value === 'summary' || value === 'strategy' || value === 'context' ? value : undefined;
|
|
1473
1477
|
}
|
|
1474
1478
|
/** 整条策略作为预算原子单元;不在句中截断,也不把缺失策略当作已经送达。 */
|
|
1475
1479
|
function renderSessionGene(g, mode, maxChars) {
|
|
@@ -1601,6 +1605,71 @@ async function readHookSessionId(read) {
|
|
|
1601
1605
|
return undefined;
|
|
1602
1606
|
}
|
|
1603
1607
|
}
|
|
1608
|
+
/** A prompt-time provider owns its operation until its terminal receipt has
|
|
1609
|
+
* settled. A deadline only stops waiting for a result; it cannot make a custom
|
|
1610
|
+
* callback's external work disappear. A malformed factory keeps admission held
|
|
1611
|
+
* because it may have dispatched before failing to return its owner. */
|
|
1612
|
+
async function readSessionStartSnapshotV1(store, deadlineAt) {
|
|
1613
|
+
if (!assetstore.isBuiltInPromptProvider(store))
|
|
1614
|
+
throw new Error('unsupported_unsupervised_prompt_provider_v1');
|
|
1615
|
+
const begin = store.beginPromptGeneSnapshotV1;
|
|
1616
|
+
if (typeof begin !== 'function')
|
|
1617
|
+
throw new Error('unsupported_prompt_gene_snapshot_v1');
|
|
1618
|
+
if (!Number.isFinite(deadlineAt) || Date.now() >= deadlineAt)
|
|
1619
|
+
throw new Error('snapshot_aborted');
|
|
1620
|
+
const release = assetstore.acquireContextRead(store);
|
|
1621
|
+
const controller = new AbortController();
|
|
1622
|
+
let rejectAbort;
|
|
1623
|
+
const deadline = new Promise((_, reject) => { rejectAbort = reject; });
|
|
1624
|
+
const abort = () => { controller.abort(); rejectAbort(new Error('snapshot_aborted')); };
|
|
1625
|
+
const timer = setTimeout(abort, Math.max(0, Math.min(0x7fffffff, deadlineAt - Date.now())));
|
|
1626
|
+
let operation;
|
|
1627
|
+
let terminal = false;
|
|
1628
|
+
let settlement;
|
|
1629
|
+
const settle = () => {
|
|
1630
|
+
// A cleanup failure does not license replaying an external operation or
|
|
1631
|
+
// invoking a second, potentially non-idempotent cleanup callback.
|
|
1632
|
+
settlement ??= Promise.resolve().then(() => operation.cancelAndSettle());
|
|
1633
|
+
return settlement;
|
|
1634
|
+
};
|
|
1635
|
+
try {
|
|
1636
|
+
if (!assetstore.isBuiltInPromptProvider(store))
|
|
1637
|
+
throw new Error('unsupported_unsupervised_prompt_provider_v1');
|
|
1638
|
+
operation = begin.call(store, { deadlineAt, signal: controller.signal });
|
|
1639
|
+
if (!operation || operation.version !== 1 || typeof operation.cancelAndSettle !== 'function'
|
|
1640
|
+
|| !operation.result || typeof operation.result.then !== 'function') {
|
|
1641
|
+
throw new Error('invalid_prompt_gene_snapshot_operation_v1');
|
|
1642
|
+
}
|
|
1643
|
+
if (Date.now() >= deadlineAt)
|
|
1644
|
+
abort();
|
|
1645
|
+
const snapshot = await Promise.race([operation.result, deadline]);
|
|
1646
|
+
await settle();
|
|
1647
|
+
terminal = true;
|
|
1648
|
+
if (controller.signal.aborted || Date.now() >= deadlineAt)
|
|
1649
|
+
throw new Error('snapshot_aborted');
|
|
1650
|
+
return snapshot;
|
|
1651
|
+
}
|
|
1652
|
+
catch (error) {
|
|
1653
|
+
if (operation?.version === 1 && typeof operation.cancelAndSettle === 'function' && !terminal) {
|
|
1654
|
+
try {
|
|
1655
|
+
await settle();
|
|
1656
|
+
terminal = true;
|
|
1657
|
+
}
|
|
1658
|
+
catch (cleanup) {
|
|
1659
|
+
if (cleanup === error)
|
|
1660
|
+
throw cleanup;
|
|
1661
|
+
throw new AggregateError([error, cleanup], 'prompt snapshot cleanup unconfirmed');
|
|
1662
|
+
}
|
|
1663
|
+
}
|
|
1664
|
+
throw error;
|
|
1665
|
+
}
|
|
1666
|
+
finally {
|
|
1667
|
+
clearTimeout(timer);
|
|
1668
|
+
controller.abort();
|
|
1669
|
+
if (terminal)
|
|
1670
|
+
release();
|
|
1671
|
+
}
|
|
1672
|
+
}
|
|
1604
1673
|
/**
|
|
1605
1674
|
* `evolver inject session-start`: the SessionStart hook entrypoint (the command every installer registers).
|
|
1606
1675
|
* It selects the eligible local genes, composes the SessionStart injection WITH the value recap (#113) through
|
|
@@ -1616,6 +1685,12 @@ async function readHookSessionId(read) {
|
|
|
1616
1685
|
* but emitInject swallows every error, so a sink failure can never break or block the attribution path.
|
|
1617
1686
|
*/
|
|
1618
1687
|
export async function runInject(argv, deps = {}) {
|
|
1688
|
+
const run = () => assetstore.withSnapshotReadInvocation(() => runInjectOwned(argv, deps));
|
|
1689
|
+
if (argv[0] !== 'session-start' || process.env['EVOLVER_CONTEXT_STAGE_DIAGNOSTICS'] !== '1')
|
|
1690
|
+
return run();
|
|
1691
|
+
return withContextReadDiagnostics(true, run, writeContextReadDiagnostic);
|
|
1692
|
+
}
|
|
1693
|
+
async function runInjectOwned(argv, deps) {
|
|
1619
1694
|
const sub = argv[0];
|
|
1620
1695
|
if (sub === 'prompt-recall') {
|
|
1621
1696
|
return runPromptRecallHook(argv.slice(1), {
|
|
@@ -1623,15 +1698,17 @@ export async function runInject(argv, deps = {}) {
|
|
|
1623
1698
|
...(deps.review ? { review: deps.review } : {}),
|
|
1624
1699
|
...(deps.provenance ? { provenance: deps.provenance } : {}),
|
|
1625
1700
|
...(deps.readHookInput ? { readHookInput: deps.readHookInput } : {}),
|
|
1701
|
+
...(deps.stdout ? { stdout: deps.stdout } : {}),
|
|
1702
|
+
...(deps.ingestor ? { ingestor: deps.ingestor } : {}),
|
|
1626
1703
|
});
|
|
1627
1704
|
}
|
|
1628
1705
|
if (sub !== 'session-start') {
|
|
1629
|
-
process.stderr.write('用法: evolver inject session-start [--content=summary|strategy] | evolver inject prompt-recall --hook-stdin\n');
|
|
1706
|
+
process.stderr.write('用法: evolver inject session-start [--content=context|summary|strategy] | evolver inject prompt-recall --hook-stdin\n');
|
|
1630
1707
|
return sub === undefined ? 0 : 1;
|
|
1631
1708
|
}
|
|
1632
1709
|
const contentMode = sessionContentMode(argv);
|
|
1633
1710
|
if (!contentMode) {
|
|
1634
|
-
process.stderr.write('inject session-start: content必须为summary或strategy;未执行注入。\n');
|
|
1711
|
+
process.stderr.write('inject session-start: content必须为context、summary或strategy;未执行注入。\n');
|
|
1635
1712
|
return 1;
|
|
1636
1713
|
}
|
|
1637
1714
|
const fromHookStdin = argv.includes('--hook-stdin');
|
|
@@ -1651,92 +1728,221 @@ export async function runInject(argv, deps = {}) {
|
|
|
1651
1728
|
maybeEmitNonGitWorkspaceNotice(deps.nonGitNotice);
|
|
1652
1729
|
}
|
|
1653
1730
|
const store = deps.store ?? new assetstore.LocalJsonlProvider(events.assetsDir());
|
|
1731
|
+
try {
|
|
1732
|
+
assetstore.assertPromptProviderNotProxy(store);
|
|
1733
|
+
if (contentMode === 'context' && !assetstore.isBuiltInPromptProvider(store))
|
|
1734
|
+
throw new Error('unsupported_unsupervised_prompt_provider_v1');
|
|
1735
|
+
}
|
|
1736
|
+
catch {
|
|
1737
|
+
process.stderr.write('inject session-start: 不支持未受监管的资产库;未执行注入。\n');
|
|
1738
|
+
return 1;
|
|
1739
|
+
}
|
|
1654
1740
|
const ingestor = deps.ingestor ?? new events.Ingestor({ path: deps.eventsPath ?? events.rootEventsPath() });
|
|
1655
|
-
|
|
1656
|
-
|
|
1741
|
+
if (contentMode === 'context' && ingestor.recoverContextDeliveries)
|
|
1742
|
+
await waitContextDelivery(Promise.resolve().then(() => ingestor.recoverContextDeliveries({ deadlineAt: Date.now() + 100 })).catch(() => undefined), 120);
|
|
1743
|
+
const localDir = assetstore.LocalJsonlProvider.isBuiltInPromptReader(store)
|
|
1744
|
+
? Object.getOwnPropertyDescriptor(store, 'baseDir')?.value : undefined;
|
|
1745
|
+
const sidecarDir = typeof localDir === 'string' ? localDir : events.assetsDir();
|
|
1746
|
+
const review = deps.review ?? new assetstore.ReviewLedger(sidecarDir);
|
|
1747
|
+
const provenance = deps.provenance ?? new assetstore.ProvenanceStore(sidecarDir);
|
|
1657
1748
|
const maxGenes = process.env['EVOLVER_BENCHMARK_ID'] !== undefined ? Math.min(deps.maxGenes ?? 8, 8) : (deps.maxGenes ?? 8);
|
|
1658
1749
|
const hardCap = deps.tokenBudgetHardCap ?? 8000;
|
|
1750
|
+
// Recap and optional hook input have their own preparation costs. Complete them before starting
|
|
1751
|
+
// the single context deadline shared by snapshot selection, qualification, and case assembly.
|
|
1752
|
+
const now = deps.now ? deps.now() : Date.now();
|
|
1753
|
+
const traces = ops.readTraceRecords(deps.tracesDir ?? events.tracesDir());
|
|
1754
|
+
const evts = readEvents(deps.eventsPath ?? events.rootEventsPath());
|
|
1755
|
+
const prices = deps.prices ?? loadPriceTable();
|
|
1756
|
+
const summary = ops.loadValueSummary({ traces, events: evts, prices, referenceScope: reference.referenceScopeForEventsPath(deps.eventsPath ?? events.rootEventsPath()) }, ops.windowFromSpec('7d', now));
|
|
1757
|
+
// Plain CLI calls never read stdin; installed hooks opt in explicitly (#205).
|
|
1758
|
+
const sessionId = deps.sessionId ?? ((fromHookStdin || deps.readHookInput) ? await readHookSessionId(deps.readHookInput) : undefined);
|
|
1659
1759
|
// Gene pool → injection candidates: the most recent TRUSTED + REVIEW-APPROVED local genes (bounded), rendered as
|
|
1660
1760
|
// compact hint lines. The provenance gate keeps untrusted hub assets out until promotion; the review gate (A2a)
|
|
1661
1761
|
// keeps auto-distilled UNPROVEN drafts out until approval.
|
|
1662
1762
|
let sourceQualifications;
|
|
1663
|
-
const
|
|
1664
|
-
|
|
1665
|
-
|
|
1666
|
-
|
|
1763
|
+
const contextDeadlineAt = Date.now() + Math.max(0, Math.min(60000, deps.contextTimeoutMs ?? 1000));
|
|
1764
|
+
let contextSnapshot;
|
|
1765
|
+
let genes;
|
|
1766
|
+
try {
|
|
1767
|
+
if (contentMode === 'context') {
|
|
1768
|
+
const benchmark = assetstore.benchmarkContext(process.env['EVOLVER_BENCHMARK_ID']);
|
|
1769
|
+
if (benchmark && (!Number.isSafeInteger(maxGenes) || maxGenes < 1))
|
|
1770
|
+
throw new Error('invalid_benchmark_gene_limit');
|
|
1771
|
+
const received = await readSessionStartSnapshotV1(store, contextDeadlineAt);
|
|
1772
|
+
contextSnapshot = {
|
|
1773
|
+
...received,
|
|
1774
|
+
...(deps.review ? { review: review.snapshot() } : {}),
|
|
1775
|
+
...(deps.provenance ? { provenance: provenance.snapshot() } : {}),
|
|
1776
|
+
};
|
|
1777
|
+
genes = assetstore.approvedGenesFromSnapshot(contextSnapshot, maxGenes, {
|
|
1778
|
+
...(benchmark ? { benchmark } : {}), deadlineAt: contextDeadlineAt,
|
|
1779
|
+
onQualification: (receipts) => { sourceQualifications = receipts; },
|
|
1780
|
+
});
|
|
1781
|
+
}
|
|
1782
|
+
else {
|
|
1783
|
+
const select = async (signal) => listApprovedGenes(store, review, maxGenes, provenance, {
|
|
1784
|
+
...(signal ? { signal, deadlineAt: contextDeadlineAt } : {}),
|
|
1785
|
+
onQualification: (receipts) => { if (!signal?.aborted)
|
|
1786
|
+
sourceQualifications = receipts; },
|
|
1787
|
+
});
|
|
1788
|
+
genes = await select();
|
|
1789
|
+
}
|
|
1790
|
+
}
|
|
1791
|
+
catch {
|
|
1792
|
+
// Invalid benchmark context and unreadable eligibility are failures, not an empty ordinary-mode pool.
|
|
1793
|
+
process.stderr.write('inject session-start: Gene资格读取失败,未注入。\n');
|
|
1794
|
+
return 1;
|
|
1795
|
+
}
|
|
1796
|
+
const rendered = contentMode === 'context' ? [] : genes.map((g) => renderSessionGene(g, contentMode, hardCap * 4));
|
|
1667
1797
|
const geneLines = rendered.map((gene) => gene.text);
|
|
1668
1798
|
const geneIds = genes.map((g) => (typeof g['id'] === 'string' ? String(g['id']) : String(g.asset_id)));
|
|
1669
|
-
// Value recap (#113): same load path as `evolver value`, over the default recap window (7d).
|
|
1670
|
-
const now = deps.now ? deps.now() : Date.now();
|
|
1671
|
-
const traces = ops.readTraceRecords(deps.tracesDir ?? events.tracesDir());
|
|
1672
|
-
const evts = readEvents(deps.eventsPath ?? events.rootEventsPath());
|
|
1673
|
-
const prices = deps.prices ?? loadPriceTable();
|
|
1674
|
-
const summary = ops.loadValueSummary({ traces, events: evts, prices, referenceScope: reference.referenceScopeForEventsPath(deps.eventsPath ?? events.rootEventsPath()) }, ops.windowFromSpec('7d', now));
|
|
1675
1799
|
// Inject emission seam (#123): wire the ingestor so core's onInject lands a `value.inject` root_event. The
|
|
1676
1800
|
// composition (Ingestor ↔ core's sink-agnostic seam) lives HERE in the CLI — core never imports the Ingestor.
|
|
1677
1801
|
const emitter = makeInjectEmitter(ingestor);
|
|
1678
1802
|
let injectedInfo;
|
|
1679
|
-
// Capture the runtime session id (#205) only when the installed hook opts in via --hook-stdin, or a test wires
|
|
1680
|
-
// readHookInput. Default (no flag, no seam) never touches stdin — so a plain `evolver inject session-start` and
|
|
1681
|
-
// the test suite can never block on a stdin read (the Windows CI hang this guards against).
|
|
1682
|
-
const sessionId = deps.sessionId ?? ((fromHookStdin || deps.readHookInput) ? await readHookSessionId(deps.readHookInput) : undefined);
|
|
1683
1803
|
if (sourceQualifications && [sessionId, deps.cycleId].some((id) => id !== undefined && Buffer.byteLength(id, 'utf8') > 128)) {
|
|
1684
1804
|
process.stderr.write('inject session-start: benchmark关联ID超过审计预算,未注入。\n');
|
|
1685
1805
|
return 1;
|
|
1686
1806
|
}
|
|
1687
|
-
|
|
1688
|
-
|
|
1689
|
-
|
|
1690
|
-
|
|
1691
|
-
|
|
1692
|
-
|
|
1693
|
-
|
|
1694
|
-
|
|
1695
|
-
const recordFor = (count) => {
|
|
1696
|
-
const content = rendered.slice(0, count).map((gene) => gene.content);
|
|
1697
|
-
return { ...injectedInfo, geneIds: geneIds.slice(0, count), contentSchema: 'session-gene-content.v1', content,
|
|
1698
|
-
omittedByBudget: rendered.length - count + content.filter((gene) => gene.omissionReason === 'budget').length,
|
|
1699
|
-
...(sourceQualifications ? { sourceQualifications: sourceQualifications.slice(0, count) } : {}),
|
|
1700
|
-
};
|
|
1701
|
-
};
|
|
1702
|
-
let inj = compose(rendered.length);
|
|
1703
|
-
const tokenLimitedCount = inj.genes.length;
|
|
1704
|
-
let low = 0;
|
|
1705
|
-
let high = inj.genes.length;
|
|
1706
|
-
// Find the largest whole-gene prefix whose content and qualification receipts fit
|
|
1707
|
-
// the actual writer envelope, before any prompt bytes reach the runtime.
|
|
1708
|
-
while (low < high) {
|
|
1709
|
-
const count = Math.ceil((low + high) / 2);
|
|
1710
|
-
if (events.fitsRootEventLine(injectEvent(recordFor(count))))
|
|
1711
|
-
low = count;
|
|
1712
|
-
else
|
|
1713
|
-
high = count - 1;
|
|
1714
|
-
}
|
|
1715
|
-
if (low < inj.genes.length) {
|
|
1716
|
-
const omitted = inj.genes.length - low;
|
|
1717
|
-
inj = compose(low);
|
|
1718
|
-
process.stderr.write(`inject session-start: 本次注入记录超过大小上限,省略${omitted}条经验。\n`);
|
|
1719
|
-
}
|
|
1720
|
-
// Keep SessionStart quiet when there is no usable memory payload. When genes do land, the model still receives
|
|
1721
|
-
// them, but the preamble explicitly tells it not to narrate routine Evolver work to the user.
|
|
1722
|
-
if (inj.genes.length > 0 && inj.systemPrompt.trim().length > 0) {
|
|
1807
|
+
if (contentMode === 'context') {
|
|
1808
|
+
const prefixFor = (count) => `${SESSION_START_PREAMBLE}\n${ops.buildValueRecap({ injectedCount: count, successCount: summary.topGenes.length, summary })}\n`;
|
|
1809
|
+
const maxChars = Number.isFinite(hardCap) ? Math.max(0, Math.min(128000, Math.floor(hardCap * 4))) : 32000;
|
|
1810
|
+
const deadlineAt = contextDeadlineAt;
|
|
1811
|
+
let eligibility;
|
|
1812
|
+
let methods;
|
|
1813
|
+
const budget = { maxChars: Math.max(0, maxChars - prefixFor(genes.length).length - 1), maxExampleChars: 3000,
|
|
1814
|
+
maxExampleCharsPerGene: 1200, maxExamplesPerGene: process.env['EVOLVER_RECALL_EXAMPLES'] === 'off' ? 0 : 1 };
|
|
1723
1815
|
try {
|
|
1724
|
-
|
|
1816
|
+
eligibility = { provenance: contextSnapshot?.provenance ?? provenance.snapshot(), review: contextSnapshot?.review ?? review.snapshot(),
|
|
1817
|
+
benchmark: assetstore.benchmarkContext(process.env['EVOLVER_BENCHMARK_ID']), referenceScope: contextSnapshot?.referenceScope ?? store.referenceScope };
|
|
1818
|
+
// Establish the fully qualified method BEFORE optional case I/O. A generic enhancement error cannot
|
|
1819
|
+
// trigger an ordinary-mode fallback, reselect Genes, or bypass benchmark/reference eligibility.
|
|
1820
|
+
methods = await assetstore.assembleGeneContext({ selectedGenes: genes.slice(0, 64), eligibility,
|
|
1821
|
+
contentMode: 'context', privacyMode: 'enforce', deadlineAt, budget: { ...budget, maxExamplesPerGene: 0 } });
|
|
1822
|
+
if (methods.omissions.some((item) => item.reason === 'qualification_unavailable'))
|
|
1823
|
+
throw new Error('eligibility_unavailable');
|
|
1725
1824
|
}
|
|
1726
1825
|
catch {
|
|
1727
|
-
process.stderr.write('inject session-start:
|
|
1826
|
+
process.stderr.write('inject session-start: Gene资格或方法组装失败,未注入。\n');
|
|
1728
1827
|
return 1;
|
|
1729
1828
|
}
|
|
1829
|
+
let context = methods;
|
|
1830
|
+
if (methods.text && budget.maxExamplesPerGene > 0 && Date.now() < deadlineAt) {
|
|
1831
|
+
try {
|
|
1832
|
+
context = await assetstore.assembleGeneContext({ selectedGenes: genes.slice(0, 64), store, eligibility,
|
|
1833
|
+
assertPromptAdapter: () => {
|
|
1834
|
+
if (!assetstore.isBuiltInPromptProvider(store))
|
|
1835
|
+
throw new Error('unsupported_unsupervised_prompt_provider_v1');
|
|
1836
|
+
},
|
|
1837
|
+
contentMode: 'context', privacyMode: 'enforce', deadlineAt, budget });
|
|
1838
|
+
if (!context.text || context.omissions.some((item) => item.reason === 'qualification_unavailable' && !item.capsuleAssetId))
|
|
1839
|
+
context = methods;
|
|
1840
|
+
}
|
|
1841
|
+
catch {
|
|
1842
|
+
context = methods;
|
|
1843
|
+
if (sessionStartHookVerboseEnabled(process.env))
|
|
1844
|
+
process.stderr.write('inject session-start: 可选案例增强失败,仅注入已合格Gene方法。\n');
|
|
1845
|
+
}
|
|
1846
|
+
}
|
|
1847
|
+
const eventFor = (value) => ({
|
|
1848
|
+
type: ops.GENE_CONTEXT_DELIVERY_EVENT, human: { title: 'Session Gene context stdout written' },
|
|
1849
|
+
payload: { receipt: ops.geneContextDeliveryReceipt(value), entrypoint: 'session_start', transport: 'stdout_written', hostReceived: 'unknown',
|
|
1850
|
+
...(sessionId && sessionId.length <= 256 ? { sessionId } : {}),
|
|
1851
|
+
...(deps.cycleId && deps.cycleId.length <= 128 ? { cycleId: deps.cycleId } : {}) },
|
|
1852
|
+
});
|
|
1853
|
+
let finalContext = wrapGeneContext(context, prefixFor(context.geneAssetIds.length), '\n');
|
|
1854
|
+
let event = eventFor(finalContext);
|
|
1855
|
+
const fitsDelivery = (value) => events.fitsRootEventLine({ ...value,
|
|
1856
|
+
payload: { ...value.payload, deliveryAttemptId: '00000000-0000-0000-0000-000000000000' } });
|
|
1857
|
+
// Reduce whole content units and rebuild offsets/digest/receipt, never slice an already-receipted string.
|
|
1858
|
+
// Drop optional cases first, then whole Genes. The pure renderer cannot reopen I/O or weaken eligibility.
|
|
1859
|
+
if (!fitsDelivery(event) || finalContext.text.length > maxChars) {
|
|
1860
|
+
// Rendering cannot reconstruct source/qualification/timeout diagnostics from projections alone.
|
|
1861
|
+
// Keep both assembly passes; the bounded receipt explicitly marks any eventual metadata truncation.
|
|
1862
|
+
const assemblyOmissions = [...context.omissions, ...methods.omissions];
|
|
1863
|
+
for (let count = methods.projections.length; count >= 0; count--) {
|
|
1864
|
+
const projections = methods.projections.slice(0, count).map((gene) => ({ ...gene, examples: [] }));
|
|
1865
|
+
const rendered = assetstore.renderGeneContext(projections, { contentMode: 'context', budget: { ...budget, maxExamplesPerGene: 0 } });
|
|
1866
|
+
const visible = new Set(rendered.geneAssetIds);
|
|
1867
|
+
context = { ...methods, ...rendered, projections: projections.filter((gene) => visible.has(gene.assetId)),
|
|
1868
|
+
omissions: [...new Map([...assemblyOmissions, ...rendered.omissions].map((item) => [JSON.stringify([item.reason, item.geneAssetId, item.capsuleAssetId]), item])).values()],
|
|
1869
|
+
qualifications: methods.qualifications.filter((item) => visible.has(item.assetId)),
|
|
1870
|
+
counts: { ...methods.counts, rendered: rendered.geneAssetIds.length, examples: 0 } };
|
|
1871
|
+
finalContext = wrapGeneContext(context, prefixFor(context.geneAssetIds.length), '\n');
|
|
1872
|
+
event = eventFor(finalContext);
|
|
1873
|
+
if (fitsDelivery(event) && finalContext.text.length <= maxChars)
|
|
1874
|
+
break;
|
|
1875
|
+
}
|
|
1876
|
+
}
|
|
1877
|
+
if (finalContext.text) {
|
|
1878
|
+
if (!fitsDelivery(event) || finalContext.text.length > maxChars) {
|
|
1879
|
+
process.stderr.write('inject session-start: 交付收据超过审计预算,未注入。\n');
|
|
1880
|
+
return 1;
|
|
1881
|
+
}
|
|
1882
|
+
const result = await deliverContextOutput({ text: finalContext.text, ...(deps.stdout ? { stdout: deps.stdout } : {}),
|
|
1883
|
+
...(ingestor.prepareContextDelivery ? { prepare: (options) => typeof ingestor.prepareContextDeliveryAsync === 'function' ? ingestor.prepareContextDeliveryAsync(event, options)
|
|
1884
|
+
: ingestor.prepareContextDelivery(event, options) } : {}) });
|
|
1885
|
+
if (result !== 'written') {
|
|
1886
|
+
process.stderr.write('inject session-start: 交付准备或输出未确认完成,未记录策略交付。\n');
|
|
1887
|
+
return 1;
|
|
1888
|
+
}
|
|
1889
|
+
}
|
|
1730
1890
|
}
|
|
1731
|
-
|
|
1732
|
-
|
|
1733
|
-
|
|
1734
|
-
|
|
1735
|
-
|
|
1736
|
-
|
|
1737
|
-
|
|
1738
|
-
|
|
1739
|
-
|
|
1891
|
+
else {
|
|
1892
|
+
const compose = (count) => {
|
|
1893
|
+
injectedInfo = undefined;
|
|
1894
|
+
return hooks.composeSessionStartWithRecap({ tokenBudgetHardCap: hardCap, preamble: SESSION_START_PREAMBLE }, { injectGenes: geneLines.slice(0, count), geneIds: geneIds.slice(0, count), successCount: summary.topGenes.length, summary }, {
|
|
1895
|
+
onInject: (info) => { injectedInfo = info; },
|
|
1896
|
+
...(deps.cycleId ? { cycleId: deps.cycleId } : {}),
|
|
1897
|
+
...(sessionId ? { sessionId } : {}),
|
|
1898
|
+
});
|
|
1899
|
+
};
|
|
1900
|
+
const recordFor = (count) => {
|
|
1901
|
+
const content = rendered.slice(0, count).map((gene) => gene.content);
|
|
1902
|
+
return { ...injectedInfo, geneIds: geneIds.slice(0, count), contentSchema: 'session-gene-content.v1', content,
|
|
1903
|
+
omittedByBudget: rendered.length - count + content.filter((gene) => gene.omissionReason === 'budget').length,
|
|
1904
|
+
...(sourceQualifications ? { sourceQualifications: sourceQualifications.slice(0, count) } : {}),
|
|
1905
|
+
};
|
|
1906
|
+
};
|
|
1907
|
+
let inj = compose(rendered.length);
|
|
1908
|
+
const tokenLimitedCount = inj.genes.length;
|
|
1909
|
+
let low = 0;
|
|
1910
|
+
let high = inj.genes.length;
|
|
1911
|
+
// Find the largest whole-gene prefix whose content and qualification receipts fit
|
|
1912
|
+
// the actual writer envelope, before any prompt bytes reach the runtime.
|
|
1913
|
+
while (low < high) {
|
|
1914
|
+
const count = Math.ceil((low + high) / 2);
|
|
1915
|
+
if (events.fitsRootEventLine(injectEvent(recordFor(count))))
|
|
1916
|
+
low = count;
|
|
1917
|
+
else
|
|
1918
|
+
high = count - 1;
|
|
1919
|
+
}
|
|
1920
|
+
if (low < inj.genes.length) {
|
|
1921
|
+
const omitted = inj.genes.length - low;
|
|
1922
|
+
inj = compose(low);
|
|
1923
|
+
process.stderr.write(`inject session-start: 本次注入记录超过大小上限,省略${omitted}条经验。\n`);
|
|
1924
|
+
}
|
|
1925
|
+
// Keep SessionStart quiet when there is no usable memory payload. When genes do land, the model still receives
|
|
1926
|
+
// them, but the preamble explicitly tells it not to narrate routine Evolver work to the user.
|
|
1927
|
+
if (inj.genes.length > 0 && inj.systemPrompt.trim().length > 0) {
|
|
1928
|
+
try {
|
|
1929
|
+
await (deps.stdout ?? writeSessionPrompt)(inj.systemPrompt + '\n');
|
|
1930
|
+
}
|
|
1931
|
+
catch {
|
|
1932
|
+
process.stderr.write('inject session-start: 输出未确认完成,未记录策略交付。\n');
|
|
1933
|
+
return 1;
|
|
1934
|
+
}
|
|
1935
|
+
}
|
|
1936
|
+
const record = recordFor(inj.genes.length);
|
|
1937
|
+
const tokenOmitted = rendered.length - tokenLimitedCount + (record.content?.filter((gene) => gene.omissionReason === 'budget').length ?? 0);
|
|
1938
|
+
if (contentMode === 'strategy' && tokenOmitted > 0) {
|
|
1939
|
+
process.stderr.write(`inject session-start: ${tokenOmitted}条Gene的完整策略因token预算未注入。\n`);
|
|
1940
|
+
}
|
|
1941
|
+
// 仅在stdout callback确认成功后记账;事件不复制策略正文,也不声称runtime已经执行。
|
|
1942
|
+
if (injectedInfo && emitter) {
|
|
1943
|
+
emitter.onInject(record);
|
|
1944
|
+
await emitter.flush();
|
|
1945
|
+
}
|
|
1740
1946
|
}
|
|
1741
1947
|
// Legacy v1 Windows scheduled-task sweep (#956): runs AFTER the injection is on stdout so a worst-case
|
|
1742
1948
|
// sweep (probe 20s + lock wait 3s + 2×(export 20s + mutation 40s) ≈ 143s) can never push the injection
|
|
@@ -2001,8 +2207,19 @@ export function runCli(argv) {
|
|
|
2001
2207
|
case 'reset-local-secret':
|
|
2002
2208
|
return runResetLocalSecret(argv.slice(1));
|
|
2003
2209
|
case 'status': {
|
|
2210
|
+
if (argv.slice(1).some(arg => arg === '--live' || arg.startsWith('--live='))) {
|
|
2211
|
+
process.stderr.write('Live status requires the asynchronous CLI dispatcher.\n');
|
|
2212
|
+
return 2;
|
|
2213
|
+
}
|
|
2004
2214
|
const s = statusReport(readEvents());
|
|
2215
|
+
const contextDelivery = events.Ingestor.contextDeliveryStatus(events.rootEventsPath());
|
|
2216
|
+
if (argv.includes('--json')) {
|
|
2217
|
+
process.stdout.write(`${JSON.stringify({ ...s, contextDelivery })}\n`);
|
|
2218
|
+
return 0;
|
|
2219
|
+
}
|
|
2005
2220
|
process.stdout.write(`events=${s.totalEvents} cycles=${s.cycles} last=${s.lastTs ?? '-'}\n`);
|
|
2221
|
+
if (contextDelivery.confirmedPending || contextDelivery.outputUnknown || contextDelivery.projectionUnknown || contextDelivery.busy)
|
|
2222
|
+
process.stdout.write(`contextDelivery: confirmedPending=${contextDelivery.confirmedPending} outputUnknown=${contextDelivery.outputUnknown} projectionUnknown=${contextDelivery.projectionUnknown} busy=${contextDelivery.busy}\n`);
|
|
2006
2223
|
return 0;
|
|
2007
2224
|
}
|
|
2008
2225
|
case 'cycles': {
|
package/dist/lifecycle.d.ts
CHANGED
|
@@ -265,6 +265,24 @@ export declare function resolveSelfUpdatingExecutable(execPath: string, argv1: s
|
|
|
265
265
|
export declare function resolveAutoexecDaemonCommand(env: NodeJS.ProcessEnv, execPath?: string, argv1?: string | undefined, autoexecHome?: string): DaemonCommand | undefined;
|
|
266
266
|
export declare function resolveProxyBinPath(): string | undefined;
|
|
267
267
|
export declare function resolveStableNodePath(): string;
|
|
268
|
+
export interface RuntimeLoopStatus {
|
|
269
|
+
state: 'recent' | 'idle' | 'disabled' | 'overdue_or_blocked' | 'degraded' | 'unknown';
|
|
270
|
+
lastTickAt?: number;
|
|
271
|
+
nextTickDueAt?: number;
|
|
272
|
+
consecutiveFailures?: number;
|
|
273
|
+
}
|
|
274
|
+
export interface ProxyRuntimeStatus {
|
|
275
|
+
state: 'running' | 'stopped' | 'unknown';
|
|
276
|
+
ipc: 'reachable' | 'unreachable' | 'unknown';
|
|
277
|
+
pid?: number;
|
|
278
|
+
reason?: string;
|
|
279
|
+
loop: RuntimeLoopStatus;
|
|
280
|
+
hubAuth?: 'ok' | 'auth_failed' | 'retired' | 'rate_limited' | 'replacement_healthy' | 'unknown';
|
|
281
|
+
syncErrorPresent?: boolean;
|
|
282
|
+
}
|
|
283
|
+
export declare function proxyLoopStatus(health: Record<string, unknown>, now: number): RuntimeLoopStatus;
|
|
284
|
+
/** A bounded, authenticated local observation. Unlike lifecycleStatus, it never removes stale state. */
|
|
285
|
+
export declare function probeProxyRuntime(paths: LifecyclePaths, timeoutMs?: number): Promise<ProxyRuntimeStatus>;
|
|
268
286
|
export declare function sessionStartHookVerboseEnabled(env?: NodeJS.ProcessEnv): boolean;
|
|
269
287
|
export declare function proxyExpected(env?: NodeJS.ProcessEnv): boolean;
|
|
270
288
|
declare function writeWindowsHelper(preferredPath: string, content: string): string;
|
package/dist/lifecycle.js
CHANGED
|
@@ -34,6 +34,13 @@ const PS_PATH = selectExistingPosixCommand([
|
|
|
34
34
|
'/run/current-system/sw/bin/ps',
|
|
35
35
|
]);
|
|
36
36
|
const LAUNCHCTL_PATH = '/bin/launchctl';
|
|
37
|
+
// `launchctl print gui/<uid>/<label>` exit statuses, as named by `launchctl error <n>`: 113 is
|
|
38
|
+
// "Could not find specified service" (the login domain exists, the label is not loaded) and 112 is
|
|
39
|
+
// "Could not find specified domain" (no GUI login session). 3 ("No such process") is kept as absent
|
|
40
|
+
// for launchd builds that report a missing label that way.
|
|
41
|
+
const LAUNCHCTL_NO_SUCH_PROCESS_STATUS = 3;
|
|
42
|
+
const LAUNCHCTL_DOMAIN_NOT_FOUND_STATUS = 112;
|
|
43
|
+
const LAUNCHCTL_SERVICE_NOT_FOUND_STATUS = 113;
|
|
37
44
|
const UNIX_RECOVERY_CONTROLLER_FILENAME = 'evolver-recovery-controller';
|
|
38
45
|
const HOST_WINDOWS_SYSTEM_ROOT = process.env['SystemRoot']?.trim() || 'C:\\Windows';
|
|
39
46
|
const LIFECYCLE_USAGE = 'Usage: evolver lifecycle <start|stop|restart|status|check|watch|install-service --target=launchd|systemd|windows [--with-autoexec] [--autoexec-home=<path>]|remove-service --target=launchd|systemd|windows [--dry-run] [--env-file=<path>]|bootstrap [--target=launchd|systemd|windows] [--dry-run]|remove-autoexec-service --target=launchd|systemd|windows [--dry-run]|cleanup-legacy-tasks [--dry-run]|restore-legacy-task-preimage --preimage=<path>>\n';
|
|
@@ -3562,9 +3569,10 @@ function probeBootstrapManagerState(target, run, uid, timeoutMs) {
|
|
|
3562
3569
|
return 'inconclusive';
|
|
3563
3570
|
if (result.status === 0)
|
|
3564
3571
|
return 'present';
|
|
3565
|
-
if (result.status ===
|
|
3572
|
+
if (result.status === LAUNCHCTL_NO_SUCH_PROCESS_STATUS
|
|
3573
|
+
|| result.status === LAUNCHCTL_SERVICE_NOT_FOUND_STATUS)
|
|
3566
3574
|
return 'absent';
|
|
3567
|
-
if (result.status ===
|
|
3575
|
+
if (result.status === LAUNCHCTL_DOMAIN_NOT_FOUND_STATUS)
|
|
3568
3576
|
return 'unavailable';
|
|
3569
3577
|
return 'inconclusive';
|
|
3570
3578
|
}
|
|
@@ -5410,7 +5418,17 @@ function readProxySettings(path, options = {}) {
|
|
|
5410
5418
|
if (!opened.isFile() || opened.dev !== before.dev || opened.ino !== before.ino) {
|
|
5411
5419
|
throw new Error('proxy settings changed while opening');
|
|
5412
5420
|
}
|
|
5413
|
-
const
|
|
5421
|
+
const buffer = Buffer.alloc(MAX_PROXY_SETTINGS_BYTES + 1);
|
|
5422
|
+
let total = 0;
|
|
5423
|
+
while (total < buffer.length) {
|
|
5424
|
+
const count = readSync(descriptor, buffer, total, buffer.length - total, total);
|
|
5425
|
+
if (!count)
|
|
5426
|
+
break;
|
|
5427
|
+
total += count;
|
|
5428
|
+
}
|
|
5429
|
+
if (total > MAX_PROXY_SETTINGS_BYTES)
|
|
5430
|
+
throw new Error('proxy settings exceed size limit');
|
|
5431
|
+
const parsed = JSON.parse(buffer.subarray(0, total).toString('utf8'));
|
|
5414
5432
|
const after = fstatSync(descriptor, { bigint: true });
|
|
5415
5433
|
if (after.dev !== opened.dev || after.ino !== opened.ino || after.size !== opened.size
|
|
5416
5434
|
|| after.mtimeNs !== opened.mtimeNs || after.ctimeNs !== opened.ctimeNs) {
|
|
@@ -5435,6 +5453,8 @@ function readProxySettings(path, options = {}) {
|
|
|
5435
5453
|
};
|
|
5436
5454
|
}
|
|
5437
5455
|
catch (err) {
|
|
5456
|
+
if (options.throwReadError && err.code !== 'ENOENT')
|
|
5457
|
+
throw err;
|
|
5438
5458
|
if (!options.quietReadError && err.code !== 'ENOENT') {
|
|
5439
5459
|
const stderr = options.stderr ?? ((text) => { process.stderr.write(text); });
|
|
5440
5460
|
stderr(`[Lifecycle] failed to read proxy settings: ${err instanceof Error ? err.message : String(err)}\n`);
|
|
@@ -5446,6 +5466,113 @@ function readProxySettings(path, options = {}) {
|
|
|
5446
5466
|
closeSync(descriptor);
|
|
5447
5467
|
}
|
|
5448
5468
|
}
|
|
5469
|
+
export function proxyLoopStatus(health, now) {
|
|
5470
|
+
const lastTickAt = health['lastTickAt'];
|
|
5471
|
+
const nextTickDueAt = health['nextTickDueAt'];
|
|
5472
|
+
const failures = health['consecutiveFailures'];
|
|
5473
|
+
const validTime = (value) => typeof value === 'number' && Number.isSafeInteger(value) && value > 0 && value <= 8_640_000_000_000_000;
|
|
5474
|
+
if (typeof health['lifecycleArmed'] !== 'boolean' || !Number.isSafeInteger(failures) || failures < 0
|
|
5475
|
+
|| (lastTickAt !== undefined && (!validTime(lastTickAt) || lastTickAt > now))
|
|
5476
|
+
|| (nextTickDueAt !== undefined && (!validTime(nextTickDueAt) || (validTime(lastTickAt) && nextTickDueAt < lastTickAt)))) {
|
|
5477
|
+
return { state: 'unknown' };
|
|
5478
|
+
}
|
|
5479
|
+
return {
|
|
5480
|
+
state: failures > 0 ? 'degraded' : health['lifecycleArmed'] === false ? 'disabled'
|
|
5481
|
+
: validTime(nextTickDueAt) && nextTickDueAt >= now ? 'idle'
|
|
5482
|
+
: validTime(nextTickDueAt) && now > nextTickDueAt + 5_000 ? 'overdue_or_blocked'
|
|
5483
|
+
: validTime(lastTickAt) ? (now - lastTickAt <= 60_000 ? 'recent' : 'overdue_or_blocked') : 'unknown',
|
|
5484
|
+
...(validTime(lastTickAt) ? { lastTickAt } : {}),
|
|
5485
|
+
...(validTime(nextTickDueAt) ? { nextTickDueAt } : {}),
|
|
5486
|
+
consecutiveFailures: failures,
|
|
5487
|
+
};
|
|
5488
|
+
}
|
|
5489
|
+
/** A bounded, authenticated local observation. Unlike lifecycleStatus, it never removes stale state. */
|
|
5490
|
+
export async function probeProxyRuntime(paths, timeoutMs = DEFAULT_HEALTH_TIMEOUT_MS) {
|
|
5491
|
+
const unknown = (reason, ipc = 'unknown') => ({ state: 'unknown', ipc, reason, loop: { state: 'unknown' } });
|
|
5492
|
+
let settings;
|
|
5493
|
+
try {
|
|
5494
|
+
settings = readProxySettings(paths.settingsFile, { throwReadError: true });
|
|
5495
|
+
}
|
|
5496
|
+
catch {
|
|
5497
|
+
return unknown('settings_unreadable_or_invalid');
|
|
5498
|
+
}
|
|
5499
|
+
if (!settings.url || !settings.token)
|
|
5500
|
+
return unknown('settings_missing_or_invalid');
|
|
5501
|
+
const controller = new AbortController();
|
|
5502
|
+
const timeout = setTimeout(() => controller.abort(), timeoutMs);
|
|
5503
|
+
let reached = false;
|
|
5504
|
+
try {
|
|
5505
|
+
const response = await fetch(`${settings.url}/proxy/status`, {
|
|
5506
|
+
headers: { authorization: `Bearer ${settings.token}` }, signal: controller.signal, redirect: 'manual',
|
|
5507
|
+
});
|
|
5508
|
+
reached = true;
|
|
5509
|
+
if (response.status >= 300 && response.status < 400) {
|
|
5510
|
+
await response.body?.cancel();
|
|
5511
|
+
return unknown('ipc_redirect_refused', 'reachable');
|
|
5512
|
+
}
|
|
5513
|
+
if (!response.ok) {
|
|
5514
|
+
await response.body?.cancel();
|
|
5515
|
+
return unknown(response.status === 401 || response.status === 403 ? 'ipc_auth_failed' : 'ipc_http_error', 'reachable');
|
|
5516
|
+
}
|
|
5517
|
+
if (!response.body)
|
|
5518
|
+
return unknown('ipc_invalid_response', 'reachable');
|
|
5519
|
+
const reader = response.body.getReader();
|
|
5520
|
+
const chunks = [];
|
|
5521
|
+
let bytes = 0;
|
|
5522
|
+
try {
|
|
5523
|
+
while (true) {
|
|
5524
|
+
const chunk = await reader.read();
|
|
5525
|
+
if (chunk.done)
|
|
5526
|
+
break;
|
|
5527
|
+
bytes += chunk.value.byteLength;
|
|
5528
|
+
if (bytes > MAX_PROXY_SETTINGS_BYTES) {
|
|
5529
|
+
await reader.cancel();
|
|
5530
|
+
return unknown('ipc_response_too_large', 'reachable');
|
|
5531
|
+
}
|
|
5532
|
+
chunks.push(chunk.value);
|
|
5533
|
+
}
|
|
5534
|
+
}
|
|
5535
|
+
finally {
|
|
5536
|
+
reader.releaseLock();
|
|
5537
|
+
}
|
|
5538
|
+
const body = JSON.parse(Buffer.concat(chunks).toString('utf8'));
|
|
5539
|
+
if (!body || typeof body !== 'object' || Array.isArray(body))
|
|
5540
|
+
return unknown('ipc_invalid_response', 'reachable');
|
|
5541
|
+
const status = body;
|
|
5542
|
+
if (status['status'] !== 'running' || status['running'] !== true)
|
|
5543
|
+
return unknown('ipc_invalid_response', 'reachable');
|
|
5544
|
+
const value = status['health'];
|
|
5545
|
+
if (!value || typeof value !== 'object' || Array.isArray(value))
|
|
5546
|
+
return {
|
|
5547
|
+
state: 'running', ipc: 'reachable', reason: 'legacy_loop_telemetry_unavailable', loop: { state: 'unknown' },
|
|
5548
|
+
};
|
|
5549
|
+
const health = value;
|
|
5550
|
+
const pid = health['pid'];
|
|
5551
|
+
const identity = coreUtil.parseFileLockProcessStartIdentity(health['processStartIdentity']);
|
|
5552
|
+
if (!Number.isSafeInteger(pid) || pid <= 0 || !identity || health['running'] !== true || health['ipcListening'] !== true
|
|
5553
|
+
|| (settings.pid !== undefined && settings.pid !== pid)
|
|
5554
|
+
|| coreUtil.inspectFileLockOwnerProcess({ pid: pid, processStartIdentity: identity }) !== 'current') {
|
|
5555
|
+
return unknown('ipc_process_identity_unconfirmed', 'reachable');
|
|
5556
|
+
}
|
|
5557
|
+
const auth = status['hub_auth_status'];
|
|
5558
|
+
const hubAuth = auth === 'ok' || auth === 'auth_failed' || auth === 'retired' || auth === 'rate_limited' || auth === 'replacement_healthy' ? auth : 'unknown';
|
|
5559
|
+
return {
|
|
5560
|
+
state: 'running', ipc: 'reachable', pid: pid, loop: proxyLoopStatus(health, Date.now()), hubAuth,
|
|
5561
|
+
syncErrorPresent: typeof status['last_sync_error'] === 'string' && status['last_sync_error'].length > 0,
|
|
5562
|
+
};
|
|
5563
|
+
}
|
|
5564
|
+
catch {
|
|
5565
|
+
if (reached)
|
|
5566
|
+
return unknown(controller.signal.aborted ? 'ipc_timeout' : 'ipc_invalid_response', 'reachable');
|
|
5567
|
+
if (settings.pid && !isPidRunning(settings.pid))
|
|
5568
|
+
return { state: 'stopped', ipc: 'unreachable', pid: settings.pid, reason: 'recorded_process_exited', loop: { state: 'unknown' } };
|
|
5569
|
+
return unknown(controller.signal.aborted ? 'ipc_timeout' : 'ipc_unreachable_or_invalid', 'unreachable');
|
|
5570
|
+
}
|
|
5571
|
+
finally {
|
|
5572
|
+
clearTimeout(timeout);
|
|
5573
|
+
controller.abort();
|
|
5574
|
+
}
|
|
5575
|
+
}
|
|
5449
5576
|
function isNumericLoopbackOrigin(value) {
|
|
5450
5577
|
if (value.length === 0 || value.length > 2_048)
|
|
5451
5578
|
return false;
|