work.newNetwork();
	static String host = "http://localhost:3001";

	@SuppressWarnings("resource")
	static GenericContainer<?> container = new GenericContainer<>("docker.io/node:lts-alpine3.23")
		.withCommand("npx -y @modelcontextprotocol/server-everything

ToxiproxyContainer toxiproxy = new ToxiproxyContainer("ghcr.io/shopify/toxiproxy:2.5.0").withNetwork(network)
		.withExposedPorts(8474, 3000);

	static Proxy proxy;

	static {
		container.start();

		toxiproxy.start();

		final ToxiproxyClient toxiproxyCli

@2025.12.18 sse")
		.withLogConsumer(outputFrame -> System.out.println(outputFrame.getUtf8String()))
		.withNetwork(network)
		.withNetworkAliases("everything-server")
		.withExposedPorts(3001)
		.waitingFor(Wait.forHttp("/").forStatusCode(404));

	static


sync fn tool_output_types_roundtrip() {
    with_doubleword_cassette(
        "conformance/tool_output_serialization",
        |client| async move {
            tool_output_serialization(client.completion_model(TOOL_MODEL), |builder| builder)

      invalid_tool_recovery(client.completion_model(TOOL_MODEL), |builder| builder)
            .await
            .expect("invalid tool call recovery should succeed");
    })
    .await;
}

#[tokio::test]
async fn hooks_rewrite_tool_flow() {
    with_doub

   .await
                .expect("tool output serialization should succeed");
        },
    )
    .await;
}

