@lobu/runtime-device 24.4.0 → 24.6.0

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.
Files changed (113) hide show
  1. package/dist/component.json +1 -1
  2. package/dist/dependencies.bun.lock +77 -64
  3. package/dist/verify.mjs +1 -1
  4. package/npm-shrinkwrap.json +176 -141
  5. package/package.json +3 -2
  6. package/vendor/cli/dist/bundled-skills/lobu/SKILL.md +65 -11
  7. package/vendor/cli/dist/commands/_lib/apply/apply-cmd.js +20 -13
  8. package/vendor/cli/dist/commands/_lib/apply/client.d.ts +48 -100
  9. package/vendor/cli/dist/commands/_lib/apply/client.js +76 -27
  10. package/vendor/cli/dist/commands/_lib/apply/deployment.js +1 -1
  11. package/vendor/cli/dist/commands/_lib/apply/desired-state.d.ts +7 -11
  12. package/vendor/cli/dist/commands/_lib/apply/desired-state.js +9 -40
  13. package/vendor/cli/dist/commands/_lib/apply/diff.d.ts +4 -4
  14. package/vendor/cli/dist/commands/_lib/apply/diff.js +37 -33
  15. package/vendor/cli/dist/commands/_lib/apply/map-config.d.ts +1 -1
  16. package/vendor/cli/dist/commands/_lib/apply/map-config.js +79 -92
  17. package/vendor/cli/dist/commands/_lib/apply/shared.d.ts +3 -6
  18. package/vendor/cli/dist/commands/_lib/apply/shared.js +8 -19
  19. package/vendor/cli/dist/commands/_lib/view-bundler.js +9 -1
  20. package/vendor/cli/dist/commands/dev.js +21 -7
  21. package/vendor/cli/dist/commands/doctor.js +1 -8
  22. package/vendor/cli/dist/commands/init.js +4 -5
  23. package/vendor/cli/dist/config/define.d.ts +27 -28
  24. package/vendor/cli/dist/config/define.js +4 -5
  25. package/vendor/cli/dist/connectors/linkedin-identity.ts +43 -0
  26. package/vendor/cli/dist/connectors/linkedin.ts +154 -3
  27. package/vendor/cli/dist/connectors/postgres.ts +77 -48
  28. package/vendor/cli/dist/connectors/x-like-follow.ts +329 -0
  29. package/vendor/cli/dist/connectors/x.ts +709 -80
  30. package/vendor/cli/dist/internal/api-client.d.ts +2 -0
  31. package/vendor/cli/dist/internal/api-client.js +6 -1
  32. package/vendor/cli/dist/internal/connector-compiler.js +3 -1
  33. package/vendor/cli/dist/internal/node-binary.d.ts +22 -0
  34. package/vendor/cli/dist/internal/node-binary.js +73 -0
  35. package/vendor/cli/dist/internal/node-version.d.ts +7 -12
  36. package/vendor/cli/dist/internal/node-version.js +16 -20
  37. package/vendor/cli/dist/runtime-components.json +4 -4
  38. package/vendor/cli/dist/templates/AGENTS.md.tmpl +2 -2
  39. package/vendor/cli/package.json +3 -2
  40. package/vendor/connector-sdk/dist/reaction-client-types.d.ts +8 -2
  41. package/vendor/connector-sdk/dist/reaction-sdk.d.ts +5 -1
  42. package/vendor/connector-sdk/package.json +1 -1
  43. package/vendor/connector-worker/dist/compile/index.d.ts +4 -3
  44. package/vendor/connector-worker/dist/compile/index.js +6 -3
  45. package/vendor/connector-worker/dist/daemon/acp-adapters/claude.js +1 -1
  46. package/vendor/connector-worker/dist/daemon/agent-turn.js +21 -10
  47. package/vendor/connector-worker/dist/daemon/client.d.ts +25 -8
  48. package/vendor/connector-worker/dist/daemon/client.js +25 -3
  49. package/vendor/connector-worker/dist/daemon/mac-device-daemon.js +7 -1
  50. package/vendor/connector-worker/dist/daemon/poll-loop.d.ts +17 -0
  51. package/vendor/connector-worker/dist/daemon/poll-loop.js +75 -6
  52. package/vendor/connector-worker/dist/daemon/resource-admission.d.ts +19 -0
  53. package/vendor/connector-worker/dist/daemon/resource-admission.js +59 -0
  54. package/vendor/connector-worker/dist/daemon/resources.d.ts +20 -0
  55. package/vendor/connector-worker/dist/daemon/resources.js +163 -0
  56. package/vendor/connector-worker/dist/daemon/start.js +29 -4
  57. package/vendor/connector-worker/dist/daemon/worker.d.ts +2 -0
  58. package/vendor/connector-worker/dist/daemon/worker.js +4 -0
  59. package/vendor/connector-worker/dist/executor/select.d.ts +1 -1
  60. package/vendor/connector-worker/dist/executor/select.js +1 -1
  61. package/vendor/connector-worker/dist/isolate/ivm-types.d.ts +1 -2
  62. package/vendor/connector-worker/dist/isolate/ivm-types.js +1 -2
  63. package/vendor/connector-worker/dist/isolate/load.d.ts +10 -12
  64. package/vendor/connector-worker/dist/isolate/load.js +23 -27
  65. package/vendor/connector-worker/dist/self-check/index.d.ts +2 -2
  66. package/vendor/connector-worker/dist/self-check/index.js +2 -2
  67. package/vendor/connector-worker/package.json +3 -4
  68. package/vendor/core/dist/contracts/agent-settings.d.ts +61 -6
  69. package/vendor/core/dist/contracts/agent-settings.js +10 -7
  70. package/vendor/core/dist/contracts/tools/manage-agents.d.ts +473 -98
  71. package/vendor/core/dist/contracts/tools/manage-agents.js +111 -2
  72. package/vendor/core/dist/contracts/tools/manage-automations.d.ts +21 -18
  73. package/vendor/core/dist/contracts/tools/manage-automations.js +15 -15
  74. package/vendor/core/dist/contracts/tools/manage-entity-schema.js +2 -2
  75. package/vendor/core/dist/contracts/tools/manage-inference-providers.d.ts +445 -0
  76. package/vendor/core/dist/contracts/tools/manage-inference-providers.js +133 -0
  77. package/vendor/core/dist/contracts/tools/manage-views.d.ts +4 -4
  78. package/vendor/core/dist/contracts/tools/manage-views.js +5 -3
  79. package/vendor/core/dist/contracts/tools/view-host.d.ts +7 -0
  80. package/vendor/core/dist/contracts/tools/view-host.js +28 -0
  81. package/vendor/core/dist/contracts/tools/view-runtime.d.ts +2 -4
  82. package/vendor/core/dist/contracts/tools/view-runtime.js +19 -7
  83. package/vendor/core/dist/contracts/worker/device-automation.js +4 -2
  84. package/vendor/core/dist/error-report.d.ts +73 -0
  85. package/vendor/core/dist/error-report.js +346 -0
  86. package/vendor/core/dist/index.d.ts +3 -1
  87. package/vendor/core/dist/index.js +4 -1
  88. package/vendor/core/dist/logger.js +7 -4
  89. package/vendor/core/dist/otel-fetch.d.ts +19 -0
  90. package/vendor/core/dist/otel-fetch.js +96 -0
  91. package/vendor/core/dist/otel.d.ts +9 -0
  92. package/vendor/core/dist/otel.js +28 -7
  93. package/vendor/core/dist/reserved.d.ts +1 -1
  94. package/vendor/core/dist/reserved.js +6 -4
  95. package/vendor/core/dist/tool-result.d.ts +8 -0
  96. package/vendor/core/dist/tool-result.js +61 -0
  97. package/vendor/core/dist/utils/diagnostic-scrubber.js +1 -1
  98. package/vendor/core/dist/worker/auth.js +4 -0
  99. package/vendor/core/package.json +16 -1
  100. package/vendor/views/dist/api.d.ts +290 -0
  101. package/vendor/views/dist/api.js +714 -0
  102. package/vendor/views/dist/bridge.d.ts +157 -0
  103. package/vendor/views/dist/bridge.js +372 -0
  104. package/vendor/views/dist/components.d.ts +172 -0
  105. package/vendor/views/dist/components.js +376 -0
  106. package/vendor/views/dist/index.d.ts +13 -0
  107. package/vendor/views/dist/index.js +3 -0
  108. package/vendor/views/dist/native.d.ts +327 -0
  109. package/vendor/views/dist/native.js +57 -0
  110. package/vendor/views/package.json +53 -0
  111. /package/vendor/cli/dist/vendor/ora/{.bun-tag-fde20e9a6df212fa → .bun-tag-77bb9b258a474a18} +0 -0
  112. /package/vendor/ora/{.bun-tag-fde20e9a6df212fa → .bun-tag-77bb9b258a474a18} +0 -0
  113. /package/vendor/postgres/{.bun-tag-22d644c2873790db → .bun-tag-c81dacd34e959a7a} +0 -0
@@ -119,9 +119,11 @@ exports.ViewRowSchema = typebox_1.Type.Object({
119
119
  attach: typebox_1.Type.Array(exports.ViewAttachmentSchema),
120
120
  params: typebox_1.Type.Record(typebox_1.Type.String(), exports.ViewParamDeclSchema),
121
121
  actions: typebox_1.Type.Record(typebox_1.Type.String(), exports.ViewActionDeclSchema),
122
- last_writer: typebox_1.Type.String({
123
- description: "apply:<apply_id> | <user_id> | migration:view-templates",
124
- }),
122
+ // Optional because a reader outside the workspace (a public workspace's
123
+ // visitor) gets the list without anyone's user id in it.
124
+ last_writer: typebox_1.Type.Optional(typebox_1.Type.String({
125
+ description: "apply:<apply_id> | <user_id> | migration:view-templates. Omitted for readers outside the workspace.",
126
+ })),
125
127
  updated_at: typebox_1.Type.String(),
126
128
  compiled_bytes: typebox_1.Type.Integer(),
127
129
  source_bytes: typebox_1.Type.Integer(),
@@ -0,0 +1,7 @@
1
+ /** Browser bridge routing hints, never authority. */
2
+ export declare const VIEW_WORKSPACE_META_KEY = "lobu/view-workspace";
3
+ export declare const VIEW_OPEN_RECORD_METHOD = "lobu/open-record";
4
+ /** A mixed read/write tool is admitted only for these fixed read actions.
5
+ * The server still applies the visiting user's authorization and org scope. */
6
+ export declare function isViewRead(tool: string, args: Record<string, unknown> | undefined): boolean;
7
+ //# sourceMappingURL=view-host.d.ts.map
@@ -0,0 +1,28 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.VIEW_OPEN_RECORD_METHOD = exports.VIEW_WORKSPACE_META_KEY = void 0;
4
+ exports.isViewRead = isViewRead;
5
+ /** Browser bridge routing hints, never authority. */
6
+ exports.VIEW_WORKSPACE_META_KEY = "lobu/view-workspace";
7
+ exports.VIEW_OPEN_RECORD_METHOD = "lobu/open-record";
8
+ /** A mixed read/write tool is admitted only for these fixed read actions.
9
+ * The server still applies the visiting user's authorization and org scope. */
10
+ function isViewRead(tool, args) {
11
+ if (tool === "manage_entity") {
12
+ return (args?.action === "list" ||
13
+ args?.action === "get" ||
14
+ args?.action === "list_links");
15
+ }
16
+ if (tool === "manage_automations")
17
+ return args?.action === "list";
18
+ if (tool === "manage_agents")
19
+ return args?.action === "get";
20
+ if (tool === "manage_connections")
21
+ return args?.action === "list";
22
+ if (tool === "manage_catalog")
23
+ return args?.action === "list_installed";
24
+ return (tool === "manage_entity_schema" &&
25
+ args?.schema_type === "entity_type" &&
26
+ (args.action === "list" || args.action === "get"));
27
+ }
28
+ //# sourceMappingURL=view-host.js.map
@@ -14,8 +14,7 @@
14
14
  */
15
15
  /** Global the shell's runtime script assigns and every view bundle reads. */
16
16
  export declare const VIEW_RUNTIME_GLOBAL = "__lobuViews";
17
- /** Per-call workspace selected by an MCP view. A routing hint, never authority. */
18
- export declare const VIEW_WORKSPACE_META_KEY = "lobu/view-workspace";
17
+ export { VIEW_WORKSPACE_META_KEY } from "./view-host";
19
18
  /** Module specifiers a view imports from the shell runtime. */
20
19
  export declare const VIEW_RUNTIME_MODULES: readonly string[];
21
20
  /** Packages behind {@link VIEW_RUNTIME_MODULES}. A view whose retained
@@ -68,9 +67,8 @@ interface RuntimePluginBuild {
68
67
  * the runtime global, so the bundle carries none of the runtime. Structurally
69
68
  * typed: core does not depend on esbuild.
70
69
  */
71
- export declare function viewRuntimePlugin(): {
70
+ export declare function viewRuntimePlugin(exportNames?: Readonly<Record<string, readonly string[]>>): {
72
71
  name: string;
73
72
  setup(build: RuntimePluginBuild): void;
74
73
  };
75
- export {};
76
74
  //# sourceMappingURL=view-runtime.d.ts.map
@@ -20,8 +20,8 @@ exports.viewRuntimeEntry = viewRuntimeEntry;
20
20
  exports.viewRuntimePlugin = viewRuntimePlugin;
21
21
  /** Global the shell's runtime script assigns and every view bundle reads. */
22
22
  exports.VIEW_RUNTIME_GLOBAL = "__lobuViews";
23
- /** Per-call workspace selected by an MCP view. A routing hint, never authority. */
24
- exports.VIEW_WORKSPACE_META_KEY = "lobu/view-workspace";
23
+ var view_host_1 = require("./view-host");
24
+ Object.defineProperty(exports, "VIEW_WORKSPACE_META_KEY", { enumerable: true, get: function () { return view_host_1.VIEW_WORKSPACE_META_KEY; } });
25
25
  /** Module specifiers a view imports from the shell runtime. */
26
26
  exports.VIEW_RUNTIME_MODULES = [
27
27
  "react",
@@ -71,17 +71,29 @@ exports.VIEW_BUILD_OPTIONS = {
71
71
  * the runtime global, so the bundle carries none of the runtime. Structurally
72
72
  * typed: core does not depend on esbuild.
73
73
  */
74
- function viewRuntimePlugin() {
74
+ function viewRuntimePlugin(exportNames = {}) {
75
75
  return {
76
76
  name: "lobu-view-runtime",
77
77
  setup(build) {
78
78
  build.onResolve({ filter: /.*/ }, (args) => exports.VIEW_RUNTIME_MODULES.includes(args.path)
79
79
  ? { path: args.path, namespace: RUNTIME_NAMESPACE }
80
80
  : undefined);
81
- build.onLoad({ filter: /.*/, namespace: RUNTIME_NAMESPACE }, (args) => ({
82
- contents: `module.exports = globalThis[${JSON.stringify(exports.VIEW_RUNTIME_GLOBAL)}][${JSON.stringify(args.path)}];`,
83
- loader: "js",
84
- }));
81
+ build.onLoad({ filter: /.*/, namespace: RUNTIME_NAMESPACE }, (args) => {
82
+ const reference = `globalThis[${JSON.stringify(exports.VIEW_RUNTIME_GLOBAL)}][${JSON.stringify(args.path)}]`;
83
+ const names = exportNames[args.path];
84
+ return {
85
+ // Explicit trusted runtime exports let the compiler reject misspelled
86
+ // components, instead of installing a bundle that renders undefined.
87
+ contents: names
88
+ ? `const runtime = ${reference};\n${names
89
+ .map((name) => name === "default"
90
+ ? "export default runtime.default;"
91
+ : `export const ${name} = runtime[${JSON.stringify(name)}];`)
92
+ .join("\n")}`
93
+ : `module.exports = ${reference};`,
94
+ loader: "js",
95
+ };
96
+ });
85
97
  },
86
98
  };
87
99
  }
@@ -45,14 +45,16 @@ exports.DEVICE_AGENT_SPECS = [
45
45
  binaryName: "claude",
46
46
  promptDelivery: { kind: "flag", flag: "-p" },
47
47
  // Automation runs have a narrow completion contract; do not merge in the
48
- // user's global MCP config, and pre-approve exactly the two completion tools.
48
+ // user's global MCP config, and pre-approve only read-only SDK discovery
49
+ // plus the two completion tools. Keep in sync with the Claude Code ACP
50
+ // adapter's allowedTools in connector-worker's mac-device-daemon.
49
51
  mcpDelivery: {
50
52
  kind: "claude-config-file",
51
53
  flag: "--mcp-config",
52
54
  extraArgs: [
53
55
  "--strict-mcp-config",
54
56
  "--allowedTools",
55
- "mcp__lobu__query_sdk,mcp__lobu__run_sdk",
57
+ "mcp__lobu__search_sdk,mcp__lobu__query_sdk,mcp__lobu__run_sdk",
56
58
  ],
57
59
  },
58
60
  headlessArgs: [],
@@ -0,0 +1,73 @@
1
+ /**
2
+ * Error grouping for telemetry: one function decides which issue a failure
3
+ * belongs to, for spans and log records alike.
4
+ *
5
+ * The fingerprint follows Sentry's grouping rules: hash the parts that identify
6
+ * the defect and none that vary per occurrence. A stack groups by the names of
7
+ * its in-app functions, never by line numbers, which move on every deploy. A
8
+ * failure without a usable stack groups by where it was reported and its
9
+ * message after every identifier, number and quoted value is replaced by a
10
+ * placeholder, so one defect affecting many users or rows stays one issue.
11
+ *
12
+ * Raw messages can carry credentials or source data, so the report keeps only
13
+ * the parameterized message and the stack's frame locations. Both pass through
14
+ * the diagnostic scrubber first.
15
+ */
16
+ /** Bump when grouping changes, so old and new fingerprints are never compared. */
17
+ export declare const ERROR_GROUPING_VERSION = 1;
18
+ /**
19
+ * Who has to act: `user` is an expected rejection of the caller's input or
20
+ * access, `dependency` is a provider or upstream failing, `system` is ours.
21
+ */
22
+ export type ErrorKind = "system" | "user" | "dependency";
23
+ export interface StackFrame {
24
+ function: string | null;
25
+ file: string;
26
+ line: number | null;
27
+ column: number | null;
28
+ inApp: boolean;
29
+ }
30
+ export interface ErrorReport {
31
+ type: string;
32
+ code: string | null;
33
+ kind: ErrorKind;
34
+ /** Parameterized and scrubbed; safe to store. */
35
+ message: string;
36
+ /** Frame locations only, one per line; no message text. */
37
+ stacktrace: string;
38
+ fingerprint: string;
39
+ /** The exact string that was hashed, for explaining a grouping decision. */
40
+ grouping: string;
41
+ }
42
+ /** Replace every per-occurrence value in a message with a named placeholder. */
43
+ export declare function parameterizeMessage(text: string): string;
44
+ /** Parse a V8/Bun stack into frames, outermost last. Message lines are skipped. */
45
+ export declare function parseStackFrames(stack: string): StackFrame[];
46
+ /** Derive the kind from structure only: a code or an HTTP status, never prose. */
47
+ export declare function classifyErrorKind(code: string | null, httpStatus: number | null): ErrorKind;
48
+ export interface DescribeErrorOptions {
49
+ /**
50
+ * Where the failure was reported, e.g. `tool query_sql` or a logger's
51
+ * service. Groups failures that carry no usable stack.
52
+ */
53
+ scope: string;
54
+ /** Overrides the derived kind when the boundary knows better. */
55
+ kind?: ErrorKind;
56
+ }
57
+ /** Build the stored report and fingerprint for a thrown value or error-shaped object. */
58
+ export declare function describeError(error: unknown, options: DescribeErrorOptions): ErrorReport;
59
+ /** Span attributes for a report, using OpenTelemetry's exception conventions. */
60
+ export declare function errorReportAttributes(report: ErrorReport): Record<string, string>;
61
+ /**
62
+ * Stamp an error-level log record with its issue fingerprint. Both server
63
+ * loggers call this on the final record, so a failure logged through either
64
+ * groups the same way as the span that recorded it.
65
+ */
66
+ export declare function annotateErrorLogRecord(record: Record<string, unknown>): void;
67
+ /**
68
+ * The log-record fields for one report: the same safe fields a span carries,
69
+ * so a consumer of the log never needs the raw message to title or explain
70
+ * the issue. A writer that stamps these keeps them through the annotator.
71
+ */
72
+ export declare function errorReportLogFields(report: ErrorReport): Record<string, string>;
73
+ //# sourceMappingURL=error-report.d.ts.map
@@ -0,0 +1,346 @@
1
+ "use strict";
2
+ /**
3
+ * Error grouping for telemetry: one function decides which issue a failure
4
+ * belongs to, for spans and log records alike.
5
+ *
6
+ * The fingerprint follows Sentry's grouping rules: hash the parts that identify
7
+ * the defect and none that vary per occurrence. A stack groups by the names of
8
+ * its in-app functions, never by line numbers, which move on every deploy. A
9
+ * failure without a usable stack groups by where it was reported and its
10
+ * message after every identifier, number and quoted value is replaced by a
11
+ * placeholder, so one defect affecting many users or rows stays one issue.
12
+ *
13
+ * Raw messages can carry credentials or source data, so the report keeps only
14
+ * the parameterized message and the stack's frame locations. Both pass through
15
+ * the diagnostic scrubber first.
16
+ */
17
+ Object.defineProperty(exports, "__esModule", { value: true });
18
+ exports.ERROR_GROUPING_VERSION = void 0;
19
+ exports.parameterizeMessage = parameterizeMessage;
20
+ exports.parseStackFrames = parseStackFrames;
21
+ exports.classifyErrorKind = classifyErrorKind;
22
+ exports.describeError = describeError;
23
+ exports.errorReportAttributes = errorReportAttributes;
24
+ exports.annotateErrorLogRecord = annotateErrorLogRecord;
25
+ exports.errorReportLogFields = errorReportLogFields;
26
+ const node_crypto_1 = require("node:crypto");
27
+ const diagnostic_scrubber_1 = require("./utils/diagnostic-scrubber");
28
+ /** Bump when grouping changes, so old and new fingerprints are never compared. */
29
+ exports.ERROR_GROUPING_VERSION = 1;
30
+ const MAX_MESSAGE_INPUT = 8192;
31
+ const MAX_MESSAGE_OUTPUT = 300;
32
+ const MAX_STACK_FRAMES = 30;
33
+ /**
34
+ * A stack starts with the error's message, which can hold untrusted text of
35
+ * any size. The frame patterns backtrack, so only a bounded prefix is read and
36
+ * any line longer than a real frame is skipped before a pattern touches it.
37
+ */
38
+ const MAX_STACK_INPUT = 64 * 1024;
39
+ const MAX_STACK_LINES = 200;
40
+ const MAX_FRAME_LINE = 512;
41
+ const GROUPING_FRAMES = 3;
42
+ /**
43
+ * Ordered like Sentry's parameterizer (`grouping/parameterization.py`): the
44
+ * more specific shapes run first so a URL is not half-eaten by the number rule.
45
+ */
46
+ const PARAMETERS = [
47
+ // An HTTP credential in free text: the scrubber only knows keyed values.
48
+ ["token", /\b(?:bearer|basic)\s+[\w.~+/-]+=*/gi],
49
+ ["email", /[\w.+-]+@[\w-]+(?:\.[\w-]+)+/g],
50
+ ["url", /\b[a-z][a-z0-9+.-]*:\/\/[^\s"'<>]+/gi],
51
+ ["traceparent", /\b[0-9a-f]{2}-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}\b/gi],
52
+ [
53
+ "uuid",
54
+ /\b[0-9a-f]{8}-?[0-9a-f]{4}-?[0-9a-f]{4}-?[0-9a-f]{4}-?[0-9a-f]{12}\b/gi,
55
+ ],
56
+ ["hash", /\b[0-9a-f]{32,64}\b/gi],
57
+ [
58
+ "date",
59
+ /\b\d{4}-\d{2}-\d{2}(?:[T ]\d{2}:\d{2}(?::\d{2}(?:\.\d+)?)?(?:Z|[+-]\d{2}:?\d{2})?)?\b/g,
60
+ ],
61
+ ["ip", /\b(?:\d{1,3}\.){3}\d{1,3}(?::\d+)?\b/g],
62
+ ["hex", /\b0x[0-9a-f]+\b/gi],
63
+ // Generated identifiers: run, conversation and token ids mix letters and
64
+ // digits, so a 12+ character run with a digit is an id; requiring the digit
65
+ // spares long ordinary words. Any 24+ character run is treated as an id too,
66
+ // since secrets are not guaranteed to contain a digit and no word is that long.
67
+ ["id", /\b(?:(?=[\w-]*\d)(?=[\w-]*[a-z])[\w-]{12,}|[\w-]{24,})\b/gi],
68
+ ["quoted", /"[^"\n]{0,200}"|'[^'\n]{0,200}'|`[^`\n]{0,200}`/g],
69
+ ["num", /-?\b\d+(?:\.\d+)?/g],
70
+ ];
71
+ /** Replace every per-occurrence value in a message with a named placeholder. */
72
+ function parameterizeMessage(text) {
73
+ if (!text)
74
+ return "";
75
+ let out = text.length > MAX_MESSAGE_INPUT ? text.slice(0, MAX_MESSAGE_INPUT) : text;
76
+ out = String((0, diagnostic_scrubber_1.scrubDiagnosticValue)(out));
77
+ for (const [name, pattern] of PARAMETERS) {
78
+ out = out.replace(pattern, `<${name}>`);
79
+ }
80
+ out = out.split("\n").slice(0, 2).join(" ").replace(/\s+/g, " ").trim();
81
+ return out.length > MAX_MESSAGE_OUTPUT
82
+ ? out.slice(0, MAX_MESSAGE_OUTPUT)
83
+ : out;
84
+ }
85
+ const V8_FRAME = /^\s*at (?:(.+?) \()?(.+?):(\d+):(\d+)\)?\s*$/;
86
+ const V8_FRAME_NO_POSITION = /^\s*at (?:(.+?) \()?([^():]+)\)?\s*$/;
87
+ /**
88
+ * Make a frame's file portable: relative to the repo for workspace code, to
89
+ * `node_modules/` for dependencies, and the bare file name for any other
90
+ * absolute path, so no machine's checkout or home directory is recorded.
91
+ */
92
+ function normalizeFile(raw) {
93
+ const file = raw.replace(/^file:\/\//, "");
94
+ const dependency = file.lastIndexOf("/node_modules/");
95
+ if (dependency >= 0)
96
+ return file.slice(dependency + 1);
97
+ const workspace = file.indexOf("/packages/");
98
+ if (workspace >= 0)
99
+ return file.slice(workspace + 1);
100
+ if (file.startsWith("/") || /^[A-Za-z]:[\\/]/.test(file)) {
101
+ return file.split(/[\\/]/).pop() || file;
102
+ }
103
+ return file;
104
+ }
105
+ function isInAppFile(file) {
106
+ return !(file.includes("node_modules/") ||
107
+ file.startsWith("node:") ||
108
+ file.startsWith("internal/") ||
109
+ file === "native" ||
110
+ file === "<anonymous>");
111
+ }
112
+ function normalizeFunction(raw) {
113
+ if (!raw)
114
+ return null;
115
+ const fn = raw
116
+ .replace(/^async /, "")
117
+ .replace(/ \[as [^\]]+\]$/, "")
118
+ .trim();
119
+ return fn && fn !== "<anonymous>" ? fn : null;
120
+ }
121
+ /** Parse a V8/Bun stack into frames, outermost last. Message lines are skipped. */
122
+ function parseStackFrames(stack) {
123
+ const frames = [];
124
+ const lines = stack.slice(0, MAX_STACK_INPUT).split("\n", MAX_STACK_LINES);
125
+ for (const line of lines) {
126
+ if (line.length > MAX_FRAME_LINE)
127
+ continue;
128
+ const match = V8_FRAME.exec(line);
129
+ if (match) {
130
+ const file = normalizeFile(match[2] ?? "");
131
+ frames.push({
132
+ function: normalizeFunction(match[1]),
133
+ file,
134
+ line: Number(match[3]),
135
+ column: Number(match[4]),
136
+ inApp: isInAppFile(file),
137
+ });
138
+ }
139
+ else {
140
+ const bare = V8_FRAME_NO_POSITION.exec(line);
141
+ if (!bare)
142
+ continue;
143
+ const file = normalizeFile(bare[2] ?? "");
144
+ frames.push({
145
+ function: normalizeFunction(bare[1]),
146
+ file,
147
+ line: null,
148
+ column: null,
149
+ inApp: isInAppFile(file),
150
+ });
151
+ }
152
+ if (frames.length >= MAX_STACK_FRAMES)
153
+ break;
154
+ }
155
+ return frames;
156
+ }
157
+ function formatFrames(frames) {
158
+ return frames
159
+ .map((frame) => {
160
+ const position = frame.line == null
161
+ ? frame.file
162
+ : `${frame.file}:${frame.line}:${frame.column}`;
163
+ return frame.function
164
+ ? `at ${frame.function} (${position})`
165
+ : `at ${position}`;
166
+ })
167
+ .join("\n");
168
+ }
169
+ /**
170
+ * Frames that identify the defect: in-app, named, and not the error's own
171
+ * constructor (`new ToolUserError`), which every throw site of a class shares.
172
+ */
173
+ function groupingFrames(frames) {
174
+ return frames
175
+ .filter((frame) => frame.inApp && frame.function && !frame.function.startsWith("new "))
176
+ .slice(0, GROUPING_FRAMES)
177
+ .map((frame) => frame.function);
178
+ }
179
+ const USER_TOOL_CODES = new Set([
180
+ "AUTH_MISSING",
181
+ "BROWSER_INTERRUPTED",
182
+ "NOT_FOUND",
183
+ "VALIDATION",
184
+ "PERMISSION",
185
+ "MANUAL_EDIT_NOT_ALLOWED",
186
+ ]);
187
+ const DEPENDENCY_TOOL_CODES = new Set([
188
+ "AUTH_INVALID",
189
+ "RATE_LIMITED",
190
+ "UPSTREAM_TIMEOUT",
191
+ "UPSTREAM_5XX",
192
+ "NETWORK",
193
+ "UPSTREAM_UNAVAILABLE",
194
+ ]);
195
+ /** Derive the kind from structure only: a code or an HTTP status, never prose. */
196
+ function classifyErrorKind(code, httpStatus) {
197
+ if (code) {
198
+ if (USER_TOOL_CODES.has(code))
199
+ return "user";
200
+ if (DEPENDENCY_TOOL_CODES.has(code) || code.startsWith("PROVIDER_"))
201
+ return "dependency";
202
+ }
203
+ if (httpStatus != null)
204
+ return httpStatus < 500 ? "user" : "system";
205
+ return "system";
206
+ }
207
+ /**
208
+ * A structured code: upper-case or numeric (`VALIDATION`, `ERR_X`, SQLSTATE
209
+ * `23505`) or lower-case snake case. Digits are allowed only in the first form,
210
+ * so a generated id or credential in a `code` field is never kept.
211
+ */
212
+ function isErrorCode(value) {
213
+ return /^(?:[A-Z0-9][A-Z0-9_]{1,63}|[a-z][a-z_]{1,63})$/.test(value);
214
+ }
215
+ function readStatus(shape) {
216
+ for (const value of [shape.httpStatus, shape.statusCode, shape.status]) {
217
+ if (typeof value === "number" && value >= 100 && value <= 599)
218
+ return value;
219
+ }
220
+ return null;
221
+ }
222
+ /** Build the stored report and fingerprint for a thrown value or error-shaped object. */
223
+ function describeError(error, options) {
224
+ const shape = error && typeof error === "object"
225
+ ? error
226
+ : { message: String(error) };
227
+ const type = typeof shape.name === "string" && shape.name
228
+ ? shape.name
229
+ : typeof shape.type === "string" && shape.type
230
+ ? shape.type
231
+ : error instanceof Error
232
+ ? error.constructor.name
233
+ : typeof error === "string"
234
+ ? "Message"
235
+ : "UnknownError";
236
+ const code = typeof shape.code === "string" && isErrorCode(shape.code)
237
+ ? shape.code
238
+ : null;
239
+ const message = parameterizeMessage(typeof shape.message === "string" ? shape.message : "");
240
+ const frames = typeof shape.stack === "string" ? parseStackFrames(shape.stack) : [];
241
+ const kind = options.kind ?? classifyErrorKind(code, readStatus(shape));
242
+ const identity = groupingFrames(frames);
243
+ const parts = identity.length > 0
244
+ ? [
245
+ `v${exports.ERROR_GROUPING_VERSION}`,
246
+ type,
247
+ code ?? "",
248
+ `frames:${identity.join(">")}`,
249
+ ]
250
+ : [
251
+ `v${exports.ERROR_GROUPING_VERSION}`,
252
+ options.scope,
253
+ type,
254
+ code ?? "",
255
+ `message:${message}`,
256
+ ];
257
+ const grouping = parts.join("|");
258
+ return {
259
+ type,
260
+ code,
261
+ kind,
262
+ message,
263
+ stacktrace: formatFrames(frames),
264
+ fingerprint: (0, node_crypto_1.createHash)("sha256")
265
+ .update(grouping)
266
+ .digest("hex")
267
+ .slice(0, 32),
268
+ grouping,
269
+ };
270
+ }
271
+ /** Span attributes for a report, using OpenTelemetry's exception conventions. */
272
+ function errorReportAttributes(report) {
273
+ return {
274
+ "exception.type": report.type,
275
+ "exception.message": report.message,
276
+ ...(report.stacktrace ? { "exception.stacktrace": report.stacktrace } : {}),
277
+ ...(report.code ? { "error.code": report.code } : {}),
278
+ "error.kind": report.kind,
279
+ "error.fingerprint": report.fingerprint,
280
+ "error.grouping": report.grouping,
281
+ };
282
+ }
283
+ function isErrorShaped(value) {
284
+ if (!value || typeof value !== "object" || Array.isArray(value))
285
+ return false;
286
+ const shape = value;
287
+ return (typeof shape.message === "string" &&
288
+ (typeof shape.stack === "string" || typeof shape.name === "string"));
289
+ }
290
+ /** First error-shaped value in a log record's conventional slots, depth-bounded. */
291
+ function findLoggedError(value, depth = 0) {
292
+ if (depth > 3 || !value || typeof value !== "object")
293
+ return null;
294
+ if (isErrorShaped(value))
295
+ return value;
296
+ const candidates = Array.isArray(value)
297
+ ? value
298
+ : ["err", "error", "data", "cause"].map((key) => value[key]);
299
+ for (const candidate of candidates) {
300
+ const found = findLoggedError(candidate, depth + 1);
301
+ if (found)
302
+ return found;
303
+ }
304
+ return null;
305
+ }
306
+ const ERROR_LEVELS = new Set(["error", "fatal"]);
307
+ /**
308
+ * Stamp an error-level log record with its issue fingerprint. Both server
309
+ * loggers call this on the final record, so a failure logged through either
310
+ * groups the same way as the span that recorded it.
311
+ */
312
+ function annotateErrorLogRecord(record) {
313
+ if (typeof record.level !== "string" || !ERROR_LEVELS.has(record.level))
314
+ return;
315
+ // A writer that already described its error (with the scope of the span it
316
+ // fails in) keeps that grouping instead of the generic log-line one.
317
+ if (typeof record.error_fingerprint === "string")
318
+ return;
319
+ const service = typeof record.service === "string" ? record.service : "unknown";
320
+ const logged = findLoggedError(record);
321
+ const message = typeof record.message === "string"
322
+ ? record.message
323
+ : typeof record.msg === "string"
324
+ ? record.msg
325
+ : "";
326
+ const report = describeError(logged ?? { name: "LoggedError", message }, {
327
+ scope: `log ${service}`,
328
+ });
329
+ Object.assign(record, errorReportLogFields(report));
330
+ }
331
+ /**
332
+ * The log-record fields for one report: the same safe fields a span carries,
333
+ * so a consumer of the log never needs the raw message to title or explain
334
+ * the issue. A writer that stamps these keeps them through the annotator.
335
+ */
336
+ function errorReportLogFields(report) {
337
+ return {
338
+ error_fingerprint: report.fingerprint,
339
+ error_type: report.type,
340
+ error_kind: report.kind,
341
+ error_message: report.message,
342
+ error_grouping: report.grouping,
343
+ ...(report.code ? { error_code: report.code } : {}),
344
+ };
345
+ }
346
+ //# sourceMappingURL=error-report.js.map
@@ -1,6 +1,7 @@
1
1
  #!/usr/bin/env bun
2
2
  export * from "./agent-policy";
3
3
  export * from "./tool-trace-summary";
4
+ export * from "./tool-result";
4
5
  export * from "./shell-safety";
5
6
  export * from "./turn-control";
6
7
  export * from "./memory-flush";
@@ -24,8 +25,9 @@ export type { ProviderRegistryEntry, ProvidersConfigFile, } from "./integration-
24
25
  export { renderFallbackSystemContext, renderSkillMemorySection, } from "./lobu-guidance";
25
26
  export * from "./logger";
26
27
  export * from "./modules";
28
+ export * from "./error-report";
27
29
  export type { OtelConfig, Span, Tracer } from "./otel";
28
- export { createChildSpan, createRootSpan, createSpan, flushTracing, getCurrentSpan, getTraceparent, getTracer, initTracing, runInSpanContext, SpanKind, SpanStatusCode, shutdownTracing, withChildSpan, withSpan, } from "./otel";
30
+ export { createChildSpan, createRootSpan, createSpan, flushTracing, getCurrentSpan, getTraceparent, getTracer, initTracing, recordError, runInSpanContext, SpanKind, SpanStatusCode, shutdownTracing, withChildSpan, withSpan, } from "./otel";
29
31
  export { currentTraceLogFields, traceparentHeader } from "./trace-context";
30
32
  export type { ProviderConfigEntry, ProviderOAuthConfig, ProviderOAuthGrantKind, } from "./provider-config-types";
31
33
  export { isSdkCompat, type PiAiApi, resolveSdkCompat, SDK_COMPAT_PROTOCOLS, type SdkCompat, type SdkCompatProtocol, } from "./sdk-compat";
@@ -16,9 +16,10 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) {
16
16
  for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
17
17
  };
18
18
  Object.defineProperty(exports, "__esModule", { value: true });
19
- exports.withLobuFileParameters = exports.slugify = exports.titleFromSessionJsonl = exports.parseSessionEntries = exports.entryToMessage = exports.sanitizeSuggestionPrompts = exports.SUGGESTION_LIMITS = exports.isRefreshSuspended = exports.hasCredentialSource = exports.generateTraceId = exports.extractTraceId = exports.SDK_COMPAT_PROTOCOLS = exports.resolveSdkCompat = exports.isSdkCompat = exports.traceparentHeader = exports.currentTraceLogFields = exports.withSpan = exports.withChildSpan = exports.shutdownTracing = exports.SpanStatusCode = exports.SpanKind = exports.runInSpanContext = exports.initTracing = exports.getTracer = exports.getTraceparent = exports.getCurrentSpan = exports.flushTracing = exports.createSpan = exports.createRootSpan = exports.createChildSpan = exports.renderSkillMemorySection = exports.renderFallbackSystemContext = exports.BaseInstructionProvider = exports.CommandRegistry = exports.inferGrantKind = void 0;
19
+ exports.withLobuFileParameters = exports.slugify = exports.titleFromSessionJsonl = exports.parseSessionEntries = exports.entryToMessage = exports.sanitizeSuggestionPrompts = exports.SUGGESTION_LIMITS = exports.isRefreshSuspended = exports.hasCredentialSource = exports.generateTraceId = exports.extractTraceId = exports.SDK_COMPAT_PROTOCOLS = exports.resolveSdkCompat = exports.isSdkCompat = exports.traceparentHeader = exports.currentTraceLogFields = exports.withSpan = exports.withChildSpan = exports.shutdownTracing = exports.SpanStatusCode = exports.SpanKind = exports.runInSpanContext = exports.recordError = exports.initTracing = exports.getTracer = exports.getTraceparent = exports.getCurrentSpan = exports.flushTracing = exports.createSpan = exports.createRootSpan = exports.createChildSpan = exports.renderSkillMemorySection = exports.renderFallbackSystemContext = exports.BaseInstructionProvider = exports.CommandRegistry = exports.inferGrantKind = void 0;
20
20
  __exportStar(require("./agent-policy"), exports);
21
21
  __exportStar(require("./tool-trace-summary"), exports);
22
+ __exportStar(require("./tool-result"), exports);
22
23
  __exportStar(require("./shell-safety"), exports);
23
24
  __exportStar(require("./turn-control"), exports);
24
25
  __exportStar(require("./memory-flush"), exports);
@@ -54,6 +55,7 @@ Object.defineProperty(exports, "renderSkillMemorySection", { enumerable: true, g
54
55
  __exportStar(require("./logger"), exports);
55
56
  // Module system
56
57
  __exportStar(require("./modules"), exports);
58
+ __exportStar(require("./error-report"), exports);
57
59
  // OpenTelemetry tracing
58
60
  var otel_1 = require("./otel");
59
61
  Object.defineProperty(exports, "createChildSpan", { enumerable: true, get: function () { return otel_1.createChildSpan; } });
@@ -64,6 +66,7 @@ Object.defineProperty(exports, "getCurrentSpan", { enumerable: true, get: functi
64
66
  Object.defineProperty(exports, "getTraceparent", { enumerable: true, get: function () { return otel_1.getTraceparent; } });
65
67
  Object.defineProperty(exports, "getTracer", { enumerable: true, get: function () { return otel_1.getTracer; } });
66
68
  Object.defineProperty(exports, "initTracing", { enumerable: true, get: function () { return otel_1.initTracing; } });
69
+ Object.defineProperty(exports, "recordError", { enumerable: true, get: function () { return otel_1.recordError; } });
67
70
  Object.defineProperty(exports, "runInSpanContext", { enumerable: true, get: function () { return otel_1.runInSpanContext; } });
68
71
  Object.defineProperty(exports, "SpanKind", { enumerable: true, get: function () { return otel_1.SpanKind; } });
69
72
  Object.defineProperty(exports, "SpanStatusCode", { enumerable: true, get: function () { return otel_1.SpanStatusCode; } });
@@ -7,9 +7,10 @@ exports.createLogger = createLogger;
7
7
  // Use simple console.log-based logger by default (unbuffered, 12-factor compliant)
8
8
  // Set USE_WINSTON_LOGGER=true only if you need Winston features (file rotation, multiple transports)
9
9
  const USE_WINSTON_LOGGER = process.env.USE_WINSTON_LOGGER === "true";
10
- // Use JSON format for structured logging (better for Loki parsing in production)
10
+ // Use JSON format for structured logging (parsed by the production log pipeline)
11
11
  const USE_JSON_FORMAT = process.env.LOG_FORMAT === "json";
12
12
  const winston_1 = __importDefault(require("winston"));
13
+ const error_report_1 = require("./error-report");
13
14
  const trace_context_1 = require("./trace-context");
14
15
  const diagnostic_scrubber_1 = require("./utils/diagnostic-scrubber");
15
16
  function safeStringify(value, space) {
@@ -62,7 +63,7 @@ function createConsoleLogger(serviceName) {
62
63
  }
63
64
  const traceFields = (0, trace_context_1.currentTraceLogFields)();
64
65
  if (USE_JSON_FORMAT) {
65
- return safeStringify({
66
+ const record = {
66
67
  timestamp,
67
68
  level: lvl,
68
69
  service: serviceName,
@@ -72,7 +73,9 @@ function createConsoleLogger(serviceName) {
72
73
  ...(args.length > 0
73
74
  ? { data: args.length === 1 ? args[0] : args }
74
75
  : {}),
75
- });
76
+ };
77
+ (0, error_report_1.annotateErrorLogRecord)(record);
78
+ return safeStringify(record);
76
79
  }
77
80
  // Append remaining args
78
81
  if (args.length > 0) {
@@ -117,7 +120,7 @@ function createLogger(serviceName) {
117
120
  }
118
121
  const isProduction = process.env.NODE_ENV === "production";
119
122
  const level = process.env.LOG_LEVEL || "info";
120
- // JSON format for structured logging (better for Loki/Grafana parsing)
123
+ // JSON format for structured logging (parsed by the production log pipeline)
121
124
  const jsonFormat = winston_1.default.format.combine(winston_1.default.format.timestamp({ format: "YYYY-MM-DDTHH:mm:ss.SSSZ" }), winston_1.default.format.json());
122
125
  // Human-readable format for development
123
126
  const humanFormat = winston_1.default.format.combine(...(isProduction ? [] : [winston_1.default.format.colorize()]), winston_1.default.format.printf(({ timestamp, level, message, service, ...meta }) => {