#[tokio::test]
async fn invalid_tool_call_recovers() {
    with_doubleword_cassette("conformance/invalid_tool_recovery", |client| async move {


              kwargs = request._session_kwargs.copy()
                    method = cast(SUPPORTED_HTTP_METHODS, kwargs.pop("method", "GET"))
                    response = await client._make_request(
                        method=method,

 session or other types - shouldn't happen in async context
                    raise TypeError(f"Session type {type(client)} not supported for async fetch")
            else:
                response = await session.fetch(url=request.url, **request._sessi

       url=request.url,
                        **kwargs,
                    )
                else:
                    # Sync


  md_content = ""

        # Add metadata
        metadata = exiftool_metadata(
            file_stream, exiftool_path=kwargs.get("exiftool_path")
        )
        if metadata:
            for f in [
                "Title",
                "Artist",

               "NumChannels",
                "SampleRate",
                "AvgBytesPerSec",
                "BitsPerSample",
            ]:
                if f in metadata:
                    md_content += f"{f}: {metadata[f]}\n"

        # Figure out

            "Author",
                "Band",
                "Album",
                "Genre",
                "Track",
                "DateTimeOriginal",
                "CreateDate",
                # "Duration", -- Wrong values when read from memory


 outCount = -1;
    int rc = diskann_prune_select(NULL, NULL, 0, alpha, max_neighbors,
                                   NULL, &outCount);
    assert(rc == 0 /* SQLITE_OK */);
    assert(outCount == 0);
    return 0;
  }

  /* Allocate arrays */
  int n =

    free(p_distances);
    free(outSelected);
    return 0;
  }

  /* Fill p_distances from fuzz data (sorted ascending for correct input) */
  for (int i = 0; i < n; i++) {
    uint8_t raw = fuzz_byte(&data, &size, (uint8_t)(i * 10));
    p_distances[i] =

 num_candidates;
  float *inter_distances = malloc(n * n * sizeof(float));
  float *p_distances = malloc(n * sizeof(float));
  int *outSelected = malloc(n * sizeof(int));
  if (!inter_distances || !p_distances || !outSelected) {
    free(inter_distances);


be 1", according to old info.
  // may need to be investigated.
  dst->rflags = src->EFlags | 0x2;
  dst->fcw = xsave->ControlWord;
  dst->fsw = xsave->StatusWord;
  dst->ftw = xsave->TagWord;
  dst->fop = xsave->ErrorOpcode;
  MemoryCopy(&dst->fip, &xsave

; n += 1, float_s += 1, float_d += 1)
    {
      MemoryCopy(float_d, float_s, sizeof(*float_d));
    }
  }
  {
    U128 *xmm_s = xsave->XmmRegisters;
    U512 *zmm_d = &dst->zmm0;
    for(U32 n = 0; n < 16; n += 1, xmm_s += 1, zmm_d += 1)
    {
      Memo

->ErrorOffset, sizeof(U64));
  MemoryCopy(&dst->fdp, &xsave->DataOffset, sizeof(U64));
  dst->mxcsr = xsave->MxCsr;
  dst->mxcsr_mask = xsave->MxCsr_Mask;
  {
    U128 *float_s = xsave->FloatRegisters;
    U80 *float_d = &dst->st0;
    for(U32 n = 0; n < 8


 err != nil {
		return nil, fmt.Errorf("can't load AWS config from environment: %w", err)
	}

	client := s3.NewFromConfig(cfg, func(o *s3.Options) {
		o.UsePathStyle = config.PathStyle
	})

	return &Store{
		s3:     client,
		bucket: config.BucketName,
	},

config Config
	if err := json.Unmarshal([]byte(data), &config); err != nil {
		return fmt.Errorf("%w: %w", store.ErrBadConfig, err)
	}

	if err := config.Valid(); err != nil {
		return fmt.Errorf("%w: %w", store.ErrBadConfig, err)
	}

	return nil
}

type C

 nil
}

func (Factory) Valid(data json.RawMessage) error {
	var


ngine.request_pause()
        else:
            raise RuntimeError("No active crawl to stop")

    def _setup_signal_handler(self) -> None:
        """Set up SIGINT handler for graceful pause."""

        def handler(_signum: int, _frame: Any) -> None:

signal(signal.SIGINT, handler)
        except ValueError:
            self._original_sigint_handler = None

    def _restore_signal_handler(self) -> None:
        """Restore original SIGINT handler."""
        if self._original_sigint_handler is not None:

         if self._engine:
                self._engine.request_pause()
            else:
                # No engine yet, just raise KeyboardInterrupt
                raise KeyboardInterrupt

        try:
            self._original_sigint_handler = signal.


        published_at: findDetailValue(rows, 'published_at') || note.date,
        views: findDetailValue(rows, '观看数') || String(note.views),
        likes: findDetailValue(rows, '点赞数') || String(note.likes),
        collects: findDetailValue(rows, '收藏数')

  comments: findDetailValue(rows, '评论数') || String(note.comments),
        shares: findDetailValue(rows, '分享数'),
        avg_view_time: findDetailValue(rows, '平均观看时长'),
        rise_fans: findDetailValue(rows, '涨粉数'),
        top_source: topSource.label,


handleSession handles an incoming SSH session by gathering system statistics
// and sending them to the hub. It signals connection events, determines the
// appropriate encoding format based on hub version, and exits with appropriate
// status codes.
func

 sessionCtx.SessionID()

	hubVersion := a.getHubVersion(sessionID, sessionCtx)

	// Legacy one-shot behavior for older hubs
	if hubVersion.LT(beszel.MinVersionAgentResponse) {
		if err := a.handleLegacyStats(s, hubVersion); err != nil {
			slog.Error("Erro

(a *Agent) handleSession(s ssh.Session) {
	a.connectionManager.eventChan <- SSHConnect

	sessionCtx := s.Context()
	sessionID :=


;
    expect(output).not.toContain('this artifact is skipped');
  });

  it('carries skipped and warning in the JSON-facing payload', () => {
    const context = loadChangeContext(tempDir, 'my-change');
    const instructions = generateInstructions(context

;
  });

  it('marks the specs dependency as skipped instead of done with files to read', () => {
    const context = loadChangeContext(tempDir, 'my-change');
    const tasksInstructions = generateInstructions(context, 'tasks');
    const specsDep = tasksI

, 'specs');

    expect(instructions.skipped).toBe(true);
    expect(instructions.warning).toContain('Do not create spec files')


g\/", url):
            # Not a Wikipedia URL
            return False

        if extension in ACCEPTED_FILE_EXTENSIONS:
            return True

        for prefix in ACCEPTED_MIME_TYPE_PREFIXES:
            if mimetype.startswith(prefix):

    def convert(
        self,
        file_stream: BinaryIO,
        stream_info: StreamInfo,
        **kwargs: Any,  # Options to pass to the converter
    ) -> DocumentConverterResult:
        # Parse the stream
        encoding = "utf-8" if stream_info

  return True

        # Not HTML content
        return False


push(value);
    }
    array.set_trailing(format!("\n{closing_indent}"));
    Value::Array(array)
}

fn json_object_to_inline(values: &serde_json::Map<String, serde_json::Value>) -> InlineTable {
    let mut table = InlineTable::new();
    for (key, value)

_json::Value::Array(values) => {
                json_array_to_value_with_indent(values, "      ", "    ", false)
            }
            _ => json_to_toml_value(value),
        };
        table.insert(key.as_str(), value);
    }
    format_inline_table_

 in values {
        let value = match value {
            serde


nput.namelist()}
        with zipfile.ZipFile(output_docx, mode="w") as zip_output:
            zip_output.comment = zip_input.comment
            for name, content in files.items():
                if name in pre_process_enable_files:

               updated_content = _pre_process_math(content)
                        # In the future, if there are more pre-processing steps, they can be added here
                        zip_output.writestr(name, updated_content)
                    excep

try:
                        # Pre-process the content


ction actually looking at
  // & doing?
#if 0
  // AVX
  {
    DWORD avx_length = 0;
    U8 *avx_s = (U8 *)LocateXStateFeature(ctx, XSTATE_AVX, &avx_length);
    if(avx_length == 16 * sizeof(U128))
    {
      U512 *zmm_d = &dst->zmm0;
      for(U32 n = 0;

 }
  }

  // AVX-512
  {
    // rjf: kmask
    DWORD kmask_length = 0;
    U64 *kmask_s = (U64*)LocateXStateFeature(ctx, XSTATE_AVX512_KMASK, &kmask_length);
    if(kmask_length == 8 * sizeof(U64))
    {
      U64 *kmask_d = &dst->k0;
      for(U32 n = 0


amInfo,
        **kwargs: Any,  # Options to pass to the converter
    ) -> DocumentConverterResult:
        file_path = stream_info.url or stream_info.local_path or stream_info.filename
        md_content = f"Content from the zip file `{file_path}`:\n\n"

               z_file_stream = io.BytesIO(zipObj.read(name))
                    z_file_stream_info = StreamInfo(
                        extension=os.path.splitext(name)[1],
                        filename=os.path.basename(name),
                    )

        with zipfile.ZipFile(file_stream, "r") as zipObj:
            for name in zipObj.namelist():
                try:


package name is reserved for a future project.

It does not provide a stable public API yet.
EOF

reserve_pkg() {
  local name="$1"
  if npm_authenticated view "$name" version >/dev/null 2>&1; then
    echo "already taken: $name"
    return 0
  fi
  if npm

 "$name" >/dev/null 2>&1; then
    echo "already reserved: $name"
    return 0
  fi

  local dir="$WORK/$name"
  mkdir -p "$dir"
  command cp -f "$WORK/README.md" "$dir/README.md"
  cat > "$dir/package.json" <<EOF
{
  "name": "$name",
  "version": "0.0.0",


t playwright.chromium.connect_over_cdp(cdp_url)

	# Get or create a page
	if playwright_browser and playwright_browser.contexts and playwright_browser.contexts[0].pages:
		playwright_page = playwright_browser.contexts[0].pages[0]
	elif playwright_browser:

 Playwright functions
tools = Tools()

@tools.registry.action(
	"Fill out a form using Playwright's precise form filling capabilities. This uses Playwright selectors for reliable form interaction.",
	param_model=PlaywrightFillFormAction,
)
async def playw

		context = await playwright_browser.new_context()
		playwright_page = await context.new_page()

# Create custom tools that use


    except BaseException as _:
            pass
        finally:
            file_stream.seek(cur_pos)
        return False

    def _feed_type(self, doc: Any) -> str | None:
        if doc.getElementsByTagName("rss"):
            return "rss"
        elif

):
            root = doc.getElementsByTagName("feed")[0]
            if root.getElementsByTagName("entry"):
                # An Atom feed must have a root element of <feed> and at least one <entry>
                return "atom"
        return None

    d


SON.stringify({
            id: 'closed-user', username: 'ClosedUser', disabled: true,
        }), { status: 200 })));
        await expect(cmd.func({ username: 'ClosedUser' })).rejects.toThrow(EmptyResultError);
    });

    it('picks the most-played perf

          count: { all: 100, win: 50, loss: 30, draw: 20 },
            perfs: {
                bullet: { games: 9000, rating: 2700 },
                blitz: { games: 100, rating: 2200 },
                puzzle: { games: 99999, rating: 2900 }, // ignored

 as topPerf', async () => {
        vi.stubGlobal('fetch', vi.fn().mockResolvedValue(new Response(JSON.stringify({
            id: 'someplayer',
            username: 'SomePlayer',
            createdAt: 1543000000000,
            seenAt: 1700000000000,


 be ignored');
  });
});

test('env var with control character in value is ignored', () => {
  withTmpPlugin((root, agentsDir) => {
    fs.writeFileSync(path.join(agentsDir, 'cavecrew-reviewer.md'), REVIEWER_FM, 'utf8');
    applyOverrides(root, { CAVECREW

;
    const out = fs.readFileSync(path.join(agentsDir, 'cavecrew-reviewer.md'), 'utf8');
    assert.strictEqual(out, REVIEWER_FM, 'control char in value should be ignored');
  });
});

test('missing agent file is silent no-op', () => {
  withTmpPlugin((roo


her to use the faster uvloop/winloop event loop implementation, if available.
        :param backend_options: Asyncio backend options to be used with `anyio.run`
        """
        backend_options = backend_options or {}
        if use_uvloop:

handler()
        try:
            return anyio.run(self.__run, backend="asyncio", backend_options=backend_options)
        finally:
            self._restore_signal_handler()

    async def stream(self) -> AsyncGenerator[Dict[str, Any], None]:
        """

 backend_options.update({"use_uvloop": True})

        # Set up SIGINT handler for graceful shutdown
        self._setup_signal_


-2.5 text-xs/relaxed has-data-[icon=inline-end]:pr-2 has-data-[icon=inline-start]:pl-2 [&_svg:not([class*='size-'])]:size-4",
        icon: "size-7 [&_svg:not([class*='size-'])]:size-3.5",
        "icon-xs": "size-5 rounded-sm [&_svg:not([class*='size-'])]

'])]:size-3",
        "icon-lg": "size-8 [&_svg:not([class*='size-'])]:size-4",
      },
    },
    defaultVariants: {
      variant: "default",
      size: "default",
    },
  }
)

function Button({
  className,
  variant = "default",
  size = "default",

:size-2.5",
        "icon-sm": "size-6 [&_svg:not([class*='size-


      ;;
    -h | --help)
      usage
      exit 0
      ;;
    --)
      shift
      PACKAGES+=("$@")
      break
      ;;
    -*)
      echo "unknown flag: $1" >&2
      usage >&2
      exit 2
      ;;
    *)
      PACKAGES+=("$1")
      shift
      ;;

  echo "refusing to run: this script reads 1Password and must run inside a persistent tmux session" >&2
  exit 2
fi

for bin in op jq node npm; do
  command -v "$bin" >/dev/null 2>&1 || {
    echo "missing required binary: $bin" >&2
    exit 2
  }
done

S

 esac
done

# Desktop fallback keeps the legacy item name unless one was named explicitly.
if [ -n "$ACCOUNT" ] && [ "$ITEM_EXPLICIT" -eq 0 ]; then
  ITEM="npmjs"
fi

if [ "${#PACKAGES[@]}" -eq 0 ]; then
  usage >&2
  exit 2
fi

if [ -z "${TMUX:-}" ]; then


 root
  'ponytail-mcp/package.json',   // MCP server (private, internal-only)
];

function readVersion(relPath) {
  try {
    // Strip a UTF-8 BOM some Windows editors prepend (breaks JSON.parse).
    const raw = fs.readFileSync(path.join(root, relPath), '

`);
  }
}

let failed = false;
const versions = VERSION_FILES.map((relPath) => {
  const version = readVersion(relPath);
  if (typeof version !== 'string' || !PINNED_SEMVER.test(version)) {
    console.error(`${relPath}: version must be a pinned X.Y.Z semv

utf8').replace(/^\uFEFF/, '');
    return JSON.parse(raw).version;
  } catch (e) {
    throw new Error(`${relPath}: ${e.message}


vide an API key'

	os.environ['OPENAI_API_KEY'] = api_key

	try:
		agent = Agent(
			task=task,
			llm=ChatOpenAI(model='gpt-4.1-mini'),
		)
		result = await agent.run()
		#  TODO: The result could be parsed better
		return str(result)
	except Exception as

-...', type='password')
				task = gr.Textbox(
					label='Task Description',
					placeholder='E.g., Find flights from New York to London for next week',
					lines=3,
				)
				model = gr.Dropdown(choices=['gpt-4.1-mini', 'gpt-5', 'o3', 'gpt-5-mini'], la

 e:
		return f'Error: {str(e)}'

def create_ui():
	with gr.Blocks(title='Browser Use GUI') as interface:
		gr.Markdown('# Browser Use Task Automation')

		with gr.Row():
			with gr.Column():
				api_key = gr.Textbox(label='OpenAI API Key', placeholder='sk


lone).
```

### Move Semantics — The Biggest Python Shock
```python
# Python — assignment copies the reference, not the data
def process(data):
    data.append(42)
    # Original list is modified!

my_list = [1, 2, 3]
process(my_list)
print(my_list)

![1, 2, 3];
let my_vec = process(my_vec);  // Ownership moves in and back out
println!("{:?}", my_vec);      // [1, 2, 3, 42]

// Or better — borrow instead of moving:
fn process_borrowed(data: &mut Vec<i32>) {
    data.push(42);
}

let mut my_vec = vec![1

# [1, 2, 3, 42] — modified by process!
```

```rust
// Rust — passing to a function MOVES ownership (for non-Copy types)
fn process(mut data: Vec<i32>) -> Vec<i32> {
    data.push(42);
    data  // Must return it to give ownership back!
}

let my_vec = vec


ema);

        let required = schema["required"].as_array().unwrap();
        assert!(required.contains(&json!("a")));
        assert!(required.contains(&json!("b")));
        assert_eq!(required.len(), 2);
    }

    #[test]
    fn test_sanitize_converts_

 mut schema = json!({
            "oneOf": [
                { "type": "string" },
                { "type": "number" }
            ]
        });

        sanitize_schema(&mut schema);

        assert!(schema.get("oneOf").is_none());
        assert!(schema


 provider crates; and
//! - examples and documentation that match the actual API, feature flags, and
//!   credential requirements.
//!
//! # Example
//! ```no_run
//! use rig_core::{
//!     client::{CompletionClient, ProviderClient},
//!     completion::

::Error>> {
//! // Initialize the OpenAI client
//! let openai = openai::Client::from_env()?;
//!
//! // Create a model and send a low-level completion request.
//! let model = openai.completion_model(openai::GPT_5_2);
//! let request = model
//!     .comp

{AssistantContent, CompletionModel},
//!     providers::openai,
//! };
//!
//! # async fn run() -> Result<(), Box<dyn std::error


o("test-server", "1.0.0")
			.capabilities(ServerCapabilities.builder().tools(true).build())
			.tools(McpServerFeatures.SyncToolSpecification.builder()
				.tool(duplicateTool)
				.callHandler((exchange, request) -> CallToolResult.builder().content(List.

() // Duplicate!
			)
			.build()).isInstanceOf(IllegalArgumentException.class)
			.hasMessage("Tool with name 'batch-varargs-tool' is already registered.");
	}

	@Test
	void testRemoveTool() {
		Tool tool = McpSchema.Tool.builder(TEST_TOOL_NAME, EMPTY_JSO

of()).isError(false).build())
				.build(),
					McpServerFeatures.SyncToolSpecification.builder()
						.tool(duplicateTool)
						.callHandler((exchange,
								request) -> CallToolResult.builder().content(List.of()).isError(false).build())
						.build


get viewport size
				if img.size != (self.size['width'], self.size['height']):
					# Use BICUBIC as it's faster than LANCZOS and good enough for screen recordings
					img = img.resize((self.size['width'], self.size['height']), Image.Resampling.BICUBIC)

size['width'], self.padded_size['height']), (0, 0, 0))
					# Center the image
					x_offset = (self.padded_size['width'] - self.size['width']) // 2
					y_offset = (self.padded_size['height'] - self.size['height']) // 2
					new_img.paste(img, (x_offset,

				# 2. Handle Padding (Macro block alignment for codecs)
				# Check if padding is actually needed
				if self.padded_size['width'] != self.size['width'] or self.padded_size['height'] != self.size['height']:
					new_img = Image.new('RGB', (self.padded_


p((w) => w.charAt(0).toUpperCase() + w.slice(1)).join(' ');

// Minimal quoting that satisfies both POSIX sh and cmd.exe: only display names
// (which contain a space) need wrapping; slugs, versions, paths, and flags don't.
const quote = (a) => (/[^\w./-]/

 passthrough = process.argv.slice(2);
const extra = passthrough.length ? ` (${passthrough.join(' ')})` : '';
console.log(`Publishing ${slugs.length} skills to ClawHub at version ${version}${extra}:`);

for (const slug of slugs) {
  const args = [
    'claw


determination on if the converter should attempt converting the document.
        This is primarily based on `stream_info` (typically, `stream_info.mimetype`, `stream_info.extension`).
        In cases where the data is retrieved via HTTP, the `stream_info

e.g., special converters for Wikipedia, YouTube etc).
        Finally, it is conceivable that the `stream_info.filename` might be used in cases
        where the filename is well-known (e.g., `Dockerfile`, `Makefile`, etc)

        NOTE: The method signatu

.url` might also be referenced to
        make a determination (


I settings

### Quick Setup

```bash
# Create virtual environment and install dependencies (from project root)
uv venv --python 3.11
source .venv/bin/activate  # On Windows: .venv\Scripts\activate
uv sync

# Set environment variables
export BROWSER_USE_API

BROWSER_USE_BASE_URL="https://api.browser-use.com/api/v1"  # Optional
export BROWSER_USE_TIMEOUT="30"  # Optional: request timeout in seconds

# Or use .env file (recommended)
cp examples/cloud/env.example .env
# Edit .env with your values

# Run examples


9"

        async with AsyncFetcherSession(proxy=proxy) as session:
            with (
                patch.object(session._async_curl_session, "request", new=AsyncMock()) as mocked_request,
                patch("scrapling.engines.static.ResponseFactory.

   assert mocked_request.call_args.kwargs["proxy"] == proxy

    @pytest.mark.asyncio
    async def test_per_request_proxy_overrides_session_proxy(self):
        """A per-request proxy must take precedence over the session-level proxy"""
        request_pr

from_http_request", return_value=MagicMock()),
            ):
                await session.get("http://example.com")


  |client| async move {
            streaming_structured_after_tool(client.completion_model(TOOL_MODEL), |builder| builder)
                .await
                .expect("streaming structured output after tool should succeed");
        },
    )
    .await

", |client| async move {
        structured_extraction(client.completion_model(DEFAULT_MODEL))
            .await
            .expect("structured extraction should succeed");
    })
    .await;
}

#[tokio::test]
async fn tool_choice_modes_roundtrip() {

;
}

#[tokio::test]
async fn structured_extraction_roundtrip() {
    with_doubleword_cassette("conformance/structured_extraction


_3_235b_a22b_thinking' in model_part:
		if model_part.endswith('_2507'):
			model = model_part.replace('qwen_3_235b_a22b_thinking_2507', 'qwen-3-235b-a22b-thinking-2507')
		else:
			model = model_part.replace('qwen_3_235b_a22b_thinking', 'qwen-3-235b-a22b-

 = model_part.replace('qwen_3_coder_480b', 'qwen-3-coder-480b')
	else:
		model = model_part.replace('_', '-')

	# OpenAI Models
	if provider == 'openai':
		api_key = os.getenv('OPENAI_API_KEY')
		return ChatOpenAI(model=model, api_key=api_key)

	# Azure Op

thinking-2507')
	elif 'qwen_3_coder_480b' in model_part:
		model


rock Anthropic adaptive-thinking model access"]
async fn streaming_emits_signature_only_adaptive_reasoning_regression() {
    let model = client().completion_model(anthropic_signature_only_model());
    let request = model
        .completion_request("What

   .build();
    let mut stream = model
        .stream(request)
        .await
        .expect("adaptive-thinking Bedrock stream should start");

    let mut reasoning_chunks = 0;
    let mut signature_chunks = 0;
    let mut signature_only_chunks = 0;

 is 2 + 2? Answer with only the number.")
        .max_tokens(2048)
        .additional_params(adaptive_thinking_params())


abel = mode === 'wenyan' ? 'wenyan-full' : mode;

// Read SKILL.md — the single source of truth for caveman behavior.
// Candidate locations, tried in order (#587/#589 — the old single '..' path
// resolved to <plugin_root>/src/skills/, which doesn't exist

 used the stale fallback ruleset):
//   1. $CLAUDE_PLUGIN_ROOT/skills/caveman/SKILL.md — Claude Code sets
//      CLAUDE_PLUGIN_ROOT when invoking plugin hooks; authoritative when present.
//   2. ../../skills/caveman/SKILL.md — hook at <plugin_root>/src/h


(response.usage.total_tokens, 4);
        let requests = http_client.requests();
        assert_eq!(requests[0].uri, "https://api.openai.com/v1/embeddings");
        let body: serde_json::Value =
            serde_json::from_slice(&requests[0].body).expect

        assert_eq!(body["dimensions"], serde_json::json!(1_536));
        assert_eq!(body["encoding_format"], serde_json::json!("float"));
        assert_eq!(body["user"], serde_json::json!("user-123"));
    }

    #[tokio::test]
    async fn openai_rejec


BinaryIO
from dataclasses import dataclass

from markitdown import StreamInfo

@dataclass
class OCRResult:
    """Result from OCR extraction."""

    text: str
    confidence: float | None = None
    backend_used: str | None = None
    error: str | None =

vision models (OpenAI-compatible)."""

    def __init__(
        self,
        client: Any,
        model: str,
        default_prompt: str | None = None,
    ) -> None:
        """
        Initialize LLM Vision OCR service.

        Args:
            clie

 None

class LLMVisionOCRService:
    """OCR service using LLM


        )

        if credential is None:
            if os.environ.get("AZURE_API_KEY") is None:
                credential = DefaultAzureCredential()
            else:
                credential = AzureKeyCredential(os.environ["AZURE_API_KEY"])

        self.doc_intel_client = DocumentIntelligenceClient(
            endpoint=self.endpoint,
            api_version=self.api_version,
            credential=credential,
        )

    def accepts(
        self,
        file_stream: BinaryIO,
        st

self.endpoint = endpoint
        self.api_version = api_version


fix).toBe(
      `git clone -- https://192.0.2.1/team.git ${q}${checkout}${q} && openspec store register ${q}${checkout}${q} --id missing-context`
    );

    // An invalid id wins over any declared remote.
    const invalid = await assembleReferenceIndex(

team.git' }],
      resolvedRoot: appRoot(),
      globalDataDir,
    });
    expect(invalid[0].status[0].code).toBe('reference_invalid_id');
    expect(invalid[0].status[0].fix).not.toContain('git clone');
  });

  it('refuses to render shell-unsafe remot

{
      references: [{ id: 'BAD ID', remote: 'https://192.0.2.1/


iteString(templ_7745c5c3_Buffer, 12, "
")
			if templ_7745c5c3_Err != nil {
				return templ_7745c5c3_Err
			}
		}
		templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 13, "
")
		if templ_7745c5c3_Err != nil {

`proofofwork.templ`, Line: 39, Col: 40}
		}
		_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var11))
		if templ_7745c5c3_Err != nil {
			return templ_7745c5c3_Err
		}
		templ_7745c5c3_Err = templruntime.WriteStr

return templ_7745c5c3_Err
		}
		var templ_7745c5c3_Var11 string
		templ_7745c5c3_Var11, templ_7745c5c3_Err = templ.JoinStringErrs(localizer.T("javascript_required"))
		if templ_7745c5c3_Err != nil {
			return templ.Error{Err: templ_7745c5c3_Err, FileName:


ecCtx{
			failoverLastSuccessModel: m1,
		})
		ctx, cancel := context.WithCancel(baseCtx)
		type result struct {
			sr  *schema.StreamReader[*schema.Message]
			err error
		}
		ch := make(chan result, 1)
		go func() {
			sr, err := w.Stream(ctx, []*schema.

, int32(1), atomic.LoadInt32(&m1Calls))
		require.Equal(t, int32(0), atomic.LoadInt32(&m2Calls))
		require.Equal(t, int32(0), atomic.LoadInt32(&shouldCalls))
	})
}

func TestTypedConsumeStream_EmptyAgenticStream(t *testing.T) {
	sr, sw := schema.Pipe[*sche

Message{schema.UserMessage("hi")})
			ch <- result{sr: sr, err: err}
		}()

		<-firstSent
		cancel()
		close(release)

		res := <-ch
		if res.sr != nil {
			res.sr.Close()
		}
		require.Nil(t, res.sr)
		require.ErrorIs(t, res.err, midErr)
		require.Equal(t


e problem, not instead of it — read the code it touches and trace the real flow first):\n' +
    '1. Does this need to be built at all? (YAGNI)\n' +
    '2. Does it already exist in this codebase? Reuse what is already here, do not re-write it.\n' +
    '3

already-installed dependency solve it? Use it.\n' +
    '6. Can this be one line? Make it one line.\n' +
    '7. Only then: write the minimum code that works.\n\n' +
    'Bug fix = root cause, not symptom: grep every caller of the function you touch and fi

. Does the standard library do this? Use it.\n' +
    '4. Does a native platform feature cover it? Use it.\n' +
    '5. Does an


   ],
    columns: ['id', 'title', 'type', 'year', 'date', 'language', 'authors', 'venue', 'citations', 'openAccess', 'openAccessUrl', 'referencedCount', 'doi', 'abstract', 'url'],
    func: async (args) => {
        const ref = requireWorkRef(args.id);

${OPENALEX_BASE}/works/${encodeURIComponent(ref)}?select=${SELECT_FIELDS}`);
        const w = await openalexFetch(url, 'openalex work');
        const authors = Array.isArray(w.authorships)
            ? w.authorships.map((a) => String(a?.author?.display_


news about AI",
    llm=ChatBrowserUse(),
)

async def main():
    history = await agent.run(max_steps=500)
```

- `task`: The task to automate
- `llm`: LLM instance (see `models.md`)
- `max_steps` (default: `500`): Maximum agent steps

## All Parameters

model_schema`: Pydantic model class for structured output validation

### Vision & Processing
- `use_vision` (default: `True`): `True` always includes screenshots, `"auto"` includes screenshot tool but only uses vision when requested, `False` never
- `visi

### Core Settings
- `tools`: Registry of tools the agent can call
- `skills` (or `skill_ids`): List of skill IDs to load (e.g., `['skill-uuid']` or `['*']` for all). Requires `BROWSER_USE_API_KEY`
- `browser`: Browser object for browser settings
- `output_


dDefaultMode,
  readQuietStartup,
  resolveSessionMode,
  writeDefaultMode,
} from "../index.js";

test("parsePonytailCommand falls back to full when invoked bare and default is off", () => {
  assert.deepEqual(parsePonytailCommand("", "off"), { type: "set

modes, status, and default subcommand", () => {
  assert.deepEqual(parsePonytailCommand("ultra", "full"), { type: "set-mode", mode: "ultra" });
  assert.deepEqual(parsePonytailCommand("status", "full"), { type: "status" });
  assert.deepEqual(parsePonytail

-mode", mode: "full" });
});

test("parsePonytailCommand parses


g resolution in getDefaultMode().
// Covers the resolution-order contract:
//   env CAVEMAN_DEFAULT_MODE → repo-local (.caveman/config.json or .caveman.json,
//   walking up to filesystem root) → user config → 'full'.
//
// Run: node tests/test_repo_local_

) never reads the developer's
// own ~/.config/caveman/config.json.
const tmpHome = fs.mkdtempSync(path.join(os.tmpdir(), 'caveman-userhome-'));
process.env.XDG_CONFIG_HOME = tmpHome;
delete process.env.CAVEMAN_DEFAULT_MODE;

const { getDefaultMode, findRe

config.js

const fs = require('fs');
const path = require('path');
const os = require('os');
const assert = require('assert');

// Isolate from the host's real user config: point XDG_CONFIG_HOME at a tmp dir
// before requiring the module so getConfigPath(


lue"})
        ).status == 200
        assert (
            await fetcher.post(
                urls["post_url"], data={"key": "value"}, stealthy_headers=True
            )
        ).status == 200
        assert (
            await fetcher.post(

       await fetcher.post(
                urls["post_url"],
                data={"key": "value"},
                stealthy_headers=True,
                follow_redirects=True,
                timeout=None,
            )
        ).status == 200

    async

      urls["post_url"], data={"key": "value"}, follow_redirects=True
            )
        ).status == 200
        assert (
            await fetcher.post(urls["post_url"], data={"key": "value"}, timeout=None)
        ).status == 200
        assert (


reamableLambda(func(ctx context.Context, in string) (output *schema.StreamReader[string], err error) {
			sr, sw := schema.Pipe[string](utf8.RuneCountInString(in))

			go func() {
				for _, field := range strings.Fields(in) {
					sw.Send(field, nil)

		v, err := in.Recv()
				if errors.Is(err, io.EOF) {
					break
				}

				if err != nil {
					return "", err
				}

				output += v
			}

			return output + output, nil
		})).
			AddLambda("two_key", CollectableLambda(func(ctx context.Context, in *schem

}
				sw.Close()
			}()

			return sr, nil
		}))
		c.AppendBranch(NewStreamChainBranch(streamCon).AddLambda("one_key", CollectableLambda(func(ctx context.Context, in *schema.StreamReader[string]) (output string, err error) {
			defer in.Close()
			for {


angesDir = path.join(testDir, 'openspec', 'changes');
      await fs.mkdir(changesDir, { recursive: true });

      await fs.mkdir(path.join(changesDir, 'change-1'), { recursive: true });
      await fs.writeFile(path.join(changesDir, 'change-1', 'proposal

      await fs.writeFile(path.join(changesDir, 'change-2', 'proposal.md'), '# Change 2');

      // Second call should return cached result (still only change-1)
      const secondResult = await provider.getChangeIds();
      expect(secondResult).toEqual([

.md'), '# Change 1');

      // First call
      const firstResult = await provider.getChangeIds();
      expect(firstResult).toEqual(['change-1']);

      // Add another change
      await fs.mkdir(path.join(changesDir, 'change-2'), { recursive: true });


can't contain multiple expression types")
)

type ExpressionOrList struct {
	Expression string   `json:"-" yaml:"-"`
	All        []string `json:"all,omitempty" yaml:"all,omitempty"`
	Any        []string `json:"any,omitempty" yaml:"any,omitempty"`
}

func (

0:
		var sb strings.Builder
		for i, pred := range eol.All {
			if i != 0 {
				fmt.Fprintf(&sb, " && ")
			}
			fmt.Fprintf(&sb, "( %s )", pred)
		}
		return sb.String()
	case len(eol.Any) != 0:
		var sb strings.Builder
		for i, pred := range eol.Any {

eol ExpressionOrList) String() string {
	switch {
	case len(eol.Expression) != 0:
		return eol.Expression
	case len(eol.All) !=


]
async fn main() -> Result<(), anyhow::Error> {
    // Initialize OpenAI client. Use this to generate embeddings (and generate test data for RAG demo).
    let openai_client = Client::from_env()?;

    // Select an embedding model.
    let model = openai_

lancedb-store").execute().await?;

    // Generate embeddings for the test data.
    let embeddings = EmbeddingsBuilder::new(model.clone())
        .documents(words())?
        // Note: need at least 256 rows in order to create an index so copy the definit

client.embedding_model(openai::TEXT_EMBEDDING_ADA_002);

    // Initialize LanceDB locally.
    let db = lancedb::connect("data/


-origin iframe extraction enabled
		# Use browser_session.get_browser_state_summary() instead of directly creating DomService
		# This goes through the proper event bus and watchdog system
		browser_state = await browser_session.get_browser_state_summary(

include_recent_events=False,
		)
		assert browser_state.dom_state is not None
		state = browser_state.dom_state

		print(f'\n📊 Found {len(state.selector_map)} total elements')

		# Find elements from different targets
		targets_found = set()
		main_page_el


ries(2)
                .build();

            // Fan out each input to the three extractors concurrently
            // (`try_join!`), and run up to four inputs at a time
            // (`buffer_unordered`) — the same concurrency the pipeline's

            "I love my dog, but I hate my cat.",
                "I'm going to the store to buy some milk.",
            ];
            let responses: Vec<String> = futures::stream::iter(inputs)
                .map(|text| {
                    let names_e

  // `try_parallel!` + `try_batch_call(4, ..)` provided.
            let inputs = vec![
                "Screw you Putin!",


a-[slot=field-group]:gap-4",
        className
      )}
      {...props}
    />
  )
}

const fieldVariants = cva(
  "group/field flex w-full gap-2 data-[invalid=true]:text-destructive",
  {
    variants: {
      orientation: {
        vertical: "flex-col *

:
          "flex-col *:w-full @md/field-group:flex-row @md/field-group:items-center @md/field-group:*:w-auto @md/field-group:has-[>[data-slot=field-content]]:items-start @md/field-group:*:data-[slot=field-label]:flex-auto [&>.sr-only]:w-auto @md/field-gro

:w-full [&>.sr-only]:w-auto",
        horizontal:
          "flex-row items-center has-[>[data-slot=field-content]]:items-start *:data-[slot=field-label]:flex-auto has-[>[data-slot=field-content]]:[&>[role=checkbox],[role=radio]]:mt-px",
        responsive


_rules>
<examples>
Here are examples of good output patterns. Use them as reference but never copy them directly.
<todo_examples>
  "write_file": {{
    "file_name": "todo.md",
    "content": "# ArXiv CS.AI Recent Papers Collection Task\n\n## Goal: Collect

.md file for storing paper data\n- [ ] Collect paper 1/20: The Automated LLM Speedrunning Benchmark\n- [x] Collect paper 2/20: AI Model Passport\n- [ ] Collect paper 3/20: Embodied AI Agents\n- [ ] Collect paper 4/20: Conceptual Topic Aggregation\n- [ ] Co

metadata for 20 most recent papers\n\n## Tasks:\n- [ ] Navigate to https://arxiv.org/list/cs.AI/recent\n- [ ] Initialize papers


emaId());

    return HttpResponse.of(HttpStatus.OK);
  }

  @Post("/versions")
  @AuthorizeExpression("""
      (#authorize(#principal, #registered_model, OWNER) &&
          #authorizeAny(#principal, #schema, OWNER, USE_SCHEMA) &&
          #authorizeAny

        @AuthorizeResourceKey(value = CATALOG, key = "catalog_name"),
        @AuthorizeResourceKey(value = SCHEMA, key = "schema_name"),
        @AuthorizeResourceKey(value = REGISTERED_MODEL, key = "model_name")
      })
      CreateModelVersion createMo

(#principal, #catalog, OWNER, USE_CATALOG))
      """)
  public HttpResponse createModelVersion(
      @AuthorizeResourceKeys({


e()
        .await?
        .contains(&"definitions".to_string())
    {
        db.open_table("definitions").execute().await?
    } else {
        db.create_table(
            "definitions",
            vec![as_record_batch(embeddings, model.ndims())?],

       .create_index(
                &["embedding"],
                lancedb::index::Index::IvfPq(IvfPqIndexBuilder::default()),
            )
            .execute()
            .await?;
    }

    // Define search_params params that will be used by the v

      )
        .execute()
        .await?
    };

    // See [LanceDB indexing](https://lancedb.github.io/lancedb/concepts/index_ivfpq/#product-quantization) for more information
    if table.index_stats("embedding").await?.is_none() {
        table


s+|back\s+to\s+|switch\s+(back\s+)?to\s+|return\s+to\s+)?normal\s+mode\b/.test(prompt) ||
      (/\bnormal\s+mode\b/.test(prompt) && /\bcaveman\b/.test(prompt));

    // Questions about caveman are not activation commands
    // ("what is caveman mode?", "

caveman
    // mode", "talk like caveman"). README tells users they can say these.
    // Also brevity requests ("less tokens", "be brief/terse", "fewer tokens",
    // "shorter answers") — but not when scoped to a single section
    // ("be brief in the s

does caveman lite drop articles?").
    const isQuestion =
      /^(what|whats|what's|how|why|when|where|who|does|do|did|is|are|can|could|would|should|tell me|explain)\b/.test(prompt);

    // Natural language activation (e.g. "activate caveman", "turn on


t result.exit_code == 0
            assert mock_fetch.call_args.kwargs["executable_path"] == "/opt/env-chromium"

    def test_invalid_arguments(self, runner, html_url):
        """Test invalid arguments handling"""
        # Missing required arguments

      """Test that comma-separated impersonate values are parsed correctly"""
        output_file = tmp_path / "output.md"

        with patch("scrapling.fetchers.Fetcher.get") as mock_get:
            mock_response = configure_selector_mock()

     result = runner.invoke(get)
        assert result.exit_code != 0

        _ = runner.invoke(get, [html_url, "output.invalid"])
        # Should handle the error gracefully

    def test_impersonate_comma_separated(self, runner, tmp_path, html_url):


tring(err));
    process.exitCode = 1;
    return;
  }

  if (typeof result === "string") {
    spinner?.stop();
    console.log(result);
    return;
  }

  const ctx = result as ContextResponse;

  if (ctx.error) {
    if (ctx.redirectUrl) {
      spinner

.cyan(ctx.redirectUrl)}`);
      log.info(`Run: ${pc.cyan(`ctx7 docs "${ctx.redirectUrl}" "${query}"`)}`);
      process.exitCode = 1;
      return;
    }

    spinner?.fail(ctx.message || ctx.error);
    if (!spinner) log.error(ctx.message || ctx.error);

?.warn("Library has been redirected");
      if (!spinner) log.warn("Library has been redirected");
      log.info(`New ID: ${pc


  };
}

function memberLine(member: WorkingSetMember): string {
  return `  ${member.id}  ${member.path}`;
}

function printHumanWorkingSet(workingSet: WorkingSet, declaredReferenceCount: number): void {
  const rootLabel = workingSet.root.store_id ?? path

.members.filter(
    (member) => member.role === 'referenced_store' && isAvailableMember(member)
  );
  const unavailable = workingSet.members.filter((member) => !isAvailableMember(member));

  if (availableStores.length > 0) {
    console.log('');
    con

.basename(workingSet.root.path);
  console.log(`Working context for ${rootLabel} (${workingSet.root.path})`);
  console.log('');
  console.log('OpenSpec root');
  console.log(`  ${rootLabel}  ${workingSet.root.path}`);

  const availableStores = workingSet


e:url';

const HERE = path.dirname(fileURLToPath(import.meta.url));
const REPO_ROOT = path.resolve(HERE, '..', '..');
const PS1 = fs.readFileSync(path.join(REPO_ROOT, 'install.ps1'), 'utf8');

// Strip comment lines so doc mentions of param()/path vars don

PS1.split('\n').filter(l => !/^\s*#/.test(l)).join('\n');

test('#565 install.ps1 has no top-level param block (everything inside a function)', () => {
  const beforeFunction = code.slice(0, code.indexOf('function '));
  assert.ok(code.includes('function '


);
const configPath = path.join(configDir, 'config.json');
fs.writeFileSync(configPath, JSON.stringify({ defaultMode: 'ultra' }));

const settingsPath = path.join(claudeDir, 'settings.json');
fs.writeFileSync(settingsPath, JSON.stringify({
  statusLine: {

/some/path/ponytail-statusline.sh' },
}));

const env = {
  HOME: home,
  USERPROFILE: home,
  XDG_CONFIG_HOME: path.join(temp, 'config-home'),
};

let result = runUninstall(env);
assert.equal(result.status, 0, result.stderr);
assert.equal(fs.existsSync(fl


		return 'groq'

	@property
	def name(self) -> str:
		return str(self.model)

	def _get_usage(self, response: ChatCompletion) -> ChatInvokeUsage | None:
		usage = (
			ChatInvokeUsage(
				prompt_tokens=response.usage.prompt_tokens,
				completion_tokens=

			else None
		)
		return usage

	@overload
	async def ainvoke(
		self, messages: list[BaseMessage], output_format: None = None, **kwargs: Any
	) -> ChatInvokeCompletion[str]: ...

	@overload
	async def ainvoke(self, messages: list[BaseMessage], output_for

response.usage.completion_tokens,
				total_tokens=response.usage.total_tokens,
				prompt_cached_tokens=None,  # Groq doesn't support cached tokens
				prompt_cache_creation_tokens=None,
				prompt_image_tokens=None,
			)
			if response.usage is not None


delProviderError
from browser_use.llm.messages import BaseMessage
from browser_use.llm.ollama.serializer import OllamaMessageSerializer
from browser_use.llm.views import ChatInvokeCompletion

T = TypeVar('T', bound=BaseModel)

@dataclass
class ChatOllama(

around Ollama's chat model.
	"""

	model: str

	# # Model params
	# TODO (matic): Why is this commented out?
	# temperature: float | None = None

	# Client initialization parameters
	host: str | None = None
	timeout: float | httpx.Timeout | None = None
	cl


alue) => cleanText(value)).filter(Boolean))];
}
export function buildProvenance(sourceUrl) {
    return {
        source_url: sourceUrl,
        fetched_at: new Date().toISOString(),
        strategy: STRATEGY,
    };
}
export function buildSearchUrl(query

be empty');
    }
    return `${SEARCH_URL_PREFIX}${encodeURIComponent(normalized)}`;
}
export function extractAsin(input) {
    const normalized = cleanText(input);
    if (!normalized)
        return null;
    if (/^[A-Z0-9]{10}$/i.test(normalized)) {

) {
    const normalized = cleanText(query);
    if (!normalized) {
        throw new ArgumentError('amazon search query cannot


);

      for (const subcmd of cmd.subcommands) {
        lines.push(`${indent}    "${subcmd.name}" {`);
        lines.push(...this.generateArgumentCompletion(subcmd, indent + '        ', 3));
        lines.push(`${indent}    }`);
      }

      lines.push

.push(...this.generateArgumentCompletion(cmd, indent, 2));
    }

    return lines;
  }

  /**
   * Generate argument completion (flags and positional)
   */
  private generateArgumentCompletion(
    cmd: CommandDefinition,
    indent: string,
    firstPos

(`${indent}}`);
    } else {
      // No subcommands
      lines


ingle, production-quality system.

## Table of Contents

### Part I: Type-Level Patterns

**[1. Generics — The Full Picture](ch01-generics-the-full-picture.md)** 🟢
Monomorphization, code bloat trade-offs, generics vs enums vs trait objects, const generics,

)** 🟡
Zero-cost type safety, compile-time state machines, builder patterns, config traits.

**[4. PhantomData — Types That Carry No Data](ch04-phantomdata-types-that-carry-no-data.md)** 🔴
Lifetime branding, unit-of-measure pattern, drop check, variance.

#

 `const fn`.

**[2. Traits In Depth](ch02-traits-in-depth.md)** 🟡
Associated types, GATs, blanket impls, marker traits, vtables, HRTBs, extension traits, enum dispatch.

**[3. The Newtype and Type-State Patterns](ch03-the-newtype-and-type-state-patterns.md


om markitdown import StreamInfo

@dataclass
class OCRResult:
    """Result from OCR extraction."""

    text: str
    confidence: float | None = None
    backend_used: str | None = None
    error: str | None = None

class LLMVisionOCRService:
    """OCR

(OpenAI-compatible)."""

    def __init__(
        self,
        client: Any,
        model: str,
        default_prompt: str | None = None,
    ) -> None:
        """
        Initialize LLM Vision OCR service.

        Args:
            client: OpenAI-com


ng.T) {
				fin, err := os.Open(filepath.Join("..", "config", "testdata", "good", st.Name()))
				if err != nil {
					t.Fatal(err)
				}
				defer fin.Close() //nolint:errcheck

				ctx := thothmock.WithMockThoth(t)
				if _, err := ParseConfig(ctx, fin,

(t *testing.T) {
				fin, err := os.Open(filepath.Join("..", "config", "testdata", "good", st.Name()))
				if err != nil {
					t.Fatal(err)
				}
				defer fin.Close() //nolint:errcheck

				if _, err := ParseConfig(t.Context(), fin, fin.Name(), anubis.De

fin.Name(), anubis.DefaultDifficulty, "info", false); err != nil {
					t.Fatal(err)
				}
			})

			t.Run("without-thoth", func


nable|start|turn on|use|switch to|want|give me)\b[^.]{0,40}\bcaveman\b/.test(prompt) ||
          /\btalk like\b[^.]{0,40}\bcaveman\b/.test(prompt) ||
          /\bcaveman\s+mode\s+(on|please|now)\b/.test(prompt) ||
          /^caveman(\s+mode)?\s*[.!]*$/.

be terse|shorter answers)\b(?!\s+(in|for|on|about|when|during|with)\b)/.test(prompt)) {
        const mode = getDefaultMode();
        if (mode !== 'off') {
          recordModeChange(claudeDir, mode); // #601: timestamped transition log
          safeWrit

test(prompt) ||
          /\b(less tokens|fewer tokens|be brief|


_model())
        .with_prompt_caching();
    let agent = AgentBuilder::new(model)
        .preamble(
            "You must call tools when the user asks for their result. \
             After a tool result is available, answer with the exact result.",

")
        .await
        .expect("adaptive-thinking prompt-caching tool roundtrip should succeed");

    assert_contains_all_case_insensitive(&response, &[ALPHA_SIGNAL_OUTPUT]);
}

#[tokio::test]
#[ignore = "requires AWS credentials and Bedrock Anthropic

     )
        .max_tokens(2048)
        .additional_params(adaptive_thinking_params())
        .tool(AlphaSignal)
        .build();

    let response = agent
        .prompt("Call `lookup_harbor_label` exactly once, then answer with the exact tool output.


 = createRegisteredModelResponse.getId();
    initializeHierarchicalAuthorization(modelId, schemaInfo.getSchemaId());

    return HttpResponse.ofJson(createRegisteredModelResponse);
  }

  private static final String LIST_AND_GET_AUTH_EXPRESSION = """

#principal, #catalog, OWNER) ||
      (#authorize(#principal, #catalog, USE_CATALOG) && #authorize(#principal, #schema, OWNER)) ||
      (#authorizeAny(#principal, #registered_model, OWNER, EXECUTE) &&
          #authorize(#principal, #schema, USE_SCHEMA)

  #authorize(#principal, #metastore, OWNER) ||
      #authorize(


 touched):
//  - fenced code blocks (``` ... ```)
//  - inline code (`...`)
//  - URLs (https?://...)
//  - filesystem paths (anything with `/` or `\`)
//  - "code-looking" tokens (parens at end, semicolons, JSON-like braces)
//  - identifiers in CamelCase

//
// Compression applied to everything else:
//  - drop articles (a, an, the)
//  - drop filler words (just, really, basically, actually, simply, quite, very)
//  - drop pleasantries (please, kindly, thank you, sure, certainly)
//  - drop hedging (perhap


eld-label"
      className={cn(
        "group/field-label peer/field-label flex w-fit gap-2 leading-snug group-data-[disabled=true]/field:opacity-50 has-data-checked:bg-primary/5 has-[>[data-slot=field]]:rounded-md has-[>[data-slot=field]]:border *:data-[

",
        className
      )}
      {...props}
    />
  )
}

function FieldTitle({ className, ...props }: React.ComponentProps<"div">) {
  return (
    <div
      data-slot="field-label"
      className={cn(
        "flex w-fit items-center gap-2 text-xs/r

slot=field]:p-2 dark:has-data-checked:bg-primary/10",
        "has-[>[data-slot=field]]:w-full has-[>[data-slot=field]]:flex-col


      Files.writeString(keyId, Hex.encodeHexString(keyIdBytes), StandardOpenOption.CREATE);
    }
  }

  public Algorithm algorithmRSA()
      throws NoSuchAlgorithmException, InvalidKeySpecException, IOException {
    return Algorithm.RSA512(rsaPublicKey(

     throws NoSuchAlgorithmException, InvalidKeySpecException, IOException {
    if (Files.notExists(rsa512PublicKey)) {
      log.info("No JWT public signing key present.");
      return null;
    }
    byte[] keyBytes = Files.readAllBytes(rsa512PublicKey

), rsaPrivateKey());
  }

  public RSAPublicKey rsaPublicKey()


*ExtParserConfig) (*ExtParser, error) {
	if conf == nil {
		conf = &ExtParserConfig{}
	}

	p := &ExtParser{
		parsers:        conf.Parsers,
		fallbackParser: conf.FallbackParser,
	}

	if p.fallbackParser == nil {
		p.fallbackParser = TextParser{}
	}

	if p

make(map[string]Parser)
	}

	return p, nil
}

// GetParsers returns a copy of the registered parsers.
// It is safe to modify the returned parsers.
func (p *ExtParser) GetParsers() map[string]Parser {
	res := make(map[string]Parser, len(p.parsers))
	for k,


llenges.cloudflare.com/cdn-cgi/challenge-platform/orchestrate/jsch/v1",
            "http://challenges.cloudflare.com/cdn-cgi/challenge-platform/scripts/abc"
        ]

        for url in test_urls:
            assert __CF_PATTERN__.search(url) is not None

            "https://example.com/challenge",
            "https://cloudflare.com/something",
            "https://challenges.cloudflare.com/other-path"
        ]

        for url in non_matching_urls:
            assert __CF_PATTERN__.search(url) is None

        # Test non-matching URLs
        non_matching_urls = [


                .collect();
            assert!(
                !text.trim().is_empty(),
                "follow-up turn should produce text after replaying redacted thinking"
            );
        },
    )
    .await;
}

#[tokio::test]
async fn redacted

 model
                .completion_request(redacted_thinking_prompt())
                .max_tokens(4096)
                .additional_params(thinking_params())
                .build();

            let mut stream = model
                .stream(request)

_thinking_streaming() {
    with_anthropic_cassette(
        "messages_thinking/redacted_thinking_streaming",
        |client| async move {
            let model = client.completion_model(anthropic::completion::CLAUDE_SONNET_4_6);
            let request =


efault), or headful/visible mode.
        :param disable_resources: Drop requests for unnecessary resources for a speed boost.
        :param blocked_domains: A set of domain names to block requests to. Subdomains are also matched (e.g., ``"example.com"``

 with ``blocked_domains``.
        :param dns_over_https: Route DNS queries through Cloudflare's DNS-over-HTTPS to prevent DNS leaks when using proxies.
        :param useragent: Pass a useragent string to be used. Otherwise the fetcher will generate a rea

blocks ``"sub.example.com"`` too).
        :param block_ads: Block requests to ~3,500 known ad/tracking domains. Can be combined


   spacing?: number
    orientation?: "horizontal" | "vertical"
  }) {
  return (
    <ToggleGroupPrimitive
      data-slot="toggle-group"
      data-variant={variant}
      data-size={size}
      data-spacing={spacing}
      data-orientation={orientation}

 className={cn(
        "group/toggle-group flex w-fit flex-row items-center gap-[--spacing(var(--gap))] rounded-md data-[size=sm]:rounded-[min(var(--radius-md),8px)] data-vertical:flex-col data-vertical:items-stretch",
        className
      )}
      {..

style={{ "--gap": spacing } as React.CSSProperties}


ks ongoing network requests."""

	def __init__(self, request_id: str, start_time: float, url: str, method: str, resource_type: str | None = None):
		self.request_id = request_id
		self.start_time = start_time
		self.url = url
		self.method = method
		self.

):
	"""Monitors browser health for crashes and network timeouts using CDP."""

	# Event contracts
	LISTENS_TO: ClassVar[list[type[BaseEvent]]] = [
		BrowserConnectedEvent,
		BrowserStoppedEvent,
		TabCreatedEvent,
		TabClosedEvent,
	]
	EMITS: ClassVar[list

resource_type = resource_type

class CrashWatchdog(BaseWatchdog


log(`\nself-test: ${ok}/${TASKS.length} instruments valid${bad ? ` — ${bad} BROKEN` : ''}`);
  process.exit(bad ? 1 : 0);
}

(async () => {
  const arms = { baseline: null, ponytail: SKILL };
  const grid = {};
  for (const t of TASKS) {
    grid[t.name] =

 0, err = 0;
      for (let i = 0; i < N; i++) {
        const res = await call(arms[arm], t.prompt);
        if (res.err) { err++; continue; }
        if (checkPy(pyBlock(res.text), t)) pass++;
      }
      grid[t.name][arm] = { pass, n: N - err };
    }

 {};
    for (const arm of Object.keys(arms)) {
      let pass =


: Literal['DEFAULT', 'LLM', 'TOOL'] = 'DEFAULT',
	**kwargs: Any,
) -> Callable[[F], F]:
	"""
	Debug-only observability decorator that only traces when in debug mode.

	This decorator will use lmnr's observe decorator if both lmnr is installed
	AND we're in

of the span/trace
	    ignore_input: Whether to ignore function input parameters in tracing
	    ignore_output: Whether to ignore function output in tracing
	    metadata: Additional metadata to attach to the span
	    **kwargs: Additional parameters passe

 debug mode, otherwise it will be a no-op.

	Debug mode is determined by:
	- DEBUG environment variable set to 1/true/yes/on
	- BROWSER_USE_DEBUG environment variable set to 1/true/yes/on
	- Root logging level set to DEBUG or lower

	Args:
	    name: Name


SKILLS = ['skills/ponytail/SKILL.md'];
// Gemini CLI auto-loads this exact path for extension hooks. Ponytail's
// Claude/Codex hook map uses events Gemini does not support, so it must stay
// behind the host-specific plugin manifests instead.
const GEMINI

trust boundaries',
  'naive heuristic',
];

function read(relPath) {
  return fs.readFileSync(path.join(root, relPath), 'utf8');
}

// Read inside each test (not at module scope) so a missing or malformed manifest
// surfaces as a clean per-test assertion

_AUTO_HOOKS = 'hooks/hooks.json';
// Same load-bearing phrases asserted by scripts/check-rule-copies.js: the file
// contextFileName points at must actually carry the rules, not just exist.
const RULE_INVARIANTS = [
  'lazy senior',
  'input validation at


 output_docx = BytesIO()
    # The files that need to be pre-processed from .docx
    pre_process_enable_files = [
        "word/document.xml",
        "word/footnotes.xml",
        "word/endnotes.xml",
    ]
    with zipfile.ZipFile(input_docx, mode="r")

docx, mode="w") as zip_output:
            zip_output.comment = zip_input.comment
            for name, content in files.items():
                if name in pre_process_enable_files:
                    try:
                        # Pre-process the conten

as zip_input:
        files = {name: zip_input.read(name) for name in zip_input.namelist()}
        with zipfile.ZipFile(output_


: React.ComponentProps<"p">) {
  return (
    <p
      data-slot="field-description"
      className={cn(
        "text-left text-xs/relaxed leading-normal font-normal text-muted-foreground group-has-data-horizontal/field:text-balance [[data-variant=legend

>a]:underline [&>a]:underline-offset-4 [&>a:hover]:text-primary",
        className
      )}
      {...props}
    />
  )
}

function FieldSeparator({
  children,
  className,
  ...props
}: React.ComponentProps<"div"> & {
  children?: React.ReactNode
}) {


t(stats.changeCache.age).toBeUndefined();
      expect(stats.specCache.age).toBeUndefined();
    });

    it('should report valid cache after data is fetched', async () => {
      const changesDir = path.join(testDir, 'openspec', 'changes');
      await fs

true });

      await fs.mkdir(path.join(changesDir, 'change-1'), { recursive: true });
      await fs.writeFile(path.join(changesDir, 'change-1', 'proposal.md'), '# Change 1');

      await provider.getChangeIds();

      const stats = provider.getCacheSt


        new ModelVersionsApi(TestUtils.createApiClient(principal1Config));
    ModelVersionsApi principal2VersionsApi =
        new ModelVersionsApi(TestUtils.createApiClient(principal2Config));

    // Grant USE SCHEMA and CREATE MODEL to principal-1

 SecurableType.SCHEMA, "cat_pr1.sch_pr1", Privileges.CREATE_MODEL);

    // Grant USE SCHEMA to principal-2
    grantPermissions(PRINCIPAL_2, SecurableType.SCHEMA, "cat_pr1.sch_pr1", Privileges.USE_SCHEMA);

    // TEST: Create registered model as principa

grantPermissions(PRINCIPAL_1, SecurableType.SCHEMA, "cat_pr1.sch_pr1", Privileges.USE_SCHEMA);
    grantPermissions(PRINCIPAL_1,


dels.definition;

import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
import com.fasterxml.jackson.databind.PropertyNamingStrategies;
import com

.Data;
import lombok.EqualsAndHashCode;
import lombok.ToString;

/**
 * Subworkflow step definition with additional fields.
 *
 * <p>Note that there is no step retry for subworkflow step. It might fail due to various reasons,
 * e.g. invalid SEL expression


ed.', 'Pass --email <address>');
        }
        if (dryRun) {
            return summarizeSubmission({
                pdfFile,
                email,
                venue,
                message: 'Input validation passed. No remote request was sent.'

  const { response: uploadUrlResponse, payload: uploadUrlPayload } = await requestJson('/api/get-upload-url', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({
                file

,
                dryRun: true,
            });
        }


 {
        // ignore
    }
    return fallback;
}
function toDownloadItems(offerId, assets) {
    const items = [];
    const pushImages = (urls, prefix) => {
        urls.forEach((url, index) => {
            items.push({
                type: 'image',

  pushImages(assets.detail_images, 'detail');
    pushImages(assets.other_images, 'other');
    assets.videos.forEach((url, index) => {
        items.push({
            type: 'video',
            url,
            filename: `${offerId}_video_${String(index

              url,
                filename: `${offerId}_${prefix}_${String(index + 1).padStart(2, '0')}${extFromUrl(url, '.jpg')}`,
            });
        });
    };
    pushImages(assets.main_images, 'main');
    pushImages(assets.sku_images, 'sku');


nc (f Factory) Build(ctx context.Context, data json.RawMessage) (store.Interface, error) {
	var config Config

	if err := json.Unmarshal([]byte(data), &config); err != nil {
		return nil, fmt.Errorf("%w: %w", store.ErrBadConfig, err)
	}

	if err := config.

 f.Client != nil {
		return &Store{
			s3:     f.Client,
			bucket: config.BucketName,
		}, nil
	}

	cfg, err := awsConfig.LoadDefaultConfig(ctx)
	if err != nil {
		return nil, fmt.Errorf("can't load AWS config from environment: %w", err)
	}

	client := s3

Valid(); err != nil {
		return nil, fmt.Errorf("%w: %w", store.ErrBadConfig, err)
	}

	if config.BucketName == "" {
		return nil, fmt.Errorf("%w: %s", store.ErrBadConfig, ErrNoBucketName)
	}

	// If a client was injected (e.g., tests), use it directly.
	if


n=xpath.condition)
        x.textnode = textnode
        x.attribute = attribute
        return x

    def __str__(self) -> str:
        path = super().__str__()
        if self.textnode:
            if path == "*":  # pragma: no cover
                path

no cover
                path = path[:-3] + "text()"
            else:
                path += "/text()"

        if self.attribute is not None:
            if path.endswith("::*/*"):  # pragma: no cover
                path = path[:-2]
            path +=

 = "text()"
            elif path.endswith("::*/*"):  # pragma:


lt.versions.join(", ")}`);
  }

  if (result.source) {
    formattedResult.push(`- Source: ${result.source}`);
  }

  return formattedResult.join("\n");
}

export function formatSearchResults(searchResponse: SearchResponse): string {
  if (!searchResponse.

 documentation libraries found matching your query.";
  }

  const parts: string[] = [];

  if (searchResponse.searchFilterApplied) {
    parts.push(
      "**Note:** Your results only include libraries matching your teamspace's library filters. To adjust

results || searchResponse.results.length === 0) {
    return "No


workflow_run_id, step_id)
);
CREATE TABLE IF NOT EXISTS maestro_step_breakpoint (
     system_generated          BOOL NOT NULL, -- True when inserting paused step attempt due to breakpoint. False to denote explicit user actions.
     workflow_id

    version                   INT8 NOT NULL,
     instance_id               INT8 NOT NULL,
     run_id                    INT8 NOT NULL,
     step_id                   TEXT NOT NULL COLLATE "C",
     step_attempt_id           INT8 NOT NULL,
     create_ts


ld_process');

const HOOK_PATH = path.resolve(__dirname, '..', 'src', 'hooks', 'caveman-mode-tracker.js');
const CLEAN_EXIT = 0;

let passed = 0;
let failed = 0;

function test(name, fn) {
  try {
    fn();
    passed++;
    console.log(`  ✓ ${name}`);
  }

mode-tracker stdin error handling\n');

// Load the REAL hook in a child, then emit an 'error' on process.stdin to
// simulate an abnormal close. stdin is left open (never closed) so the only
// event that fires is the injected 'error' — isolating the hand

 catch (e) {
    failed++;
    console.error(`  ✗ ${name}`);
    console.error(`    ${e.message}`);
  }
}

console.log('caveman-


>
	 * This method handles the transmission of messages to the server in an asynchronous
	 * manner. Messages are sent in JSON-RPC format as specified by the MCP protocol.
	 * </p>
	 * @param message the {@link JSONRPCMessage} to be sent to the server
	 * @

been sent
	 */
	Mono<Void> sendMessage(JSONRPCMessage message);

	/**
	 * Unmarshals the given data into an object of the specified type.
	 * @param <T> the type of the object to unmarshal
	 * @param data the data to unmarshal
	 * @param typeRef the type r

return a {@link Mono<Void>} that completes when the message has


oad_dotenv

load_dotenv()

from browser_use import Agent, Browser, ChatBrowserUse
from browser_use.browser.events import AgentFocusChangedEvent, TabCreatedEvent
from browser_use.browser.watchdog_base import BaseWatchdog

CUSTOM_HEADERS = {
	'X-Custom-Auth'

Request-Source': 'browser-use-agent',
	'X-Trace-Id': 'example-trace-12345',
}

class CustomHeadersWatchdog(BaseWatchdog):
	"""Injects custom HTTP headers on every new tab and focus change.

	Listens to both TabCreatedEvent (new tabs) and AgentFocusChanged


e')
			is_visible = await element.is_visible()

			result_data = {
				'selector': params.selector,
				'text_content': text_content,
				'inner_text': inner_text,
				'tag_name': tag_name,
				'is_visible': is_visible,
			}

		success_msg = f'✅ Extracted

 = f'❌ Playwright text extraction failed: {str(e)}'
		return ActionResult(error=error_msg)

async def main():
	"""
	Main function demonstrating Browser-Use + Playwright integration with custom actions.
	"""
	print('🚀 Advanced Playwright + Browser-Use Inte

text using Playwright: {result_data}'

		return ActionResult(
			extracted_content=str(result_data),
			include_in_memory=True,
			long_term_memory=f'Extracted from {params.selector}: {result_data["text_content"]}',
		)

	except Exception as e:
		error_msg


    return;
  }

  if (process.platform === 'win32') {
    spawn('taskkill', ['/pid', String(child.pid), '/t', '/f'], {
      stdio: 'ignore',
      windowsHide: true,
    }).on('error', () => {
      child.kill('SIGKILL');
    });
    return;
  }

  try

SIGKILL');
  } catch {
    child.kill('SIGKILL');
  }
}

function formatOutputTail(output: string): string {
  const lines = output.trimEnd().split(/\r?\n/);
  return lines.slice(-20).join('\n');
}

export function terminateActiveCliChildren(): void {
  fo


e).
- Delay Cursor support until its config stabilizes (partial accept): gate Cursor behind a feature flag until verified in real environments.

## Risks
- Tool configuration formats may change, requiring updates to wrappers/frontmatter.
- Incorrect paths

 add path existence checks and clear logging.
- Marker misuse (inside frontmatter) can break parsing; enforce placement rules in tests.

## Future Work
- Support additional editors/agents that expose slash command APIs.
- Allow users to customize command n


 {
    Ok(git::git_cmd()?
        .arg("ls-files")
        .arg("--stage")
        .arg("-z")
        .arg("--")
        .arg(if file_base.as_os_str().is_empty() {
            Path::new(".")
        } else {
            file_base
        })
        .check(

a Path> + 'a {
    stdout
        .split(|&b| b == b'\0')
        .filter_map(move |entry| parse_stage_entry(entry, file_base, filenames, executable))
}

fn parse_stage_entry<'a>(
    entry: &'a [u8],
    file_base: &Path,
    filenames: &FxHashSet<&Path>,

true)
        .output()
        .await?
        .stdout)
}

pub(super) fn matching_git_index_paths_by_executable_bit<'a>(
    stdout: &'a [u8],
    file_base: &'a Path,
    filenames: &'a FxHashSet<&Path>,
    executable: bool,
) -> impl Iterator<Item = &'


// StreamableRun returns a [schema.StreamReader] that yields string chunks
// incrementally. The caller (ToolsNode) is responsible for closing the reader.
type StreamableTool interface {
	BaseTool

	StreamableRun(ctx context.Context, argumentsInJSON string

 results.
//
// Unlike [InvokableTool], arguments arrive as a [schema.ToolArgument] (not a
// raw JSON string) and the result is a [schema.ToolResult] which can carry
// text, images, audio, video, and file content.
//
// When a tool implements both a stan

, opts ...Option) (*schema.StreamReader[string], error)
}

// EnhancedInvokableTool is a tool that returns structured multimodal


.com/login")
    email = await page.must_get_element_by_prompt("username field", llm=llm)
    await email.fill("your-username")

    # Agent: AI-driven completion
    agent = Agent(browser=browser, llm=llm)
    await agent.run("Complete login and navigate

Execution

```python
title = await page.evaluate('() => document.title')
result = await page.evaluate('(x, y) => x + y', 10, 20)
stats = await page.evaluate('''() => ({
    url: location.href,
    links: document.querySelectorAll('a').length
})''')
```

##

to repositories")

    await browser.stop()
```

### JavaScript


rink-0",
  {
    variants: {
      variant: {
        default: "bg-transparent",
        icon: "flex size-8 shrink-0 items-center justify-center rounded-md bg-muted text-foreground [&_svg:not([class*='size-'])]:size-4",
      },
    },
    defaultVariants:

  className,
  variant = "default",
  ...props
}: React.ComponentProps<"div"> & VariantProps<typeof emptyMediaVariants>) {
  return (
    <div
      data-slot="empty-icon"
      data-variant={variant}
      className={cn(emptyMediaVariants({ variant, clas

 {
      variant: "default",
    },
  }
)

function EmptyMedia({


dentity(accessToken: string): Promise<string> {
  try {
    const whoami = await fetchWhoami(accessToken);
    const name = whoami.email || whoami.name;
    if (!name) return "Login successful!";
    const team = whoami.teamspace?.name;
    return team

  : `Logged in as ${pc.bold(name)}`;
  } catch {
    return "Login successful!";
  }
}

export async function performLogin(openBrowser = true): Promise<string | null> {
  const spinner = ora("Preparing login...").start();

  let authorization;
  try {

? `Logged in as ${pc.bold(name)} ${pc.dim(`(${team})`)}`


al
	from browser_use.llm.oci_raw.chat import ChatOCIRaw
	from browser_use.llm.ollama.chat import ChatOllama
	from browser_use.llm.openai.chat import ChatOpenAI
	from browser_use.llm.vercel.chat import ChatVercel

_LAZY_IMPORTS = {
	'Browser': ('browser_use

BrowserProfile': ('browser_use.browser', 'BrowserProfile'),
	'BrowserSession': ('browser_use.browser', 'BrowserSession'),
	'ChatOpenAI': ('browser_use.llm.openai.chat', 'ChatOpenAI'),
	'ChatGoogle': ('browser_use.llm.google.chat', 'ChatGoogle'),
	'ChatAnth


rgs);
			return this;
		}

		public Builder args(List<String> args) {
			Assert.notNull(args, "The args can not be null");
			this.args = new ArrayList<>(args);
			return this;
		}

		public Builder arg(String arg) {
			Assert.notNull(arg, "The arg can not

 Builder env(Map<String, String> env) {
			if (env != null && !env.isEmpty()) {
				this.env.putAll(env);
			}
			return this;
		}

		public Builder addEnvVar(String key, String value) {
			Assert.notNull(key, "The key can not be null");
			Assert.notNull(

 be null");
			this.args.add(arg);
			return this;
		}

		public


i = f"data:{content_type};base64,{base64_image}"

        # Prepare the OpenAI API request
        messages = [
            {
                "role": "user",
                "content": [
                    {"type": "text", "text": prompt},

type": "image_url",
                        "image_url": {
                            "url": data_uri,
                        },
                    },
                ],
            }
        ]

        # Call the OpenAI API
        response = client.ch


ge: error instanceof Error ? error.message : "network error",
    };
  }

  if (response.ok) {
    const tokens = (await response.json()) as TokenData;
    return { status: "approved", tokens };
  }

  // Treat any 5xx as transient so a flaky backend doesn

(response.status >= 500) {
    const err = (await response.json().catch(() => ({}))) as TokenErrorResponse;
    return {
      status: "transient",
      errorMessage: err.error_description || err.error || `HTTP ${response.status}`,
    };
  }

  const err


d
			fingerprints, err := testHub.FindRecordsByFilter("fingerprints", "system = {:system}", "", -1, 0, map[string]any{"system": system.Id})
			require.NoError(t, err)
			require.Len(t, fingerprints, 1)
			fingerprint := fingerprints[0]

			// Verify token

empty and is a valid UUID format
				assert.NotEmpty(t, actualToken, tc.description)
				assert.Len(t, actualToken, 36, "Generated token should be UUID format") // UUID length
			} else {
				assert.Equal(t, tc.expectToken, actualToken, tc.description)

			actualToken := fingerprint.GetString("token")
			if tc.expectToken == "" {
				// For generated tokens, just verify it's not


t INDEPENDENT_MODES = new Set(['commit', 'review', 'compress']);

// opencode resolves its config dir from $XDG_CONFIG_HOME, else ~/.config/opencode
// on every platform — including Windows, where it uses %USERPROFILE%\.config\opencode
// (NOT %APPDATA%).

.homedir(), '.config', 'opencode');
}

const flagPath = path.join(opencodeConfigDir(), '.caveman-active');

function reinforcementLine(mode) {
  return 'CAVEMAN MODE ACTIVE (' + mode + '). ' +
    'Drop articles/filler/pleasantries/hedging. Fragments OK. '

os.homedir() is %USERPROFILE% on win32, so the default branch
// is already correct cross-platform.
function opencodeConfigDir() {
  if (process.env.XDG_CONFIG_HOME) {
    return path.join(process.env.XDG_CONFIG_HOME, 'opencode');
  }
  return path.join(os


"):
        _replace_equations(tag)
    return str(soup).encode()

def pre_process_docx(input_docx: BinaryIO) -> BinaryIO:
    """
    Pre-processes a DOCX file with provided steps.

    The process works by unzipping the DOCX file in memory, transforming

 converting OMML elements to LaTeX), and then zipping everything back into a
    DOCX file without writing to disk.

    Args:
        input_docx (BinaryIO): A binary input stream representing the DOCX file.

    Returns:
        BinaryIO: A binary output


   required: true,
            positional: true,
            help: '回复ID'
        },
        {
            name: 'fid',
            required: true,
            help: '板块ID（如278汽车区）'
        }
    ],
    columns: ['status', 'message'],
    func: async (page

 const url = 'https://bbs.hupu.com/pcmapi/pc/bbs/v1/reply/cancelLight';
        // 构建请求体（与点赞相同）
        const body = {
            tid,
            pid,
            puid: '',
            fid,
            shumei_id: '',
            deviceid: ''
        };

, kwargs) => {
        const { tid, pid, fid } = kwargs;


mmit, etc.) — not
// selectable via /caveman <arg>.
const INDEPENDENT_MODES = new Set(['commit', 'review', 'compress']);

const claudeDir = process.env.CLAUDE_CONFIG_DIR || path.join(os.homedir(), '.claude');
const flagPath = path.join(claudeDir, '.caveman

prompt can restore it (#599).
const prevPath = path.join(claudeDir, '.caveman-active.prev');

let input = '';
process.stdin.on('data', chunk => { input += chunk; });
// Abnormal stdin close (broken pipe, parent crash) emits 'error'; without a
// listener N

-active');
// Remembers the prose mode active before a one-shot independent mode
// (/caveman-commit etc.) so the next ordinary


se rig::providers::openai;
use rig::tool::{DynamicTool, ToolOutput};
use serde::Deserialize;
use serde_json::json;

#[derive(Deserialize)]
struct OperationArgs {
    x: i32,
    y: i32,
}

fn runtime_tools() -> Vec<DynamicTool> {
    let parameters = json!

     "properties": {
            "x": { "type": "integer" },
            "y": { "type": "integer" }
        },
        "required": ["x", "y"]
    });
    vec![
        DynamicTool::new(
            "add",
            "Add x and y",
            parameters.c


DEBUG] Agent.run() failed with error: {str(agent_error)}',
				file=sys.stderr,
			)
			print(f'[DEBUG] Error type: {type(agent_error).__name__}', file=sys.stderr)
			# Re-raise to be caught by outer try-catch
			raise agent_error

		agent_output = history

DEBUG] Agent execution completed', file=sys.stderr)

		# Test if LLM is working by making a simple call
		try:
			response = await agent_llm.ainvoke([UserMessage(content="Say 'test'")])
			print(
				f'[DEBUG] LLM test call successful: {response.completion


teIncomingMessage(subscribeRequest(RESOURCE_URI));
		transport.clearSentMessages();

		StepVerifier
			.create(server.notifyResourcesUpdated(new McpSchema.ResourcesUpdatedNotification("test://other/resource")))
			.verifyComplete();

		assertThat(transport

		MockMcpServerTransport transport = new MockMcpServerTransport();
		MockMcpServerTransportProvider transportProvider = new MockMcpServerTransportProvider(transport);
		McpAsyncServer server = buildServer(transportProvider);

		transportProvider.simulateI

.getAllSentMessages())
			.as("notification for a different URI should not reach a session subscribed to a different URI")
			.isEmpty();

		server.closeGracefully().block();
	}

	@Test
	void notifyResourcesUpdated_afterUnsubscribe_doesNotNotifySession() {


 explicit default.
			# Use a type-appropriate zero value for primitives/arrays;
			# fall back to None (with | None) for enums and nested objects
			# where no in-set or constructible default exists.
			json_type = prop_schema.get('type', 'string')
			if

't pick an arbitrary enum member as default — use None
				# so absent fields serialize as null, not an out-of-set value.
				prop_type = prop_type | None
				default = None
			elif json_type in _PRIMITIVE_DEFAULTS:
				default = _PRIMITIVE_DEFAULTS[json_t


P.get(json_type, str)

	# Nullable
	if schema.get('nullable', False):
		return base | None

	return base

_PRIMITIVE_DEFAULTS: dict[str, Any] = {
	'string': '',
	'number': 0.0,
	'integer': 0,
	'boolean': False,
}

def _build_model(schema: dict, name: str

type JSON Schema node."""
	_check_unsupported(schema)

	properties = schema.get('properties', {})
	required_fields = set(schema.get('required', []))
	fields: dict[str, Any] = {}

	for prop_name, prop_schema in properties.items():
		prop_type = _resolve_typ

) -> type[BaseModel]:
	"""Build a pydantic model from an object-


 step_end_time=1.0, step_interval=None)
	assert metadata_none.step_interval is None

	# Omitted (defaults to None)
	metadata_default = StepMetadata(step_number=0, step_start_time=0.0, step_end_time=1.0)
	assert metadata_default.step_interval is None

def

Step 1): runs from 100.0 to 102.5 (duration: 2.5s)
	previous_start = 100.0
	previous_end = 102.5
	previous_duration = previous_end - previous_start

	# Current step (Step 2): should have step_interval = previous step's duration
	# This tells the rerun syst

test_step_interval_calculation():
	"""Test step_interval calculation logic (uses previous step's duration)"""
	# Previous step (


g",
    "pct",
    "bmp",
    "gif",
    "jpg",
    "jpeg",
    "png",
    "pst",
    "psp",
    "tif",
    "tiff",
    "ai",
    "drw",
    "dxf",
    "eps",
    "ps",
    "svg",
    "cdr",
    "ico",
    "webp",
    # audio
    "mp3",
    "wma",
    "ogg

",
    "mid",
    "au",
    "aiff",
    # video
    "3gp",
    "asf",
    "asx",
    "avi",
    "mov",
    "mp4",
    "mpg",
    "qt",
    "rm",
    "swf",
    "wmv",
    "m4a",
    "m4v",
    "flv",
    "webm",
    # office suites
    "xls",
    "xlsm",


ort com.fasterxml.jackson.databind.DeserializationConfig;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializationConfig;
import com.fasterxml.jackson.

.databind.ser.BeanSerializerModifier;
import io.unitycatalog.server.delta.model.DeltaDataType;
import io.unitycatalog.server.delta.model.DeltaDecimalType;
import io.unitycatalog.server.delta.model.DeltaPrimitiveType;
import io.unitycatalog.server.delta.ser

databind.deser.BeanDeserializerModifier;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson


th variables ($PSCommandPath / $MyInvocation.MyCommand.Path)
//      are $null under iex — any use must be guarded, never passed straight
//      into Split-Path (that was the #565 crash).

import { test } from 'node:test';
import assert from 'node:assert/

import { fileURLToPath } from 'node:url';

const HERE = path.dirname(fileURLToPath(import.meta.url));
const REPO_ROOT = path.resolve(HERE, '..', '..');
const PS1 = fs.readFileSync(path.join(REPO_ROOT, 'install.ps1'), 'utf8');

// Strip comment lines so do

strict';
import fs from 'node:fs';
import path from 'node:path';


t string
}

func (s *Store) Delete(ctx context.Context, key string) error {
	normKey := strings.ReplaceAll(key, ":", "/")
	// Emulate not found by probing first.
	if _, err := s.s3.HeadObject(ctx, &s3.HeadObjectInput{Bucket: &s.bucket, Key: &normKey}); err

w: %w", store.ErrNotFound, err)
	}
	if _, err := s.s3.DeleteObject(ctx, &s3.DeleteObjectInput{Bucket: &s.bucket, Key: &normKey}); err != nil {
		return fmt.Errorf("can't delete from s3: %w", err)
	}
	return nil
}

func (s *Store) Get(ctx context.Context, k


dflare's DNS-over-HTTPS to prevent DNS leaks when using proxies.
        :param useragent: Pass a useragent string to be used. Otherwise the fetcher will generate a real Useragent of the same browser and use it.
        :param cookies: Set cookies for the

timeout in milliseconds that is used in all operations and waits through the page. The default is 30,000
        :param wait: The time (milliseconds) the fetcher will wait after everything finishes before closing the page and returning the Response object.

next request.
        :param network_idle: Wait for the page until there are no network connections for at least 500 ms.
        :param load_dom: Enabled by default, wait for all JavaScript on page(s) to fully load and execute.
        :param timeout: The


 `let vendor_id: Option<u16> = None` |
| `fn route(level: &str)` with fallback | Typos silently default | `let level: DiagLevel = s.parse()?` |
| `Builder::new().finish()` without fields | Incomplete object constructed | Typestate builder: `finish()` gated

|
| Raw `unsafe { ptr::read(...) }` scattered | UB risk, unauditable | `MmioRegion::read_u32()` safe wrapper |
| `async fn transition(&mut self)` | Mutable borrows don't enforce state | `async fn transition(self) -> NextState` |
| `fn cleanup()` called man

 on `Set` |
| `let buf: Vec<u8>` for fixed-size HW buffer | Size only checked at runtime | `RegisterBank<4096>` (const generic)


 it in a
      // command snippet; have the agent wire it up by hand instead.
      output += "\n\n" +
        "STATUSLINE SETUP NEEDED: The ponytail plugin includes a statusline badge showing active mode. " +
        "Its install path contains characters

. " +
        "Proactively offer to set this up for the user on first interaction.";
    }
  }
} catch (e) {
  // Silent fail — don't block session start over statusline detection
}

try {
  writeHookOutput('SessionStart', mode, output);
} catch (e) {
  //

unsafe to embed in a shell command, so configure it manually: " +
        "add a statusLine command of type \"command\" that runs " + scriptName +
        " from the plugin's hooks directory to " + settingsPath + ", quoting/escaping the path for your shell


   def urls(self, httpbin):
        url = httpbin.url
        return {
            "status_200": f"{url}/status/200",
            "status_404": f"{url}/status/404",
            "status_501": f"{url}/status/501",
            "basic_url": f"{url}/get",

url}/delay/10",  # 10 Seconds delay response
            "cookies_url": f"{url}/cookies/set/test/value"
        }

    async def test_basic_fetch(self, fetcher, urls):
        """Test doing a basic fetch request with multiple statuses"""
        assert (aw

       "html_url": f"{url}/html",
            "delayed_url": f"{


        assert client.__aexit__ is None

    @pytest.mark.asyncio
    async def test_session_level_proxy_is_applied(self):
        """Session-level proxy must reach the request, not be silently dropped (#295)"""
        proxy = "http://10.255.255.1:9999"

            with (
                patch.object(session._async_curl_session, "request", new=AsyncMock()) as mocked_request,
                patch("scrapling.engines.static.ResponseFactory.from_http_request", return_value=MagicMock()),
            ):

async with AsyncFetcherSession(proxy=proxy) as session:


lue(args).map_err(|error| {
                        rig::tool::ToolExecutionError::invalid_args(error.to_string())
                            .with_source(error)
                    })?;
                    Ok(ToolOutput::json(json!(args.x - args.y)))

::from_env()?
        .agent(openai::GPT_4O)
        .preamble(
            "You are a calculator here to help the user perform arithmetic operations. \
             You must use the provided tools before answering.",
        )
        .dynamic_tools(runti

             })
            },
        ),
    ]
}

#[tokio::main]
async fn main() -> Result<()> {
    let agent = openai::Client


tLevel(logging.INFO)

    formatter = logging.Formatter(fmt="[%(asctime)s] %(levelname)s: %(message)s", datefmt="%Y-%m-%d %H:%M:%S")

    console_handler = logging.StreamHandler()
    console_handler.setFormatter(formatter)

    # Add handler to logger (if

 ContextVar[logging.Logger] = ContextVar("scrapling_logger", default=setup_logger())

class LoggerProxy:
    def __getattr__(self, name: str):
        return getattr(_current_logger.get(), name)

log = LoggerProxy()

def set_logger(logger: logging.Logge

 not already added)
    if not logger.handlers:
        logger.addHandler(console_handler)

    return logger

_current_logger:


istral
	from browser_use.llm.oci_raw.chat import ChatOCIRaw
	from browser_use.llm.ollama.chat import ChatOllama
	from browser_use.llm.openai.chat import ChatOpenAI
	from browser_use.llm.vercel.chat import ChatVercel

_LAZY_IMPORTS = {
	'Browser': ('browser

.browser', 'BrowserSession'),
	'ChatOpenAI': ('browser_use.llm.openai.chat', 'ChatOpenAI'),
	'ChatGoogle': ('browser_use.llm.google.chat', 'ChatGoogle'),
	'ChatAnthropic': ('browser_use.llm.anthropic.chat', 'ChatAnthropic'),
	'ChatBrowserUse': ('browser_us

_use.browser', 'BrowserSession'),
	'BrowserProfile': ('browser_use.browser', 'BrowserProfile'),
	'BrowserSession': ('browser_use


n).not.toHaveBeenCalled();
  });

  test("explains ephemeral runners instead of trying to self-upgrade", async () => {
    checkForUpdates.mockResolvedValue({
      currentVersion: "0.3.13",
      latestVersion: "0.3.99",
      updateAvailable: true,

includes("ephemeral runner"))).toBe(true);
    expect(plainLogOutput().some((line) => line.includes("npx ctx7@latest <command>"))).toBe(true);
    expect(spawn).not.toHaveBeenCalled();
  });

  test("runs the upgrade command with --yes when possible", asyn

 installMethod: "npx",
      upgradePlan: {
        displayCommand: "npx ctx7@latest <command>",
        canRun: false,
        needsExplicitVersion: true,
      },
    });

    await runCommand("upgrade");

    expect(plainLogOutput().some((line) => line.


2h_s += sizeof(U256), zmmh_d += 1)
      {
        MemoryCopy(&zmmh_d->u8[32], avx512h_s, sizeof(U256));
      }
    }

    // rjf: zmm
    DWORD avx512_length = 0;
    U8 *avx512_s = (U8 *)LocateXStateFeature(ctx, XSTATE_AVX512_ZMM, &avx512_length);

d = &dst->zmm16;
      for(U32 n = 0; n < 16; n += 1, avx512_s += sizeof(U512), zmm_d += 1)
      {
        MemoryCopy(zmm_d, avx512_s, sizeof(U512));
      }
    }
  }

  // CET / Shadow Stack
  if(xstate_mask & XSTATE_MASK_CET_U)
  {
    DWORD cet_leng

   if(avx512_length == 16 * sizeof(U512))
    {
      U512 *zmm_


 kwargs) => {
        const userId = normalizeXhsUserId(String(kwargs.id));
        const limit = parseLimit(kwargs.limit);
        await page.goto(`https://${WEB_HOST}/user/profile/${userId}`);
        let snapshot = await page.evaluate(USER_SNAPSHOT_JS);

         await page.wait({ time: 1 });
            snapshot = await page.evaluate(USER_SNAPSHOT_JS);
            const nextResults = extractXhsUserNotes(snapshot ?? {}, userId, WEB_HOST);
            if (nextResults.length <= previousCount)

        let results = extractXhsUserNotes(snapshot ?? {}, userId, WEB_HOST);
        let previousCount = results.length;
        for (let i = 0; results.length < limit && i < 4; i += 1) {
            await page.autoScroll({ times: 1, delayMs: 1500 });


gisteredModel;
import io.unitycatalog.client.model.ModelVersionInfo;
import io.unitycatalog.client.model.RegisteredModelInfo;
import io.unitycatalog.client.model.SecurableType;
import io.unitycatalog.client.model.UpdateModelVersion;
import io.unitycatalog.

jupiter.api.Test;

/**
 * SDK-based access control tests for Registered Model and Model Version CRUD operations.
 *
 *
This test class verifies:
 *
 *

 *
Model creation requires CREATE MODEL permission on schema
 *
Model get requires ow

client.model.UpdateRegisteredModel;
import io.unitycatalog.server.base.ServerConfig;
import io.unitycatalog.server.persist.model.Privileges;
import io.unitycatalog.server.utils.TestUtils;
import java.util.List;
import lombok.SneakyThrows;
import org.junit.


s.notExists(keyId)) {
      log.info("Initializing security configuration.");
      KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
      keyPairGenerator.initialize(2048);
      KeyPair keyPair = keyPairGenerator.generateKeyPair()

Files.write(rsa512PublicKey, keyPair.getPublic().getEncoded(), StandardOpenOption.CREATE);
      Files.write(rsa512PrivateKey, keyPair.getPrivate().getEncoded(), StandardOpenOption.CREATE);

      byte[] keyIdBytes = new byte[32];
      new SecureRandom().

;

      // Create parent directory first if it does not exist
      Path parentDirectory = rsa512PublicKey.getParent();
      if (parentDirectory != null && !Files.exists(parentDirectory)) {
        Files.createDirectories(parentDirectory);
      }


_prompt: Arc::new(Mutex::new(None)),
                seen_response: Arc::new(Mutex::new(None)),
            };

            let response = agent.prompt("Entertain me!").add_hook(hook.clone()).await?;

            assert_nonempty_response(&response);

       hook.prompt_calls.load(Ordering::SeqCst) == 1,
                "expected one prompt hook call"
            );
            anyhow::ensure!(
                hook.response_calls.load(Ordering::SeqCst) == 1,
                "expected one response hook c


e=MagicMock()),
            ):
                await session.get("http://example.com")

            assert mocked_request.call_args.kwargs["proxy"] == proxy

    @pytest.mark.asyncio
    async def test_per_request_proxy_overrides_session_proxy(self):

.object(session._async_curl_session, "request", new=AsyncMock()) as mocked_request,
                patch("scrapling.engines.static.ResponseFactory.from_http_request", return_value=MagicMock()),
            ):
                await session.get("http://exam

   """A per-request proxy must take precedence over the session-level proxy"""
        request_proxy = "http://10.255.255.2:9999"

        async with AsyncFetcherSession(proxy="http://10.255.255.1:9999") as session:
            with (
                patch


 fn description(&self) -> String {
        "Add x and y together".to_string()
    }

    fn parameters(&self) -> serde_json::Value {
        json!({
            "type": "object",
            "properties": {
                "x": {
                    "type"

       "type": "number",
                    "description": "The second number to add"
                }
            }
        })
    }

    async fn call(
        &self,
        _context: &mut rig::tool::ToolContext,
        args: Self::Args,
    ) -> Res

: "number",
                    "description": "The first number to add"
                },
                "y": {


    {...props}
    />
  )
}

function CommandDialog({
  title = "Command Palette",
  description = "Search for a command to run...",
  children,
  className,
  showCloseButton = false,
  ...props
}: Omit<React.ComponentProps<typeof Dialog>, "children"> & {

: string
  className?: string
  showCloseButton?: boolean
  children: React.ReactNode
}) {
  return (
    <Dialog {...props}>
      <DialogHeader className="sr-only">
        <DialogTitle>{title}</DialogTitle>
        <DialogDescription>{description}</Dial


clude.NON_NULL)
@JsonPropertyOrder(
    value = {
      "workflow_id",
      "workflow_version_id",
      "workflow_instance_id",
      "workflow_run_id",
      "step_id",
      "step_attempt_id",
      "create_time"
    },
    alphabetic = true)
@Builder

 String stepId;
  private final long workflowVersionId;
  private final long workflowInstanceId;
  private final long workflowRunId;
  private final long stepAttemptId;
  private final long createTime;

  /** builder class for lombok and jackson. */
  @Jso

@Getter
@EqualsAndHashCode
public class PausedStepAttempt {
  @NotNull private final String workflowId;
  @NotNull private final


nt = path.dirname(dir);
      if (parent === dir) return null;
      dir = parent;
    }
  } catch (e) {
    // Defensive: any cwd / fs failure → no repo config
  }
  return null;
}

function readModeFromConfigFile(configPath) {
  try {
    const raw = fs.

raw);
    if (config && config.defaultMode &&
        VALID_MODES.includes(String(config.defaultMode).toLowerCase())) {
      return String(config.defaultMode).toLowerCase();
    }
  } catch (e) {
    // Missing / unreadable / invalid JSON → caller falls t

readFileSync(configPath, 'utf8');
    const config = JSON.parse(


ls.FileOperations;
import io.unitycatalog.server.utils.ServerProperties;
import lombok.Getter;
import org.hibernate.SessionFactory;

/**
 * Each server instance has a set of repositories that are used to interact with the database. This
 * class is used to

are then shared across the server instance.
 */
@Getter
public class Repositories {
  private final SessionFactory sessionFactory;
  private final FileOperations fileOperations;
  private final ExternalLocationUtils externalLocationUtils;

  private final


(realDir).toLowerCase();
          const normalizedHome = path.resolve(home).toLowerCase();
          if (!normalized.startsWith(normalizedHome + path.sep) && normalized !== normalizedHome) return;
        }
      } else {
        realDir = dir;
      }

  }

    const realPath = path.join(realDir, path.basename(filePath));
    try {
      if (fs.lstatSync(realPath).isSymbolicLink()) return;
    } catch (e) {
      if (e.code !== 'ENOENT') return;
    }

    const O_NOFOLLOW = typeof fs.constants.O_NOFOLLO


     List.of(
                    new FunctionParameterInfo()
                        .name("param1")
                        .typeName(ColumnTypeName.INT)
                        .typeText("int")
                        .typeJson("{\"type\":\"int\"}")

_NAME)
            .catalogName(CATALOG_NAME)
            .schemaName(SCHEMA_NAME)
            .parameterStyle(CreateFunction.ParameterStyleEnum.S)
            .isDeterministic(true)
            .comment(COMMENT)
            .externalLanguage("python")

                     .position(0)));
    CreateFunction createFunction =
        new CreateFunction()
            .name(FUNCTION


].url == "https://example.com/sitemap.xml"
        assert out[0].callback == spider._parse_sitemap

    @pytest.mark.asyncio
    async def test_parse_sitemap_robots_with_no_directives_warns(self):
        # Spider's logger has propagate=False, so we attach

import logging

        class S(SitemapSpider):
            name = "s"
            sitemap_urls = ["https://example.com/robots.txt"]

        spider = S()
        records: list[logging.LogRecord] = []

        class _Capture(logging.Handler):
            d


esting.T) {
	ctx := context.Background()

	t.Run("basic interrupt", func(t *testing.T) {
		err := Interrupt(ctx, "test info")
		assert.Error(t, err)

		var signal *core.InterruptSignal
		assert.True(t, errors.As(err, &signal))
		assert.Equal(t, "test info"

signal.IsRootCause)
	})
}

func TestStatefulInterrupt(t *testing.T) {
	ctx := context.Background()

	t.Run("stateful interrupt", func(t *testing.T) {
		type myState struct {
			Value int
		}
		state := &myState{Value: 42}

		err := StatefulInterrupt(ctx, "


ys single-runtime.
//
// API: compress(text, opts?) → { compressed, before, after }
//
// Boundaries (NEVER touched):
//  - fenced code blocks (``` ... ```)
//  - inline code (`...`)
//  - URLs (https?://...)
//  - filesystem paths (anything with `/` or `\

like braces)
//  - identifiers in CamelCase / snake_case / dotted.path form
//
// Compression applied to everything else:
//  - drop articles (a, an, the)
//  - drop filler words (just, really, basically, actually, simply, quite, very)
//  - drop pleasantr

`)
//  - "code-looking" tokens (parens at end, semicolons, JSON-


ences SHALL be configuration-driven rather than separate duplicated loops

#### Scenario: Legacy upgrade path reuses engine

- **WHEN** legacy cleanup triggers artifact regeneration
- **THEN** the regeneration path SHALL use the same shared engine
- **AND*

 the same transform and validation rules

### Requirement: Fidelity Guardrails

The system SHALL enforce guardrails that prevent output drift during refactors.

#### Scenario: Projection parity checks

- **WHEN** CI runs template generation tests
- **THEN*


ut += chunk; });
process.stdin.on('end', finish);

// Never hang the session. On Windows, Claude Code runs this hook through a
// PowerShell `if {}` wrapper that can swallow the piped prompt JSON, so stdin
// 'end' never fires and the hook blocks forever —

 On error, or after a short fallback, process whatever arrived (recovering the
// mode if data came without EOF) and exit. unref() keeps the timer from adding
// latency to the normal path, where 'end' fires first. Mirrors the best-effort,
// never-block c


? Answer with only the number.")
        .max_tokens(2048)
        .additional_params(adaptive_thinking_params())
        .build();
    let mut stream = model
        .stream(request)
        .await
        .expect("adaptive-thinking Bedrock stream should

chunks = 0;
    let mut signature_chunks = 0;
    let mut signature_only_chunks = 0;
    let mut got_final = false;

    while let Some(item) = stream.next().await {
        match item.expect("adaptive-thinking Bedrock stream item should succeed") {


200"
        self.status_404 = f"{httpbin.url}/status/404"
        self.status_501 = f"{httpbin.url}/status/501"
        self.basic_url = f"{httpbin.url}/get"
        self.html_url = f"{httpbin.url}/html"
        self.delayed_url = f"{httpbin.url}/delay/10

       self.cookies_url = f"{httpbin.url}/cookies/set/test/value"

    def test_session_creation(self):
        """Test if the session is created correctly"""

        with StealthySession(
            headless=True,
            disable_resources=True,